Turning off auto indent when pasting text into vim

I am making the effort to learn Vim.

When I paste code into my document from the clipboard, I get extra spaces at the start of each new line:

line
  line
    line

I know you can turn off auto indent but I can't get it to work because I have some other settings conflicting or something (which look pretty obvious in my .vimrc but don't seem to matter when I take them out).

How do I turn off auto indenting when I paste code but still have vim auto indent when I am writing code? Here is my .vimrc file:

set expandtab  
set tabstop=2  
set shiftwidth=2  
set autoindent  
set smartindent  
set bg=dark  
set nowrap  

Update: Better answer here: https://stackoverflow.com/a/38258720/62202

To turn off autoindent when you paste code, there's a special "paste" mode.

Type

:set paste

Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) --.

After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.

:set nopaste

However, I always found that cumbersome. That's why I map <F3> such that it can switch between paste and nopaste modes while editing the text! I add this to .vimrc

set pastetoggle=<F3>

To avoid undesired effects while pasting, there is an option that needs to be set:

set paste

A useful command to have in your .vimrc is set pastetoggle=<F10> or some other button, to easily toggle between paste and nopaste.


I usually use :r! cat and then paste ( shift + insert ) the content, and CTRL+D.

No need to enable & disable, direct usage.


If you are working locally, you can paste from the system clipboard with the key sequence:

"+p

This is a proper vim command, so no need to worry about entering an insert mode or switching off autoindent first.

Of course if you are working remotely (console over SSH, for example) then this won't work and you should go the :set noai, insert mode, paste into console, leave insertmode, :set ai route as described elsewhere.