I'm having hard time with vim smart indent vim feature while editing Python code. In general I like :set nocompatible option in vim, together with :set autoindent (and/or :set smartindent). Everything is fine except one very annoying behavior. Let's say you code something and then would like to insert a Python code snippet which you grab from elsewhere. The python code snippet may contain a comment, e.g.
# comment1
a=1
# comment2
b=1
In vim, when you enter insert mode, e.g. typing o, and do your code paste, vim will do too much job of indenting your code and instead of your snippet you'll get
# comment1
# a=1
# # comment2
# b=1
so it inserts additional comments (pound sign) after a first comment and preserves it for the rest of the code snippet. Now imaging that you have quite long code snippet with different identination and you can imaging how ugly your paste action will looks like (code will be improperly indented and commented).
Is there is any way to fix it?
The only way I fix the problem is to set vim compatible mode together with noautoindent option and then paste code snippet. Doing so it will insert it correct (as is). But switching between modes (nocompatible vs compatible) is too much (call me lazy, but it should be a way to properly insert snippets with comments in nocompatible mode). Setting noautoindent in nocompatilbe mode does not make any difference (the problem still exists), so it has something to do with compatible/nocompatible modes.
set pasteis the correct approach to this problem, I feel that I should point out that the comment character is inserted due to the 'r' flag of theformatoptionssetting in case someone happens across this trying to disable that behavior in general.