Reputation: 30532
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?
Upvotes: 4
Views: 518
Reputation: 121
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
mc
sets a mark named "c" at the current location0
moves to the beginning of the line2x
deletes the first two characters it finds there`c
returns to the mark you created in step one2h
moves you left two charactersUpvotes: 0
Reputation: 81
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.
Upvotes: 2