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.
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.
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
Some More Useful Tips:
Copy/paste code correctlyWhen 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.
and after you have pasted the code come back to normal mode
Indent a line or multiple lines at oncepress 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 <<
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.
Enable auto indentationThe command below will keep the cursor to the same column when enter key is pressed to change the line.
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