DEV Community

3 Ways to Comment Out Blocks of Code in vi

Liz Lam on September 19, 2019

Learning vi for the first time can be really intimidating. The learning curve is a bit high and there are many ways to do many things in this simp...
Collapse
 
adriengiboire profile image
Adrien Giboire • Edited

Quick tips:

  • To go to the beginning/end of your function/block, you can use %
  • Instead of typing the line numbers in your s command, you can highlight the lines and type :. It will prompt :'<,'> and you can continue with your command, i.e. s/^/\/\//, then Enter.

Hope I was clear :)

Collapse
 
grepliz profile image
Liz Lam

Thanks for the tip!

Collapse
 
pianocomposer321 profile image
pianocomposer321

Quote:
What about //? Won't vi get confused since substitution uses / to separate the old value from the new value? This is where we need to use \ (forward slash) to escape the double back slashes that represent commenting.

Acutally, / is forward slash and \ is backslash. :)

Collapse
 
grepliz profile image
Liz Lam

Oh yes, you are right! Correcting now!

Collapse
 
moopet profile image
Ben Sinclair

I use a plugin to do this because different languages have different requirements for comments and I'm lazy). I use commentary but there are a few that all do much the same thing.

Out of your options, I prefer #3, but I'd also consider using a macro and repeating it n times if the comments required changing the start and end of the line, like in CSS.

Using ctrl-smilieface to enter pedantic mode I feel the urge to point out that #3 is Vim only and not available in Vi.

Collapse
 
grepliz profile image
Liz Lam

I haven't had a lot of experiences with different plugins, but I will have to check out commentary.

So funny, yes. I tend to use the words 'vi' and 'vim' interchangeably and I was debating if I should make that distinction on this blog.

True story, I used vi proper for almost 10 years and for 8 of those years at work on an old RedHat Workstation distribution. A time came where all our work machines got upgraded to Ubuntu and I ended up with vim on my machine (I think it was vim-tiny). I wasn't familiar with visual mode. Everytime I accidentally hit CTRL + v, I would quickly ESC out because I didn't know what it was doing.

3 months ago, I decided to finally make the small effort to learn visual mode.

I love how you can learn new things all the time even in the tools you've been using forever!

Thanks for the comments!

Collapse
 
pnaranja profile image
Paul

Thanks for sharing!

For your #3, I use relative numbers so it's easy to see you can press "6j" to get to the end of the function.

And interesting code you're editing :)

Collapse
 
grepliz profile image
Liz Lam

Definitely a great shortcut also!

Yes! I will probably start blogging about Rust at some point in the future!