hopefully this is not obvious, but: I know how to indent and unindent multiple lines via: 3>> (shift right) and 3<< (shift left).

The shift width is specified with 'shiftwidth'.

How can I easily achieve to indent unindent lines with one or two space characters (and not modifying shiftwidth)?

  • How can I improve the question? I see the downvoters, so, maybe a comment how to improve this? – stephanmg Sep 15 '20 at 15:47

You can use blockwise Visual mode to select a block of columns and insert text (such as one or two spaces) in front of the block. Likewise, you can also use blockwise Visual mode to delete one or two columns of spaces in order to unindent lines.

To add indentation:

  1. Go to the first line of the block.
  2. Use 0 (or ^) to move to the first column (or first character of the line.)
  3. Use Ctrl+V to enter blockwise Visual mode.
  4. Move down to the last line of your block. If you want to indent three lines, then you can use 2j.
  5. Use I to start Insert mode at the start of the visual.block. Then insert one or two spaces, and press <Esc>.

In order to remove indentation, you can use essentially the same procedure, just in step 2 make sure you use 0 to select columns of spaces, and in step 5 use x or d to delete the column and shift the lines left. If you wanted to delete two spaces of indentation, make the Visual block two columns wide, with the l motion, before you delete it.

See :help blockwise-visual and :help blockwise-operators.

  • I see, so I cannot use visual mode? This is what I was missing probably. – stephanmg Sep 15 '20 at 14:30
  • 1
    You need blockwise Visual mode to get the right effect in both cases. (Note that blockwise Visual mode is a Visual mode... But perhaps it's different from the "visual mode" you're referring to, which I imagine is character-wise or linewise visual mode.) – filbranden Sep 15 '20 at 14:34
  • 1
    Yes, I was assuming I could use v or V as well to select the lines, then do an I on these visually highlighted lines. But I presume if I am in linewise visual it will only apply to one line (current line)? – stephanmg Sep 15 '20 at 14:35
  • 1
    Yes that's correct. See :help v_b_I, you'll see the I command that inserts at the beginning of every line only applies to blockwise Visual mode. Blockwise Visual mode is a great tool in Vim! You might want to read through those help sections and experiment with it for a bit, it can solve very interesting problems, it's a great tool to add to your "Vim tool belt." – filbranden Sep 15 '20 at 14:39
  • 1
    Thanks, you are right. I almost forgot about block mode somehow, even though I remember I read about it already a decade ago. Kind regards. – stephanmg Sep 15 '20 at 14:43

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.