How to insert text at beginning of a multi-line selection in vi/Vim
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
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, 2022Comments
-
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 over 15 yearsThe only bummer with this is that it appears Ctrl+V is overridden in GVIM.
-
pixelbeat over 15 yearsNot for me (on linux) it's not
-
Gareth over 15 yearsYou 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 over 15 yearsThanks! Makes total sense. And removing the text goes as follows: '<,'>s!^//!!
-
nkare over 15 yearsTo 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 over 15 yearsactually the :g command isn't necessary. This will do: :'<,'>norm I//
-
graywh over 15 yearsAnd :s is better to use in this case, too.
-
Nathan Fellman about 15 yearsYou can also use Nerd Commenter at vim.org/scripts/script.php?script_id=1218
-
jimiyash over 13 yearsThis worked for me. I had to press escape twice though (on mac terminal)
-
Henrik K almost 13 yearsWhat is the meaning of the exclamation marks in the above answer? (:%s!^!//!)
-
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 over 12 years+1 This works in VsVim where (Ctrl+V) (Shiift+I) Esc doesn't.
-
MigDus about 12 yearsThanks! Also, to replace the END of each line you might write: %s!$!//!
-
cn1h almost 12 yearsto remove the beginning #: instead of :14,20s/#/^/, you should use :14,20s/#//
-
Cheezmeister over 11 yearsCtrl+Shift+V works for me in GVIM, but I might have set that by hand...don't actually remember.
-
strongriley over 11 yearsIf anyone else got confused like me... That's Shift + i, not a lowercase l.
-
user57359 over 10 yearsDon'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 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 over 10 yearsShift+i takes me back into insert mode and I lose the block selection that I get through CTRL+V. Any reasons?
-
cokedude about 10 yearsThats 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 capitalI
. I thought it was a|
at first. -
Patrick Sanan about 10 yearsThe "wait one second" part was what was confusing me on previous attempts to discover this method.
-
Tek over 9 yearsAny 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
notCTRL + v
. @vkaul11 Probably the same thing what you did lol -
user1418706 about 9 yearsSo useful its life changing. Thank you
-
Rahul Prasad almost 9 yearsWhat if you want to add # on only selected (or few) lines
-
Rahul Prasad almost 9 yearsIf I do "5." it deletes 5 character from same line. How do I make it delete 5 character at once from each line ?
-
ankush981 over 8 years@cn1h I think this will replace other
#
in the line as well. You should use^#
instead. -
ankush981 over 8 yearsUpvoted because it introduced something new -
vmap
! -
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 over 7 years:help visual-operators -> I = block insert , A = block append
-
Peaceful over 7 yearsThis is the most useful answer.
-
mgouin almost 7 yearsSorry 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 almost 7 yearsCTRL 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 about 6 yearsDoes anyone know why it takes exactly one second between escaping Visual mode and inserting the characters on subsequent lines? I'm just curious.
-
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 likeCtrl-V
Shift-I
Ctrl-R
"
Esc
. -
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 over 5 yearsThis adds the text to the left of the first non-space character in the line.
-
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 hitx
to delete them. -
ankur_kachru about 5 yearsThe 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 almost 5 yearsThanks for explaining the basics. It's good to know why something happens.
-
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 over 4 yearsThis actually works. Commonly here, the 2nd highest vote tally is actually the correct answer...
-
user228395 about 4 yearsTook me a while to figure out that you really have to press
Esc
, and not the command mode-key (which isCtrl-C
for me), when exiting VISUAL BLOCK. -
Duy Tran about 3 yearsthanks, this help a lot with modifying file in servers without additional plugin of VI
-
Lino Ferreira almost 2 yearsWorks in Emacs Evil mode. Thanks!