0

I'm new with vim and working on Mac with python, and want to know how to comment/uncomment a single line with vim. Most of the IDEs that I've worked with use Cmd+/ it there something similar? I tried to find the answer but everything I found was about multiple lines!

Emi OB
  • 2,814
  • 3
  • 13
  • 29
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
  • 1
    Take a look at [question: What's a quick way to comment/uncomment lines in Vim?](https://stackoverflow.com/questions/1676632/whats-a-quick-way-to-comment-uncomment-lines-in-vim). As far as I know there is no way to do a quick command in plain vim, unless you add extensions. – Thamognya Dec 28 '22 at 10:55

2 Answers2

3

Here are some of the native ways to comment the current line in Python:

I#<Esc> 
:s/^/#<CR>

See :help I, :help :s, and :help /^.

And here are some of the native ways to uncomment it:

^x
:s/^#<CR>

See :help ^ and :help x.

In a different language with a different syntax, like JavaScript, it would become:

I//<Esc>
^xx

Vim knows the syntax of comments for lots of different languages by way of :help 'comments' and :help 'commentstring', but it only uses the former for formatting and the latter for folding. It doesn't have a native equivalent of that "toggle comments" shortcut you are used to and the native way to handle comments is not even remotely as efficient as that shortcut. That is why there have been so many plugins written in the past decades to address such a common need: NERD Commenter, Commentary, etc.

If you are already using Vim for actual work (as opposed to just learning), then I would suggest you to pick a commenting plugin and move on.

romainl
  • 186,200
  • 21
  • 280
  • 313
1

Comments in Python are prefixed with #

Working in vim you will need to insert # at some point where you think it's appropriate.

Go to that point then type: i#ESC ...where ESC is the escape key

To delete a comment you'll want to search for #

Type: /#

This will take you to the first occurrence of # from your current position. Once you've established that you've found the comment that you want to delete then...

Type: d

Doktor OSwaldo
  • 5,732
  • 20
  • 41
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • While vim can be used for editing your Python source files it's not a good choice when you can get any one of several very good IDEs at no cost. An IDE set up for Python will give you much more than just editing capability – DarkKnight Dec 28 '22 at 11:06
  • I disagree. Vim is an excellent python editor. Vim also does give you much more than just editing capability if you want. A quick websearch will give you a ton of sources to configure vim as python IDE. – Doktor OSwaldo Dec 30 '22 at 06:43