Linux, OpenSource, Programming And Hacks

Aug 28, 2015

How to Auto Indent a Program: Vim Tips & Tricks

Aug 28, 2015
In this tutorial we will see automatic vim editor indentation tips and more. Indentation makes a program readable as well as neat and organised. In python programming language indentation is used instead of curly braces or keywords which make code neat and concise. follow this tutorial and your coding life will become a little easier :)

Note: If you haven't used vim before then see some vim basics HERE

Automatically Indent a whole program!

Let's say you made a 100 line code but didn't care to indent it. Here is how to do it in a very simple way.

I have a c program for insertion sort which i didn't care to indent. let's open it in vim editor.
vi program.c

then press esc key and then the following


where gg is start of the file, = is to indent and G is to end of the file

There you go! easily done!

save changes and exit vim.

This trick will work in most of the programming languages like java, perl, c, c++, bash, javascript, php... but in python the indentation won't be as expected because no curly braces are used in python and of course vim won't what lines belong to which block of the code.

I have set my tab size to 4 (default is 8), which reduces the indent size to 4. even you can do so by this command

:set ts=4

 Some More Useful Tips: 

Copy/paste code correctly

When you copy and paste code from somewhere into vim the code gets arranged with incorrect spacing. So, whenever you are pasting a code into vim editor first press esc and enter the following command to set paste mode and then paste the copied stuff.

:set paste

and after you have pasted the code come back to normal mode

:set nopaste

Indent a line or multiple lines at once

press esc key and goto the line which you wanna indent

Now enter the following key combination

indent to left
>> (greater than key two times)

indent to right
<< (less than key two times)

if you wanna indent multiple lines then give no. of lines to indent, such as 4, (indent 4 lines) and then >> or <<

in short
n>> or n<< where n is the no. of lines to indent from the current position.

by default the indentation will be 8 spaces. I prefer 4, enter this command to make it 4.

:set sw=4

Enable auto indentation

The command below will keep the cursor to the same column when enter key is pressed to change the line.

:set ai

Note: the changes that you have made with the :set command will go away when vim editor is closed. if you want these changes to persist then you have to save these commands in .exrc file.

Create a file named .exrc in your home directory (if it's not there already) and write all your set commands in that file( do not give the colon (:) before set). save and exit. The dot (.) before the filename makes it hidden. To view all hidden files press Ctrl+h

No comments:

Post a Comment