Many times I run across a situation where a line is not indented properly. Ether through a paste, bad / not preferred indent plugin, or most often extra spaces offsetting the indent value. I usually fix this by << or >> the line a few times to fix it up. In the case of extra spaces I'll do a 100<< then a >> for each indent level I actually want.

The question is, like the | motion that lets you set the column by number 10| sends the cursor to the 10th column. How can I specify the indent level?

An example (this does not work) with shiftwidth=4 expandtab:

The quick (indent level 0)
••••Brown Fox (indent level 1)
••••••••••Jumped over the lazy dog (indent level 2 with two extra spaces)

In this case I currently have to count the indent level of the last line (2) and add one for the extra spaces then type 3<< then count the indent level of what I then 1>> (or use autoindent and == command).

I'm asking for something like 1== to force the indent to be indent level 1. Or in some cases 0== for removing an indent all together.

I realize the above example does auto indenting on 1 or 0 lines (respectively) and so does not do what I'd like but hoped it would help illustrate the question better.


You can use the :left command:

:[range]le[ft] [indent]
Left-align lines in [range]. Sets the indent in the lines to [indent] (default 0). {not in Vi}

Note that :left sets the indent to n spaces, and is not aware of shiftwidth or tabstop, so using :left 8 will use 8 spaces.

If you want to set the indentation level, you can easily define a command:

command! -nargs=1 Left execute 'left ' . &sw * <args>

Use :Left 2 will set the indentation to 8 spaces.

To map this to <Leader>=, you could use:

noremap <expr> <Leader>= ':left ' . str2nr(nr2char(getchar())) * &sw . '<CR>'

I'm not sure if this is the best way, but it's the only way I can manage... \=2 will indent the current line to 8 spaces, and 5\=3 will indent the next 5 lines to 12 spaces.

A related hint that also solves your problem is setting the shiftround option. From :help 'shiftround'

Round indent to multiple of 'shiftwidth'. Applies to > and < commands. CTRL-T and CTRL-D in Insert mode always round the indent to a multiple of 'shiftwidth' (this is Vi compatible).

In your example, the first << will "round" to 8 spaces. So your problem (using 3<< and then >>) is solved. And as the help page says, you can also use <C-d> from insert mode.

  • Awesome! These solutions work perfect. – Sukima Mar 7 '15 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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