Vim Recipes Editing Indenting Lines

Indenting Lines

Problem

You want to use whitespace (spaces or tabs) to indent lines from the left margin.

For example, you may want to start your paragraphs with an indented first line. Or, if you're writing program source code, you may want to visually represent the structure of your program by using indentation to show nesting.

Solution

To start a line indented, just press the tab key once for each level of indentation.

To indent existing lines, highlight them visually and press > to indent or < to unindent.

If you're in Insert or Replace mode you can use <Ctrl>-<Shift>-t to indent (mnemonic: tab), and <Ctrl>-<Shift>-d to unident (mnemonic: de-tab/indent).

More powerful are motions combined with indent/unident commands. The syntax is >motion to indent the text described by motion, and <motion to unident it. For example, >ap indents the current paragraph.

Description

For many users, this solution will be sufficient. However, programmers regularly need more control over indentation because it's so important to their work.

The :set list command makes literal tabs visible. It displays them as ^I, and uses a similar notation for other non-printable characters. The $ symbol is used to show the end of lines.

A contentious issue among programmers involves how the tab key should work. There are two main schools of thought:

shiftwidth controls how many spaces are inserted when using the >>/<< technique described above, or the automatic indenting used with source code.

softtabstop specifies how many columns Vim uses when Tab is hit in Insert mode. If it's less than tabstop, and Vim's not expanding tabs (:set noexpandtab), Vim indents with tabs, padding with spaces where necessary.

(It can be seen, then, that you'll typically want to make softtabstop and shiftwidth equal, for reasons of consistency and sanity.)

The boolean expandtab option replaces tabs with spaces if true; leaves them alone if false.

These settings are not retroactive. To make an existing file honour your indentation preferences use the :retab! command.

See Also