How do I insert text at beginning of a multi-line

2019-01-12 13:18发布

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?

12条回答
\"骚年 ilove
2楼-- · 2019-01-12 13:29

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-12 13:33

This adds # at the beginning of every line:

:%s/^/#/

And people will stop complaining about your lack of properly commenting scripts.

查看更多
冷血范
4楼-- · 2019-01-12 13:34

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.

查看更多
Deceive 欺骗
5楼-- · 2019-01-12 13:37

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'

查看更多
Emotional °昔
6楼-- · 2019-01-12 13:38
  • 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 this related article on the vim wiki.

查看更多
女痞
7楼-- · 2019-01-12 13:38

Mark the area to be comment as a visual block (<C-V)

and do c#<ESC>p

  1. change it to "#"
  2. put it back

If you do it often, define a short cut (example \q) in your .vimrc

:vmap \q c#<ESC>p
查看更多
登录 后发表回答