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|...
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 (-#).
50 Answers
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:
- First, go to the first line you want to comment, press CtrlV. This will put the editor in the
VISUAL BLOCKmode. - Then using the arrow key and select until the last line
- Now press ShiftI, which will put the editor in
INSERTmode and then press #. This will add a hash to the first line. - Then press Esc (give it a second), and it will insert a
#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 (any remaining highlighting of the first character of each line can be removed with :nohl).
Here are two small screen recordings for visual reference.
Comment:
Uncomment:
To comment out blocks in vim:
- press Esc (to leave editing or other mode)
- hit ctrl+v (visual block mode)
- use the ↑/↓ arrow keys to select lines you want (it won't highlight everything - it's OK!)
- Shift+i (capital I)
- insert the text you want, e.g.
% - press EscEsc