Jay Taylor's notes
back to listing indexHow do I insert text at beginning of a multi-line selection in vi/Vim?
[web search]- Home
-
- Public
- Stack Overflow
- Tags
- Users
- Jobs
-
- Teams
- Create Team
In Vim, how would I go about inserting characters at the beginning of each line in a selection?
For instance, let's say 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?
- 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.
-
6The only bummer with this is that it appears Ctrl+V is overridden in GVIM. – Jordan Parmer Oct 31 '08 at 13:04
-
9
-
20You 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 – Gareth Oct 31 '08 at 13:07
-
9If your ctrl-v is overridden in windows gvim, you should edit the global vimrc to stop including mswin.vim. – graywh Jan 4 '09 at 21:20
-
10Any 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 – Tek Jan 16 '15 at 22:31
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.
-
2Thanks! Makes total sense. And removing the text goes as follows: '<,'>s!^//!! – Jordan Parmer Oct 31 '08 at 13:08
-
-
2What is the meaning of the exclamation marks in the above answer? (:%s!^!//!) – HK_CH May 31 '11 at 8:57
-
13@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 ! – cyber-monk Jun 7 '11 at 20:46
-
2+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!^!//
) – Hashbrown Dec 18 '13 at 6:19
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
-
to remove the beginning #: instead of :14,20s/#/^/, you should use :14,20s/#// – cn1h Jun 16 '12 at 9:21
-
1@cn1h I think this will replace other
#
in the line as well. You should use^#
instead. – dotslash Aug 23 '15 at 4:01
Another way that might be easier for newcomers:
some█
code
here
Place the cursor on the first line, e.g. by
: 1 Enter
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.
-
2Thats 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. – cokedude Feb 28 '14 at 17:30 -
If I do "5." it deletes 5 character from same line. How do I make it delete 5 character at once from each line ? – Rahul Prasad Jun 24 '15 at 6:58
-
@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... – ninegrid Mar 1 '16 at 7:03
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
This adds #
at the beginning of every line:
:%s/^/#/
And people will stop complaining about your lack of properly commenting scripts.
-
1
If you want to get super fancy about it, put this in your .vimrc:
vmap \c :s!^!//!<CR>
vmap \u :s!^//!!<CR>
Then, whenever in visual mode, you can hit \c
to comment the block and \u
to uncomment it. Of course, you can change those shortcut keystrokes to whatever.
Yet another way:
:'<,'>g/^/norm I//
/^/
is just a dummy pattern to match every line. norm
lets you run the normal-mode commands that follow. I//
says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).
:g
is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.
-
actually the :g command isn't necessary. This will do: :'<,'>norm I// – Leonardo Constantino Dec 18 '08 at 19:56
-
1
-
For commenting blocks of code, I like the NERD Commenter plugin.
Select some text:
Shift-V
...select the lines of text you want to comment....
Comment:
,cc
Uncomment:
,cu
Or just toggle the comment state of a line or block:
,c<space>
I can recommend the EnhCommentify plugin.
eg. put this to your vimrc:
let maplocalleader=','
vmap <silent> <LocalLeader>c <Plug>VisualTraditional
nmap <silent> <LocalLeader>c <Plug>Traditional
let g:EnhCommentifyBindInInsert = 'No'
let g:EnhCommentifyMultiPartBlocks = 'Yes'
let g:EnhCommentifyPretty = 'Yes'
let g:EnhCommentifyRespectIndent = 'Yes'
let g:EnhCommentifyUseBlockIndent = 'Yes'
you can then comment/uncomment the (selected) lines with ',c'
-
2You can also use Nerd Commenter at vim.org/scripts/script.php?script_id=1218 – Nathan Fellman Mar 9 '09 at 10:59
Mark the area to be comment as a visual block (<C-V
)
and do c#<ESC>p
c
hange it to "#"- put it back
If you do it often, define a short cut (example \q
) in your .vimrc
:vmap \q c#<ESC>p
Your Answer
Not the answer you're looking for? Browse other questions tagged vim editing viemu or ask your own question.
asked |
9 years, 8 months ago |
viewed |
261,987 times |
active |
Get the weekly newsletter! In it, you'll get:
- The week's top questions and answers
- Important community announcements
- Questions that need answers
see an example newsletter
Linked
Related
Hot Network Questions
-
Does casting a spell use a spell slot if you have the components for the spell?
-
Accusing private figures of crime in print
-
Halting Problem without self-reference: why does this argument not suffice (or does it)?
-
Do "good" viruses exist? If so, what are they called?
-
Was Officer Alex Murphy medically murdered?
-
Why does "Not in a month of Sundays" mean "It won't happen"?
-
What do you do when your message could be dangerous?
-
Why didn't line infantry tactics try to keep up a constant volley of fire?
-
how to shade segment of a sector in tikzpicture
-
Python lexicon class
-
Did a German plane really land in Moscow in 1941 May?
-
Why do toddlers hate getting their face cleaned off with a wet washcloth and is there a better way?
-
23 Years Old, With No Debt. Invest into Rental Properties or 401K?
-
How do huge open source libraries get maintained while having code far from "clean code" practices?
-
What would induce a country to actively guard an empty wasteland?
-
Stacked digit staircases
-
What are the Apex Managed sharing best practice for a large number of records
-
Why didn't Barack Obama try to force the Senate to hold hearings on SCOTUS nominee Merrick Garland?
-
How can I handle a co-worker awkwardly forcing herself into conversations?
-
What is the best way to translate 'remember' into Latin?
-
Holonomy groups of compact Riemannian symmetric spaces
-
wp_transition_post_status does not change the status of the post
-
Count Consecutive Characters
-
Learning Songs on Guitar
site design / logo © 2018 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required. rev 2018.7.13.31025