I'm setting up my .vimrc for learning Python. So far I have:

" configure expansion of tabs for .py files
au BufRead,BufNewFile *.py set expandtab

set expandtab       " Use spaces instead of TAB
set tabstop=2       " One TAB equals 2 spaces
set softtabstop=2
set shiftwidth=2    " Spaces to use for autoindent
set autoindent      " Copy indent from current line on new line   
set ruler       " show line and column number
syntax on       " syntax highlighting
set smartindent

" keep indentation on comments (#)
" http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash
:inoremap # X<BS>#

My question is -- every time I start a line with a #, it is a comment and to make it pretty I always add a space after the hash. Is there a way to ask vim to insert said space automagically? It doesn't necessarily need to be at the beginning of the line, though that would be ideal.

  • I've defined a user command if I have to comment more than one line: command! -range CommentShellScript <line1>,<line2>s/^/# /g Then I do a VISUAL LINE select and execute it
    – ka3ak
    Feb 7, 2017 at 7:26

1 Answer 1


Add the following line to ~/.vim/ftplugin/python.vim:

inoremap # #<space>

Alternatively, you can add this setting to your vimrc file by adding the following line:

autocmd BufRead,BufNewFile *.py inoremap # #<space>
  • I don't know. I tried it and it didn't work. I tried it with both <space> and also with just a space character, inoremap # # . Neither one did the trick.
    – Stephen C
    Feb 7, 2017 at 2:34
  • Just retested it. Works for me. Perhaps try setting it manually by opening up a python file, typing :inoremap # #<space>, and then hitting the enter key. Then retest. If that works, the problem is that your vim is not checking the python.vim file I listed for some reason. Feb 7, 2017 at 2:45
  • 1
    I've edited this solution to include a description of how to set this mapping from your vimrc file. Feb 7, 2017 at 2:52
  • I'd never heard of the ~/.vim/ftplugin/python.vim folder before and it didn't exist on my system. Like a good *NIXer, I did some research and found that in order to enable the ftplugin folder, I had to add filetype plugin to my .vimrc file. After that it worked, though it broke some of my indentation. Still fiddling with it.
    – Stephen C
    Feb 7, 2017 at 4:19
  • @StephenC Read :h filetype-plugin and :h startup. To override settings in a ftplugin you need to do that in a corresponding file placed in ~/.vim/after/ftplugin. It's worth spending 5 minutes to understand how things are supposed to work together. Feb 7, 2017 at 5:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .