开发者

Vim - Visual Block : Delete rather than insert

I often use visual block then inserting on multiple lines when for example commenting out a lot of code. This is great for inserting text in the same position on multiple lines but I can't figure out how to delete this text later u开发者_JS百科sing visual block mode, Backspace, Del and d all don't work. I am using MacVim.


You're looking for x:

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh

Then visual-block-select, x:

root:/root:/bin/bash
daeaemon:/usr/sbin:/bin/sh
bin/bin:/bin/sh
sys/dev:/bin/sh

I use this frequently, for exactly the same reason -- commenting and uncommenting large blocks of code.


This isn't directly answering the question (sarnold has already done so), but I would suggest there are more efficient ways of (un-)commenting code blocks. I have a CommentToggle function which either comments or uncomments the current line, depending on whether or not it begins with the "comchar".

function! CommentToggle(comchar)
    let firstchar = matchstr(getline("."),"[^ ]")
    if firstchar == a:comchar
        sil exe 'normal ^xx'
    else 
        sil exe 'normal ^i' . a:comchar . ' '
    endif
endfunction

So, for perl files you can map:

nnoremap <silent> <leader>c :call CommentToggle('#')<CR>

and pressing 3 \ c (un-)comments three lines from the cursor position.

You can also write a visual-mode mapping:

vnoremap <silent> <leader>c :call CommentToggle('#')<CR>

allowing you to select a visual region and press \c to (un-)comment them all.

This particular function only works for one-character comments ("#", "%", etc.), but it is straightforward to extend it to longer strings (e.g. "//"), and even more complex replacements, such as HTML comments.

Hope this helps.


Prince Goulash's answer doesn't work in lines with leading tabs.

I changed it, adding the tab character to the pattern, although lines lose their indent after comment and uncomment.

function! CommentToggle( comchar )
        let firstchar = matchstr( getline( "." ), "[^ \t]" )
        if firstchar == a:comchar
                sil exe 'normal ^2x'
        else
                sil exe 'normal ^i' . a:comchar . ' '
        endif
endfunction

I like more adding the comment char to first position in line, this modification to Prince Goulash's function does the trick:

function! CommentToggle( comchar )
        let firstchar = matchstr( getline( "." ), "[^ \t]" )
        if firstchar == a:comchar
                sil exe 'normal ^2x'
        else
                sil exe 'normal gI' . a:comchar . ' '
        endif
endfunction
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜