22

I tried visual block, but visual block only allow to highlight or delete characters on multiple lines.

Is there any function that allows to add space before the first character of multiple lines when I press spacebar?

1

3 Answers 3

30

You were right about visual mode, but you should have tried blockwise visual mode by pressing <C-V>.

In blockwise visual mode you can select the lines and columns of your selection. When you selected the desired lines of the block you want, you can press I (that is Shift + i), you are now on insert mode, where you can add space in front of your line.

When you press <ESC> the new spaces will be added to all lines of your selection.

1
7

To add a space at the beginning of mutliple lines you also can use the normal command. Let's say you have the following file:

" foo
" bar
buzz
fizz

You can select the lines you want to add a space on and use the command

:'<,'> norm I 

Note the space character after the I. The command means:

:'<,'>      For the line I selected
norm        Execute the following sequence of keystrokes as if I was in normal mode
I           Insert at the beginning of the line the following characters
[space]     A space

I you select the 3 first lines you'll get:

 " foo
 " bar
 buzz
fizz

For even more power you can combine the normal command with the global command to apply the transformation only on lines matching a pattern. If you want to add a space in front of the commented lines in our previous example you can use:

:g/"/norm I 

to apply norm I on lines containing ". Note the space character after the I

Which will give you:

 " foo
 " bar
buzz
fizz
4

Lets say you want to prepend 2 spaces to beginning of the line for 7 lines.

Approach 1: :set number and then we can add spaces to the beginning of the lines we want. Like for example :22,29s/^/ /

so here the 22,29 is the line range and :s is short for :substitute and /^ is to search at beginning of the lines and the 2 spaces are to replace the beginning of line in the given range with 2 spaces

Approach 2: :set shiftwidth=2 and :set number and :22,29> where > is for adding the width which is 2 spaces in this case

1
  • 3
    Note that set number is useful to know what is the number of your lines but it has no effects on the commands you mention. You could have set nonumber or set relativenumber and that would work the same.
    – statox
    Jul 9, 2020 at 11:35

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.