Why does Vim indent pasted code incorrectly?

There're two reasons:

  • Auto insert comment
  • Auto indenting

For pasting in vim while auto-indent is enabled, you must change to paste mode by typing:

:set paste

Then you can change to insert mode and paste your code. After pasting is done, type:

:set nopaste

to turn off paste mode. Since this is a common and frequent action, vim offers toggling paste mode:

set pastetoggle=<F2>

You can change F2 to whatever key you want, and now you can turn pasting on and off easily.


To turn off auto-insert of comments, you can add these lines to your vimrc:

augroup auto_comment
    au!
    au FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o
augroup END

vim also provides a pasting register for you to paste text from the system clipboard. You can use "*p or "+p depending on your system. On a system without X11, such as OSX or Windows, you have to use the * register. On an X11 system, like Linux, you can use both.

Further reading

  • Accessing the system clipboard
  • How can I paste something to the VIM from the clipboard
  • fakeclip

Use the vim paste. What you want is to paste what is on the clipboard buffer "+p

This selects the + and pastes it in place.

If you're using Linux, * is the X/middle-click buffer (the last selected text).

Then vim knows it's a paste.

Otherwise vim thinks you have typed the keys being pasted and does its own auto-indentation (on top of your copied indentation) all the way to the end of the paste.

As a note for this to work over SSH you need to set the option for your clipboard to be shared -Y

See man ssh for more details.


The tabs were inserted because you have autoindent turned on and you can disable that behavior by turning off autoindent (:set noai) before you paste into terminal.

The commented lines are produced by auto commenting and can be disabled by turning that off.

Alternative to those you should get the desired behavior using the toggles :set paste, pasting your formatted code and :set nopaste to restore normal behavior.