Pasting a block of code copied from elsewhere in Vim is a nightmare, unless you know how to do it right. The autoindent (and, possibly, smartindent) features of Vim go crazy when you yank and slap a block of text. How do you do it right, then? This is not a new trick, but something I did not know about for a long time, so I suppose it is reasonable to assume many others who use Vim may not have come across it either. It is called the “paste mode“. In Vim, you can enable the paste mode by typing “:set paste” on Vim’s command interface. Once the paste mode is enabled, you can paste the block(s) of code you have yanked from elsewhere, and disable the paste mode through the command “:set nopaste” as soon as you are done with pasting text. A bit inconvenient, but it is a handy feature to get familiar with if you use Vim a lot to write code.
Python programmers would run into syntax error problems if they execute source code files in which they pasted code in the paste mode. I am not completely certain on this, but when text is pasted in paste mode, the copied lines are indented with spaces irrespective of the tab character and tab width defined for the open Vim session. If you tend to indent source files by the tab character (something probably any sane Python developer should do), this will definitely create problems. There is an easy way to fix this. Just after you turn off the paste mode, highlight the pasted text by moving the cursor to the first line pasted, pressing “shift + v” to enable “visual” mode in Vim (which is used solely for highlighting blocks of text), and dragging the highlight marker down until all the pasted text is highlighted, and pressing either the right angle bracket (>) or the left (<) to conveniently indent the block of highlighted text right and left according to the tab character and tab width set for the current Vim session. Simply indenting left once, and then right once will get the block of code back to its original indent position, but will additionally (and this is the important bit) indent the block according to the currently defined tab width and tab character settings. Pretty convenient, eh?