5

I use two spaces in my indentation of codes. What are the possible ways to indent or unindent a block of code?

3 Answers 3

3

I use two spaces in my indentation of codes.

First off, you should set the 'shiftwidth' option to 2, to match the number of spaces you want to use as indentation. You will probably also want to set 'expandtab' so that Vim will keep using spaces for indentation once you get to 8 spaces (or whatever the tab size is set to.) So:

:set shiftwidth=2 expandtab

What are the possible ways to indent or unindent a block of code?

If you have the block visually selected, then you can use the > command to indent it and the < command to unindent it. You can pass these commands a "count" to indent/unindent the visual block by multiple shiftwidths.

In normal mode, you can use the > or < command followed by a motion to indent/unindent the lines covered by that motion.

You also have the >> or << commands to indent/unindent "count" lines (or a single line, without a count.)

These are a few of the ways in which you can indent/unindent an existing block. There are others available while you're in insert mode, either automatically (e.g. 'autoindent' or using indent expressions) or manually (Ctrl-T to indent, Ctrl-D to unindent, the TAB key can be set to indent by setting an option such as 'softtabstop' to match 'shiftwidth', etc.)

4

You can combine the > and < operators with % to indent blocks of code.

The % key will jump to the matching parenthesis, bracket or brace if your cursor is sitting on one of these characters: (, ), [, ], { or }.

For an example, say you have a block of code like this and you want to indent it:

{
  stuff here
}

To indent the code block, put the cursor on one of the braces (either one will work), type > followed by %.

1

:help left

In ex mode you can use :left or :le to align lines a specified amount. Specifically, :left will Left align lines in the [range]. It sets the indent in the lines to [indent] (default 0).

:%le3 or :%le 3 or :%left3 or :%left 3 will align the entire file by padding with three spaces.

:5 le 4 will pad line 5 with 4 spaces

:5,7 le 3 will align lines 5 through 7 by padding them with 3 spaces.

:le without any value or :le 0 will left align with a padding of 0.

This works in vim and gvim.

Source: https://stackoverflow.com/questions/235839/indent-multiple-lines-quickly-in-vi/32509423#32509423

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.