set vim indentation

How to Set Indentation in Vim

Vim is a popular text editor used in Linux. Sometimes you may need to set indentation in vim editor. This is useful especially if you are a python programmer. In this article, we will learn several ways to do this in Linux.


How to Set Indentation in Vim

Here are the steps to set indentation in Vim editor.


Modifying vimrc file

One of the simplest ways to set indentation is to modify the .vimrc file which is the configuration file for vim editor. Open it in vim editor.

$ vi ~/.vimrc

Add the following line to it.

set autoindent expandtab tabstop=2 shiftwidth=2

Save and close the file. Close and re-open vi editor to apply changes. If the changes are still not applied, reload the configuration file using the following command.

$ source ~/.vimrc

Let us look at the above command that we have saved in .vimrc file.


Set Autoindent

In the above line we use ‘set autoindent’ so that when you press Enter key to go to next line, vim editor automatically indents it.


Using Spaces for Indentation

Here are 3 directives to set spaces for indentation in your code.

set expandtab
set tabstop=<NUM OF SPACES>
set shiftwidth=<NUM OF SPACES>

The first line ensures that indentation is done even if you hit the tab key. The second line enters the specified number of spaces when you do a line indentation. The third option will indent out or when you use >> or << to indent an already existing line of code.

Combining all directive in one line we use the following

set autoindent expandtab tabstop=2 shiftwidth=2

It is advisable to use 2 or 4 for tabstop and shiftwidth directives. Also, use the same value for both variables.


Using Tab for Indentation

On the other hand, if you want to use tabs for indentation, you can use the following configuration in .vimrc file.

set noexpandtab
set tabstop=4
set shiftwidth=4

The noexpandtab prevents conversion of tabs into spaces. In the above configuration, indentation is counted as 4 spaces.

In this article, we have learnt how to set indentation in vim editor.

Also read:

How to Show Progress in Rsync
How to Clean up Snap Packages in Linux
How to Fix Unacceptable TLS Certificate in Linux
How to Reconfigure Installed Packages in Ubuntu/Debian
Return False vs PreventDefault in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *