Explain Codes LogoExplain Codes Logo

How to comment out a block of Python code in Vim

python
vim
commenting
efficiency
Alex KataevbyAlex Kataev·Aug 15, 2024
TLDR

Comment out your Python block in Vim with visual block mode as follows:

  1. Ctrl + V: activate visual block mode.
  2. Use arrows to highlight the desired lines.
  3. Shift + I and then #.
  4. Press Esc to comment your block.
" Ctrl + V (Visual block mode on) " Shift + I (Insert), # " Esc (Apply to all selected lines)

Custom efficiency key mapping

Let’s supercharge block commenting with custom mappings in your .vimrc.

  1. Open .vimrc: :e $MYVIMRC.
  2. Add the following mappings:
" Commenting (press Ctrl + c!) vnoremap <C-c> :s/^/#/<CR> " Uncommenting (Ctrl + u will restore your code) vnoremap <C-u> :s/^#//<CR>
  1. Reload .vimrc or restart Vim.

Now, toggle comments on the go with Ctrl + c and Ctrl + u. Less hand movement = more time to debate tabs vs spaces.🤭

Dealing with special cases

A toggle to rule them all

Switch between commenting your visual block in and out with a toggle function:

  • Implement the toggle:
" Toggle (Ctrl + t will do the trick) vnoremap <C-t> :s/^/#/<CR>:noh<CR>gv:s/^#//<CR>:noh<CR>
  • Select your block and press Ctrl + t. Now you've got the power!

Making use of line numbers

Line numbers streamline block selection:

  1. Enable line numbers: :set number.
  2. Use line numbers with : to select a range.
:15,25s/^/#/

Put the line numbers to work when your code is as long as the arguments you had last Friday about the best Star Wars movie. 🌑💥

Achieve a cleaner code with comments

Quieting with alternative methods

For larger pieces of code (a function, class), consider the power of multiline strings (""") for comments.

  1. Highlight your block with V.
  2. Press Shift + I, then '"""' and Esc to "mute" them in style.

Commenting responsibly

While commenting is cool, avoid turning your code into a hash tornado. Pro-tip: Comments should explain why the code does something, not how.

Spring cleaning your comments

Commenting using substitutions

Directly prefix line/s with # without entering visual block using substitution:

:10,20s/^/#/

"Wait, wasn't # supposed to be a trending topic symbol?" Nope, not here! 🙃

Enhancing your efficiency with motions

Try commenting combined with motion commands:

  1. Pressing #down arrow comments out the next line.
  2. Use Ctrl-v together with a motion command (e.g., % to jump between {} pairs).

Leveraging plugins

If manual tinkering feels old school, try plugins like tpope's vim-commentary:

Plug 'tpope/vim-commentary'

Being sly as a fox, now look more like a python. 🦊➡️🐍