What's a quick way to comment/uncomment lines in Vim?
I have a Ruby code file open in vi, there are lines commented out with #
:
class Search < ActiveRecord::Migration
def self.up
# create_table :searches do |t|
# t.integer :user_id
# t.string :name
# t.string :all_of
# t.string :any_of
# t.string :none_of
# t.string :exact_phrase
#
# t.timestamps
# end
end
def self.down
# drop_table :searches
end
end
Say I want to uncomment all the lines in the first def ... end
section. What's an efficient way to do that in Vim?
In general, I'm looking for an easy and fluid way to comment and uncomment lines. Here I'm dealing with Ruby code, but it could be JavaScript ( //
) or Haml ( -#
).
I use the NERD Commenter script. It lets you easily comment, uncomment or toggle comments in your code.
For those tasks I use most of the time block selection.
Put your cursor on the first #
character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the #
characters vertically.
For commenting a block of text is almost the same:
VISUAL BLOCK
mode. INSERT
mode and then press #. This will add a hash to the first line. #
character on all other selected lines. For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/#
in the third step instead.
To comment out blocks in vim:
%
To uncomment blocks in vim:
If you want to select multiple characters, use one or combine these methods: