Thursday, February 3, 2011

Some useful settings and plugins for VI Editor : Part 5 - Comment a code block

In the part 5 of this series, I am going to explain how to Comment/Uncomment a code block in VIM editor.

Method 1

Add folowing lines in your ~/.vimrc file

func! PhpUnComment() range
    let l:paste = &g:paste
    let &g:paste = 0

    let l:line        = a:firstline
    let l:endline     = a:lastline

    while l:line <= l:endline
        if getline (l:line) =~ '^\s*\/\/.*$'
            let l:newline = substitute (getline (l:line), '^\(\s*\)\/\/ \(.*\).*$', '\1\2', '')
        else
            let l:newline = substitute (getline (l:line), '^\(\s*\)\(.*\)$', '\1// \2', '')
        endif
        call setline (l:line, l:newline)
        let l:line = l:line + 1
    endwhile

    let &g:paste = l:paste
endfunc

vnoremap <buffer> <C-c> :call PhpUnComment()<CR>

Now In visual mode select the lines to comment/uncomment and press <CTRL-c>. This will comment all the uncommented lines, and uncomment all the commented lines.


Method 2

Using blockwise visual mode (CTRL-V) select the block to be commented.
Press I (capital i) and write the text you want to prepend to each line of the selected block (e.g. // or #). Then press ESC and the text will be inserted to the left of each line of the selected block.


For other posts related to VIM settings and plugins you can also visit

Some useful settings and plugins for VI Editor : Part 1 - General settings
Some useful settings and plugins for VI Editor : Part 2 - Autocompletion
Some useful settings and plugins for VI Editor : Part 3 - PHP documentor
Some useful settings and plugins for VI Editor : Part 4 - CodeSniffer Integration

No comments:

Post a Comment