Thank you for teaching me this practical Vim trick. In the past, I usually used 
macros to solve similar problems.

However, since I like using the mouse, I just came up with an idea:
I wrote a function and put it into my vimrc:

function! s:ToggleBlockCommentVisual() range
  let l:start_line = line("'<")
  let l:end_line   = line("'>")

  if l:start_line > l:end_line
    let l:tmp = l:start_line
    let l:start_line = l:end_line
    let l:end_line = l:tmp
  endif

  if &filetype ==# 'python'
    let l:begin = '"""'
    let l:end   = '"""'
  elseif &filetype ==# 'go'
    let l:begin = '/*'
    let l:end   = '*/'
  else
    echo "The current file type does not support block comments:" . &filetype
    return
  endif

  let l:prev_line = getline(l:start_line - 1)
  let l:next_line = getline(l:end_line + 1)

  let l:prev_trim = trim(l:prev_line)
  let l:next_trim = trim(l:next_line)

  if l:prev_trim ==# l:begin && l:next_trim ==# l:end
    call deletebufline(bufnr('%'), l:end_line + 1)
    call deletebufline(bufnr('%'), l:start_line - 1)
  else
    call append(l:end_line, l:end)
    call append(l:start_line - 1, l:begin)
  endif
endfunction

xnoremap <silent> # :<C-u>call <SID>ToggleBlockCommentVisual()<CR>


Of course, abusing """ code """ is a bad habit of mine—you can change it to 
another approach if you like.

After selecting a block of code with the mouse (of course, you need to enable 
the mouse with set mouse=a), press Shift + 3 (the # key) to comment that block. 
You can also use the same shortcut to uncomment a block that has already been 
commented.
-- 
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to