Toggle auto-indenting for code paste
From Vim Tips Wiki
Tip 906 • Previous Tip • Next Tip
Created: March 31, 2005 Complexity: basic Author: Adam MacKinnon Minimum version: 5.7 Karma: 10/15 Imported from: Tip#906
Pasting text into a terminal running Vim with 'autoindent' or 'smartindent' set can destroy the indenting of the pasted text.
With the following in your vimrc, you can press <F2> before and after pasting-in text from another application. Then the existing indentation of the pasted text will be retained.
set pastetoggle=<F2>
If you have a mapping for <F2>, that mapping will apply (and the pastetoggle function will not operate).
Some people like the visual feedback shown in the status line by the following alternative for your vimrc:
nnoremap <F2> :set invpaste paste?<CR> imap <F2> <C-O><F2> set pastetoggle=<F2>
The first line sets a mapping so that pressing <F2> in normal mode will invert the 'paste' option, and will then show the value of that option. The second line does the same in insert mode (but insert mode mappings only apply when 'paste' is off). The third line allows you to press <F2> when in insert mode, to turn 'paste' off.
See VimTip330.
