Vim Auto Indent Command


Vim is a modal text editor that allows users to alter text in different modes. These different modes determine how the alphanumeric keys on keyboards function.

Vim has an extremely powerful and flexible automatic indent option, indentexpr. Indentation may seem like an insignificant step when coding, but Vim makes it automatic with its indent option, indentexpr. This will save you time having to TAB to the right indentation on every line of code.

This makes indenting happen according to a particular expression. It’s particularly useful when used together with automatic filetype detection.

This powerful yet flexible tool indents based on expression. In this article, we will cover how to use the Vim auto indent command.

How to Turn On Vim Auto Indent

To turn Vim auto indent on, add this line to your ~/.vimrc:

filetype indent on

You can also use :filetype indent on in command mode once Vim has started, but this won’t persist between sessions.

Now, find out the detected type of your file with the command :set filetype. In the case of this file, it’s HTML. Check out /usr/share/vim/vimXX/indent/filetype.vim (where XX is the Vim version you’re running, and filetype is the filetype name). If the file is not there, try /usr/local/share. This file has the indent rules for your filetype, and you can edit them or add more rules if you don’t like them.

Similarly, you can create a set of indent rules for any filetype that isn’t already listed. Be sure to check out the Vim website first in case someone’s done it already.

Smartindent and autoindent offer a less sophisticated alternative to indentexpr. It’s also worth setting these in your ~/.vimrc, in case you have a file of a type that Vim doesn’t know. Use these lines:

set ai

set si

How to Turn Off Vim Auto Indent

You can also temporarily turn off automatic indenting by typing :set paste in command mode. (:unset paste to turn it back on again.) This is useful — as you might guess from the command name — if you’re pasting in chunks of text or code to avoid getting annoying extraneous indents.

Other Vim Indenting Variables

Here are some other helpful Vim indenting variables you may want to consider setting:

Set indenting to four spaces:

:set shiftwidth=4

Set stricter rules for C programs:

:set cindent

To stop indenting when pasting with the mouse. Finish the command by pressing the F5 key while in insert mode:

set pastetoggle=<f5>

Web hosting companies also use Vim Auto.