~adeodato/ blog/ entries/ 2008/ 03/ 02/ Making EnhancedCommentify.vim more useable for me

Making EnhancedCommentify.vim more useable for me

I use the enhanced commentify script from vim.org to easily comment and decomment parts of code. It knows about comment delimiters in a ton of languages, and it’s generally nice.

Lately, I’ve been a bit annoyed about commenting several lines with different indent levels. In particular, given for example this snippet:

  def foo():
      if duck.is_hungry():
          grab_food()
          feed_duck()

If one instructs the script to comment the three last lines, the result is:

  def foo():
      # if duck.is_hungry():
          # grab_food()
          # feed_duck()

When what I would like is:

  def foo():
      # if duck.is_hungry():
      #     grab_food()
      #     feed_duck()

There is one variable one can set to achieve this behavior: EnhCommentifyUseBlockIndent. However, it only works when commenting from visual mode. From normal mode (what I normally use — that is, going to e.g. line 2 above, and pressing 3,c), it doesn’t work, because from normal mode the commenting function does not receive the block, it just gets called three times, once per line.

To solve this, the solution I found was to create a custom command that accepts a range, and calls the function exactly once, for the whole block.

In particular, this is all my enhanced commentify configuration from ~/.vimrc:

  let EnhCommentifyPretty = "yes"
  let EnhCommentifyUserBindings = "yes"
  let EnhCommentifyRespectIndent = "yes"
  let EnhCommentifyUseBlockIndent = "yes"

  " The MyEnhancedCommentify bit is needed because the normal nmap just
  " calls EnhancedCommentify() <count> times, thus UseBlockIndent can't
  " work.
  nmap <Leader>c :MyEnhancedCommentify<CR>
  vmap <Leader>c <Plug>VisualTraditional
  command! -range MyEnhancedCommentify 
      \ call EnhancedCommentify('', 'guess', <line1>, <line2>)