Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert text at beginning of a multi-line selection in vi/Vim

Tags:

vim

editing

viemu

In Vim, how do I insert characters at the beginning of each line in a selection?

For instance, I want to comment out a block of code by prepending // at the beginning of each line assuming my language's comment system doesn't allow block commenting like /* */. How would I do this?

like image 394
Jordan Parmer Avatar asked Oct 31 '08 12:10

Jordan Parmer


People also ask

How do you put a character in front of multiple lines?

vim Inserting text Insert text into multiple lines at once Press Ctrl + v to enter into visual block mode. Use ↑ / ↓ / j / k to select multiple lines. Press Shift + i and start typing what you want. After you press Esc , the text will be inserted into all the lines you selected.

How do I go to the beginning of a line in vi editor?

Press ^ to move the cursor to the start of the current line. Press $ to move the cursor to the end of the current line.

How will you insert a line before the first line in vi editor?

Use sed 's insert ( i ) option which will insert the text in the preceding line.

How do you add a word at the end of each line in vim?

In a visual block, you can insert text in each line before the selection with I , and you can append text in each line after the selection with A . If you use $ to convert the visual selection to select to the end of line, then A will append text to the end of each line in the visual block.


2 Answers

  • Press Esc to enter 'command mode'
  • Use Ctrl+V to enter visual block mode
  • Move Up/Downto select the columns of text in the lines you want to comment.
  • Then hit Shift+i and type the text you want to insert.
  • Then hit Esc, wait 1 second and the inserted text will appear on every line.

For further information and reading, check out "Inserting text in multiple lines" in the Vim Tips Wiki.

like image 99
pixelbeat Avatar answered Sep 29 '22 09:09

pixelbeat


This replaces the beginning of each line with "//":

:%s!^!//! 

This replaces the beginning of each selected line (use visual mode to select) with "//":

:'<,'>s!^!//! 

Note that gv (in normal mode) restores the last visual selection, this comes in handy from time to time.

like image 42
Tomalak Avatar answered Sep 29 '22 10:09

Tomalak