Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a block of white spaces starting at the cursor position in vi?

Tags:

vim

vi

Suppose I have the piece of text below with the cursor staying at the first A currently,

AAAA BBB CC D 

How can I add spaces in front of each line to make it like, and it would be great if the number of columns of spaces can be specified on-the-fly, e.g., two here.

  AAAA   BBB   CC   D 

I would imagine there is a way to do it quickly in visual mode, but any ideas?

Currently I'm copying the first column of text in visual mode twice, and replace the entire two column to spaces, which involves > 5 keystrokes, too cumbersome.

Constraint:

Sorry that I didn't state the question clearly and might create some confusions.

The target is only part of a larger file, so it would be great if the number of rows and columns starting from the first A can be specified.

Edit:

Thank both @DeepYellow and @Johnsyweb, apparently >} and >ap are all great tips that I was not aware of, and they both could be valid answers before I clarified on the specific requirement for the answer to my question, but in any case, @luser droog 's answer stands out as the only viable answer. Thank you everyone!

like image 731
nye17 Avatar asked Sep 29 '11 04:09

nye17


People also ask

How do I put text before a cursor in vi?

Insert text to the left of the cursor by typing i from command mode. Type I to insert text at the beginning of a line. The command moves the cursor from any position on that line. Press Esc to return to command mode after you type the desired text.


1 Answers

I'd use :%s/^/ /

You could also specify a range of lines :10,15s/^/ /

Or a relative range :.,+5s/^/ /

Or use regular expressions for the locations :/A/,/D/>.

For copying code to paste on SO, I usually use sed from the terminal sed 's/^/ /' filename


Shortcut

I just learned a new trick for this. You enter visual mode v, select the region (with regular movement commands), then hit : which gives you this:

:'<,'> 

ready for you to type just the command part of the above commands, the marks '< and '> being automatically set to the bounds of the visual selection.

To select and indent the current paragraph:

vip> 

or

vip:> 

followed by enter.

Edit:

As requested in the comments, you can also add spaces to the middle of a line using a regex quantifier \{n} on the any meta-character ..

:%s/^.\{14}/& / 

This adds a space 14 chars from the left on each line. Of course % could be replaced by any of the above options for specifying the range of an ex command.

like image 84
luser droog Avatar answered Sep 23 '22 20:09

luser droog