2

I am editing a file in vim and currently my cursor is in the middle of this line:

# foo bar baz foo bar baz foo bar baz foo bar baz 

Using JetBrains/PyCharm/VSCode, I can hit Ctrl+/ to uncomment/comment the line without moving the cursor left or right. Is this possible in vim?

This does not solve my problem: What's a quick way to comment/uncomment lines in Vim?

Udi
  • 29,222
  • 9
  • 96
  • 129
  • This similar discussion may be useful to you. https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim – Stun Brick May 31 '22 at 06:28

2 Answers2

2

You may want to use some plugin, for example: commentary by tim pope is a lightweight plugin with basic functionality: https://vimawesome.com/plugin/commentary-vim

"Comment stuff out." is the first line in the Readme. With commentary-vim installed and running, navigate to the line you want to comment out (your cursor can be in the middle of the line), then hit gcl to comment out that line and stay with the cursor at the exact position. In python a # (hash and space) will be inserted, so the text will be shifted 2 positions to the right, but the cursor will stay exactly at the position as it was before. Use gcl again to uncomment the line.

If you want your plugin to do more fancy stuff, take a look at the Nerd Commenter: https://vimawesome.com/plugin/the-nerd-commenter

Another lightweight plugin you may want to take a look at: https://github.com/tomtom/tcomment_vim

If you want to avoid installing plugins I'd suggest you write your custom key binding / shortcut.

0

Warning: this is not elegant. It assumes that the comment you want to remove always looks like the one in your question. But it works.

This would work as a macro or a keybinding, as far as I can tell.

mc02x`c2h
  1. mc sets a mark named "c" at the current location
  2. 0 moves to the beginning of the line
  3. 2x deletes the first two characters it finds there
  4. `c returns to the mark you created in step one
  5. 2h moves you left two characters
Nox
  • 1,358
  • 1
  • 13
  • 25
MDeBusk
  • 111
  • 1
  • 1
  • 7
  • this link has great information on formatting text on this site: https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks#:~:text=To%20use%20literal%20backticks%20at,yields%20the%20Perl%20%24%60%20operator. – Nox Jun 03 '22 at 15:11
  • Although the title of my question says "uncomment", the actual functionality, implemented in many other editors, is comment/uncomment with the same key. I will update the title of my question to emphasize this. Thank you! – Udi Jun 04 '22 at 16:18
  • @Udi That's beyond my skill level, then. Sorry. Closest I could come to that is adding key bindings to integrate [Thomas Jensen's boxes utility](https://boxes.thomasjensen.com/editors-vim.html) into vim. I love that tool but I don't use it often enough to feel good about putting it in my config. – MDeBusk Jun 04 '22 at 17:58