VIM Tip of the Day: leave python comments indented, don’t put cursor at beginning of the line

Posted by Mike on May 15th, 2009

If you’re ever been annoyed by VIM throwing your cursor to the left margin when you type “#” in a python file, there’s a simple remedy. It’s the fault of “smartindent” in VIM, which in reality isn’t all that smart. If you want to leave smartindent on but fix the weird hash behavior, throw the following in your $HOME/.vimrc.

:inoremap # X<C-H>#

See http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash


2 Responses

  1. Jonathan Says:

    But the question is, why would you want to leave smartindent on when editing python (or anything for that matter)? I’m sure an indent feature with a few hard-coded rules for C-like languages was awesome back in the ’80s ;P but we’ve moved on since then. Vim has real python specific indentation support, which is actually intelligent and actually tailored to the language in question.

    Just put “filetype plugin indent on” in your vimrc and make sure smartindent is off (it interferes with filetype indentation). Leaving autoindent on can be nice for consistent formatting in comments (it just carries the previous line’s indentation to a new line, if the python indentation support doesn’t override it because you just entered a new code block).

    You’ll also want to setup your PEP8-friendly softtabstop, shiftwidth, expandtab, smarttab, etc. settings. I’d recommend doing that inside a .vim/ftplugin/python/pep8.vim file, which will be auto-loaded anytime you edit a python language file.

    You could stick a “setlocal nosmartindent” in that pep8.vim file if you wanted to keep smartindent on for everything except python, but I think you’ll find that vim’s filetype indentation will have support for and be superior to smartindent for nearly every language around.

  2. Mike Says:

    Jonathan: Thanks for the thorough reply!

    The only value I seem to get from smartindent is what you mentioned — the comment formatting (which admittedly is still hokey, even with this kludge).

    I did already have the `filetype plugin indent on`, but had the softtabstop/shiftwidth/etc. inline in the .vimrc, rather than externalized in `ftplugin/python.vim`

    Looks like it’s time to clean up my .vimrc.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.