Search code examples
vimindentation

Indent few lines in vim with a fixed amount of spaces, here : three for example, without changing vim settings


I have a block that I need to indent 3 characters right.

Currently my vim has for default settings an indentation of eight characters, and I don't want to change it.

I need do to this in order to indent blocks that are sometimes under a

* .... 
- ...

For example, to have this output :

  • The wished output :

    The ouput I'm willing to see.
    
  • Instead of this one :

The one that isn't properly indented

There, keeping an indentation of eight character wouldn't word : markdown would not interpret the block correctly anymore.

What is the proper command to indent, let's say, the five lines from my cursor with 3 spaces ?

That makes

this
and this
and this
and this
and this

becoming :

   this
   and this
   and this
   and this
   and this

Solution

  • There are so many ways to do that…

    Method 0

    1. Use <C-v>{motion} to select the first column of each lines in visual-block mode.
    2. Prepend three spaces to the whole selection with I <Esc>.

    Method 1

    1. Visually select the block (the exact type of visual mode doesn't matter).
    2. Do :'<,'>norm I .

    Method 2

    Instead of starting from visual mode, which inserts the '<,'> range for you, use an explicit range. In this case, it could be: :1,5norm I , or :,+4norm I , or any other contextually valid range.

    Method 3

    Essentially the same starting point as the two methods above but with a substitution instead of :norm:

    :[range]s/^/   /
    

    Method 4

    1. Prepend the first line with three spaces: I .
    2. Move the cursor to the line below: j or <Down>.
    3. Repeat the last normal mode command with ..
    4. Etc.

    In short: I <Esc>j.j.j.j..

    Method 5

    A possibly more scalable variant of the above:

    1. Prepend the first line with three spaces: I .

    2. Move the cursor to the line below: j or <Down>.

    3. Visually select the remaining lines or use an explicit range to repeat the last normal mode command on the desired lines:

      :[range]norm .
      

    And so on…

    See :help motion.txt, the most mind-blowing part of the whole documentation, and :help user-manual for the easiest to follow and most comprehensive text editor tutorial ever.