[python] How to comment out a block of Python code in Vim

I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or n lines above/below current cursor position).

So basically something that converts the following

def my_fun(x, y):
    return x + y

to

#def my_fun(x, y):
#    return x + y

I am okay with using either # or """ for commenting out the relevant lines. Ideally, I would also like the same keymapping to uncomment the lines if the given lines have been commented out.

This question is related to python vim editor

The answer is


one way manually

:set number
:10,12s/^/#

I usually sweep out a visual block (<C-V>), then search and replace the first character with:

:'<,'>s/^/#

(Entering command mode with a visual block selected automatically places '<,'> on the command line) I can then uncomment the block by sweeping out the same visual block and:

:'<,'>s/^#//

You could add the following mapping to your .vimrc

vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>

Highlight your block with:

Shift+v

# to comment your lines from the first column.

-# to uncomment the same way.


No plugins or mappings required. Try the built-in "norm" command, which literally executes anything you want on every selected line.

Add # Comments

1. shift V to visually select lines
2. :norm i#

Remove # Comments

1. visually select region as before
2. :norm x

Or if your comments are indented you can do :norm ^x

Notice that these are just ordinary vim commands being preceded by ":norm" to execute them on each line.

More detailed answer for using "norm" command in one of the answers here

What's a quick way to comment/uncomment lines in Vim?


A very minimal light weight plugin: vim-commentary.

gcc to comment a line
gcgc to uncomment. check out the plugin page for more.

v+k/j highlight the block then gcc to comment that block.


NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.

Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.

(The default <leader> key in vim is \)


Highlight your block with: ShiftV

Comment the selected block out with: :norm i# (lower case i)

To uncomment, highlight your block again, and uncomment with: :norm ^x

The :norm command performs an action for every selected line. Commenting will insert a # at the start of every line, and uncommenting will delete that #.


There's a lot of comment plugins for vim - a number of which are multi-language - not just python. If you use a plugin manager like Vundle then you can search for them (once you've installed Vundle) using e.g.:

:PluginSearch comment

And you will get a window of results. Alternatively you can just search vim-scripts for comment plugins.


CtrlK for comment (Visual Mode):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU for uncomment (Visual Mode):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

There are some good plugins to help comment/uncomment lines. For example The NERD Commenter.


I have the following lines in my .vimrc:

" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N><C-N>    <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n

" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N>n     <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

The shortcuts preserve your cursor position and your comments as long as they start with # (there is space after #). For example:

# variable x
x = 0

After commenting:

# variable x
#x = 0

After uncomennting:

# variable x
x = 0

Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to vim

Why does using from __future__ import print_function breaks Python2-style print? How to run vi on docker container? How can I install MacVim on OS X? Find and replace strings in vim on multiple lines Running Python code in Vim How do I set the default font size in Vim? Move cursor to end of file in vim Set encoding and fileencoding to utf-8 in Vim How to select all and copy in vim? Why I've got no crontab entry on OS X when using vim?

Examples related to editor

Select all occurrences of selected word in VSCode Change the Theme in Jupyter Notebook? How to view Plugin Manager in Notepad++ Set language for syntax highlighting in Visual Studio Code Copy text from nano editor to shell How do I duplicate a line or selection within Visual Studio Code? How to set editor theme in IntelliJ Idea How to change background color in the Notepad++ text editor? What is the difference between Sublime text and Github's Atom What are the advantages of Sublime Text over Notepad++ and vice-versa?