How can I keep the code formatted as original source when I paste them to vim?

Do this before:

:set paste

Then after:

:set nopaste

http://vim.wikia.com/wiki/Toggle_auto-indenting_for_code_paste

Toggle auto-indenting for code paste

Background

If you use Vim commands to paste text, nothing unexpected occurs. The problem only arises when pasting from another application, and only when you are not using a GUI version of Vim. In a console or terminal version of Vim, there is no standard procedure to paste text from another application. Instead, the terminal may emulate pasting by inserting text into the keyboard buffer, so Vim thinks the text has been typed by the user. After each line ending, Vim may move the cursor so the next line starts with the same indent as the last. However, that will change the indentation already in the pasted text.

Paste toggle

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

set pastetoggle=<F2>

To paste from another application:

  • Start insert mode.
  • Press F2 (toggles the 'paste' option on).
  • Use your terminal to paste text from the clipboard.
  • Press F2 (toggles the 'paste' option off).

Then the existing indentation of the pasted text will be retained.

You do not have to start insert mode first, but if you are in normal mode and 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>
set pastetoggle=<F2>
set showmode

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 allows you to press F2 when in insert mode, to toggle 'paste' on and off. The third line enables displaying whether 'paste' is turned on in insert mode.


It is the autoindent that is messing with you.

set autoindent
set smartindent

Try to disable them when you cut and paste your code, and then enable them again when you are done.

Tags:

Vim

Copy Paste