Saturday, March 19, 2011

Disable auto indent when pasting code text into vim

Method 1:
Paste toggle

Put the following in your vimrc (change the <F2> to whatever key you want):

set pastetoggle=<F2>

Note: if F2 key does not work, you might need to press ctrl-v F2 keys instead of just "F2" key.

To paste from another application:
Press (toggles the 'paste' option on).
Use your terminal to paste text from the clipboard. (Shift - Insert key)
Press (toggles the 'paste' option off).
Then the existing indentation of the pasted text will be retained.
If you have a mapping for , 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.

http://gala4th.blogspot.com/2009/11/toggle-auto-indenting-for-code-paste.html

Method 2:
When you copy multiple lines text and paste it into the vim , sometimes you might find the text is aligned wrongly as the following:

Line1
    Line 2
        Line 3
            Line 4

To solve this problem, enter the paste mode by

: set paste

Then do all the pasting works, and when finished, type

: set nopaste

Reference:
http://www.linuxask.com/questions/disable-auto-indent-when-pasting-text-into-vim

No comments: