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

407,683

Solution 1

  • 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.

Solution 2

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.

Solution 3

The general pattern for search and replace is:

:s/search/replace/

Replaces the first occurrence of 'search' with 'replace' for current line

:s/search/replace/g

Replaces all occurrences of 'search' with 'replace' for current line, 'g' is short for 'global'

This command will replace each occurrence of 'search' with 'replace' for the current line only. The % is used to search over the whole file. To confirm each replacement interactively append a 'c' for confirm:

:%s/search/replace/c

Interactive confirm replacing 'search' with 'replace' for the entire file

Instead of the % character you can use a line number range (note that the '^' character is a special search character for the start of line):

:14,20s/^/#/

Inserts a '#' character at the start of lines 14-20

If you want to use another comment character (like //) then change your command delimiter:

:14,20s!^!//!

Inserts a '//' character sequence at the start of lines 14-20

Or you can always just escape the // characters like:

:14,20s/^/\/\//

Inserts a '//' character sequence at the start of lines 14-20

If you are not seeing line numbers in your editor, simply type the following

:set nu

Solution 4

Another way that might be easier for newcomers:

 some█
 code
 here

Place the cursor on the first line, e.g. by

gg

and type the following to get into insert mode and add your text:

I / / Space

 // █some
 code
 here

Press Esc to get back to command mode and use the digraph:

j . j .

 // some
 // code
 //█here

j is a motion command to go down one line and . repeats the last editing command you made.

Solution 5

And yet another way:

  • Move to the beginning of a line
  • enter Visual Block mode (CTRL-v)
  • select the lines you want (moving up/down with j/k, or jumping to a line with [line]G)
  • press I (that's capital i)
  • type the comment character(s)
  • press ESC
Share:
407,683
Jordan Parmer
Author by

Jordan Parmer

I am a software engineer for Oseberg, a data analytics company. I specialize in .NET, GIS, Scala, Postgres/Oralce/MS SQL Server, and Python. In my free time I spend time with my wife and kids, study Koine Greek, roast my own coffee, and train for obstacle races.

Updated on July 17, 2022

Comments

  • Jordan Parmer
    Jordan Parmer almost 2 years

    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?

  • Jordan Parmer
    Jordan Parmer over 15 years
    The only bummer with this is that it appears Ctrl+V is overridden in GVIM.
  • pixelbeat
    pixelbeat over 15 years
    Not for me (on linux) it's not
  • Gareth
    Gareth over 15 years
    You can use Ctrl-Q as a replacement in gVim (as :help Ctrl-V explains) but you need to use hjkl to navigate in this mode rather than the arrow keys
  • Jordan Parmer
    Jordan Parmer over 15 years
    Thanks! Makes total sense. And removing the text goes as follows: '<,'>s!^//!!
  • nkare
    nkare over 15 years
    To be able to use the arrow keys in visual mode on windows just add "set keymodel-=stopsel" to your _vimrc. More at vim.wikia.com/wiki/…
  • Cyber Oliveira
    Cyber Oliveira over 15 years
    actually the :g command isn't necessary. This will do: :'<,'>norm I//
  • graywh
    graywh over 15 years
    And :s is better to use in this case, too.
  • Nathan Fellman
    Nathan Fellman about 15 years
    You can also use Nerd Commenter at vim.org/scripts/script.php?script_id=1218
  • jimiyash
    jimiyash over 13 years
    This worked for me. I had to press escape twice though (on mac terminal)
  • Henrik K
    Henrik K almost 13 years
    What is the meaning of the exclamation marks in the above answer? (:%s!^!//!)
  • cyber-monk
    cyber-monk almost 13 years
    @HKK, normally one uses the forward slash character / as a delimeter for the search and replace command. In this case we are inserting a forward slash as part of the search and replace so we use an alternative delimeter, namely the exclamation character !
  • Seth Reno
    Seth Reno over 12 years
    +1 This works in VsVim where (Ctrl+V) (Shiift+I) Esc doesn't.
  • MigDus
    MigDus about 12 years
    Thanks! Also, to replace the END of each line you might write: %s!$!//!
  • cn1h
    cn1h almost 12 years
    to remove the beginning #: instead of :14,20s/#/^/, you should use :14,20s/#//
  • Cheezmeister
    Cheezmeister over 11 years
    Ctrl+Shift+V works for me in GVIM, but I might have set that by hand...don't actually remember.
  • strongriley
    strongriley over 11 years
    If anyone else got confused like me... That's Shift + i, not a lowercase l.
  • user57359
    user57359 over 10 years
    Don't forget to install the REAL Vim on Ubuntu since the default Vi editor is vim-tiny and it does not work the same. $ sudo apt-get install vim
  • Hashbrown
    Hashbrown over 10 years
    +1, had no idea you could use something else as the regex delimiter (here I was using / and having to escape the // in :s/^/\/\/ instead of writing :s!^!//)
  • vkaul11
    vkaul11 over 10 years
    Shift+i takes me back into insert mode and I lose the block selection that I get through CTRL+V. Any reasons?
  • cokedude
    cokedude about 10 years
    Thats really simple :). If you are having trouble with it may be because you are typing a bar (the other symbol with your \ ) | instead of a capital I. I thought it was a | at first.
  • Patrick Sanan
    Patrick Sanan about 10 years
    The "wait one second" part was what was confusing me on previous attempts to discover this method.
  • Tek
    Tek over 9 years
    Any idea why this wouldn't do anything after pushing esc? I waited like 10 seconds for something to happen on less than a hundred lines -- Never mind, I was pushing Shift + v not CTRL + v. @vkaul11 Probably the same thing what you did lol
  • user1418706
    user1418706 about 9 years
    So useful its life changing. Thank you
  • Rahul Prasad
    Rahul Prasad almost 9 years
    What if you want to add # on only selected (or few) lines
  • Rahul Prasad
    Rahul Prasad almost 9 years
    If I do "5." it deletes 5 character from same line. How do I make it delete 5 character at once from each line ?
  • ankush981
    ankush981 over 8 years
    @cn1h I think this will replace other # in the line as well. You should use ^# instead.
  • ankush981
    ankush981 over 8 years
    Upvoted because it introduced something new - vmap!
  • ninegrid
    ninegrid about 8 years
    @RahulPrasad Let's say you have 25 lines, then beginning at the front of the first line just record 5xj into a register and play that register 24 times, for example: qa5xjq25@a But it would be better if you posted this as an actual question if it doesnt exist already...
  • here
    here over 7 years
    :help visual-operators -> I = block insert , A = block append
  • Peaceful
    Peaceful over 7 years
    This is the most useful answer.
  • mgouin
    mgouin almost 7 years
    Sorry if not related, but anyone knows how to paste something at the beginning of lines in a block. Basically same steps as mentioned in the answer, but instead of typing at step 3, pasting an already yanked text (let's say too complex to type in full again)?
  • alienCY
    alienCY almost 7 years
    CTRL not shift! That's what I had confused so watch out! Now then could you please tell me how to uncomment a selection of lines?
  • StockB
    StockB about 6 years
    Does anyone know why it takes exactly one second between escaping Visual mode and inserting the characters on subsequent lines? I'm just curious.
  • Admin
    Admin almost 6 years
    @mgouin Hopefully you figured this out over the past year, but I'll leave this here in case anyone sees your question - you can always use Ctrl-R (register) to put (paste) while in insert mode. So, something like Ctrl-V Shift-I Ctrl-R " Esc.
  • mgouin
    mgouin almost 6 years
    @brhfl Thanks you for taking the time to put the trick to my old question... It's funny, I found about the Ctrl-R in search mode (/) but I did not realize I could use it in that case also. Thanks!
  • Kingsley
    Kingsley over 5 years
    This adds the text to the left of the first non-space character in the line.
  • karakays
    karakays over 5 years
    @alienCY yes, it must be visual block selection so do it with Ctrl-v. To uncomment, select in the same way and then hit x to delete them.
  • ankur_kachru
    ankur_kachru about 5 years
    The confusing bit for me was that in Step 2 you have to press Ctrl + "Uppercase V", so in effect Ctrl + Shift + v to enter Visual block mode.
  • didierCH
    didierCH almost 5 years
    Thanks for explaining the basics. It's good to know why something happens.
  • alphaGeek
    alphaGeek over 4 years
    @ankur_kachru : for me ctrl+v (lower case) works just fine. tested on Ubuntu 18.04 LTS and VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Jun 06 2019 17:31:41).
  • Chris
    Chris over 4 years
    This actually works. Commonly here, the 2nd highest vote tally is actually the correct answer...
  • user228395
    user228395 about 4 years
    Took me a while to figure out that you really have to press Esc, and not the command mode-key (which is Ctrl-C for me), when exiting VISUAL BLOCK.
  • Duy Tran
    Duy Tran about 3 years
    thanks, this help a lot with modifying file in servers without additional plugin of VI
  • Lino Ferreira
    Lino Ferreira almost 2 years
    Works in Emacs Evil mode. Thanks!