What's the most elegant way of commenting / uncommenting blocks of ruby code in Vim?

前端 未结 10 681
悲哀的现实
悲哀的现实 2021-01-30 13:23

In VIM, at the moment when I need to comment out a section of Ruby code:

  • I navigate to the first column in the row I want to comment out
  • I press CTRL-v t
相关标签:
10条回答
  • 2021-01-30 14:00

    I use these plugins:

    1. vim-commentary by Tim Pope, which defines a comment operator gc
    2. vim-textobj-rubyblock, which defines ir (inside Ruby block) and ar (around Ruby block) for Ruby do ... blocks.
    3. vim-ruby which defines im/am for inside/around Ruby method, and iM/aM for inside/around Ruby class.

    Using this combination, I can easily comment/uncomment Ruby-specific code in Normal mode, e.g.:

    1. gcir / gcar comment inside/around Ruby do/end block.
    2. gcim / gcam comment inside/around Ruby method.
    3. gciM / gcaM comment inside/around Ruby class.
    4. Plus normal Commentary maps like gcc to comment a line, or 5gcc to comment 5 lines.

    All in all it's very Vim-like and natural.

    Hope that helps.

    0 讨论(0)
  • 2021-01-30 14:01

    After visually selecting, in block mode, the text you want to comment out, hit I (that is a capital i), type # and finally hit the escape key. It's basically the same procedure you are using currently, but using insert instead of replace.

    0 讨论(0)
  • 2021-01-30 14:02

    I like using the following:

    • put cursor on the first line you want to comment out
    • enter ma (no colon) to put a marker on that line
    • go to the last line of the block you want to comment out
    • enter :'a,.s/^/#/ and then enter

    That says, from the line containing marker "a", up to the current line, substitute a hash for the beginning of the line.

    0 讨论(0)
  • 2021-01-30 14:03

    For each language (ftplugin), I write mappings which will add or remove the comment leader and move the cursor down one line. For example, in my python ftplugin, I have this:

    noremap   <buffer> K      :s,^\(\s*\)[^# \t]\@=,\1#,e<CR>:nohls<CR>zvj
    noremap   <buffer> <C-K>  :s,^\(\s*\)#\s\@!,\1,e<CR>:nohls<CR>zvj
    

    I find this to be an extremely flexible setup:

    • Hit K to comment the current line.
    • Hit K repeatedly to comment lots of lines.
    • 6K to comment 6 lines.
    • K in visual mode comments the whole selection.
    • Everything can be uncommented in the same way using CTRL-K
    • If lines are already commented, they won't have an additional # added to the start.
    • If a # is followed by a space, it is considered a text comment and doesn't get touched.

    I adapt this slightly for each language. It doesn't work as well for Old C comments (/*...*/) but I prefer not to use those anyway.

    0 讨论(0)
提交回复
热议问题