Previous: , Up: Electric Indent Mode   [Index]


8.10.1.2 Indenting the Current Line

When you press ‘TAB’, Emacs usually calls indent-for-tab-command, a generic proxy command that either indents your code or attempts to ‘TAB’-complete the word at the point.

indent-for-tab-command &optional ARG

Indent the current line or region, or insert a tab, as appropriate. This function either inserts a tab, or indents the current line, or performs symbol completion, depending on ‘tab-always-indent’. The function called to actually indent the line or insert a tab is given by the variable ‘indent-line-function’.

If a prefix argument is given, after this function indents the current line or inserts a tab, it also rigidly indents the entire balanced expression which starts at the beginning of the current line, to reflect the current line’s indentation.

If ‘transient-mark-mode’ is turned on and the region is active, this function instead calls ‘indent-region’. In this case, any prefix argument is ignored.

Some major modes override the ‘TAB’ key and instead call their own specialized indent command — one example is the C major mode.

However, pressing ‘TAB’ (or M-x indent-for-tab-command) will, if its heuristic determines that it should indent, call the indentation function stored in the variable indent-line-function.

The variable tab-always-indent governs Emacs’s behavior when you press ‘TAB’. Usually, it just indents but it also has a completion mechanism, though seldomly used.

If tab-always-indent is ‘t’, hitting ‘TAB’ always just indents the current line. If nil, hitting TAB indents the current line if point is at the left margin or in the line’s indentation, otherwise it inserts a "real" TAB character. If ‘complete’, TAB first tries to indent the current line, and if the line was already indented, then try to complete the thing at point.

If you dislike the use of tab characters and if you prefer whitespace, customize the variable indent-tabs-mode. Indentation can insert tabs if this is non-nil.

The variable tab-width controls how many characters of spacing each tab uses. It also controls the amount of whitespace to use if you disabled indent-tabs-mode.

Finally, when Emacs indents it calls the aforementioned function in indent-line-function. The default function is indent-relative, a command that inserts an actual tab character. Modes such as ‘text-mode’ and ‘fundamental-mode’ (the default mode for a new, empty buffer) uses indent-relative. Most programming modes do not.

Tab Stops

There is also the concept of tab stops in Emacs and you can edit the tab stops by typing M-x edit-tab-stops and inserting ‘:’ characters where you want Emacs to set the tab point. Subsequent calls to ‘M-i’ (which calls the command M-x tabs-to-tab-stop) then insert tab stops, by way of whitespace and tab characters.


Previous: Indenting New Lines, Up: Electric Indent Mode   [Index]