copying text from vim to windows - vim

I am trying to copy a selection of text from vim to another windows application...say firefox or notepad for example. However I can't seem to do this with the y command. I have windows hotkeys enabled so by pressing ctrl-c I can achieve this but was hoping to get rid entirely of these windows commands in Vim.
Is this possible? also what about vice versa copying from windows and pasting into vim

I have
set clipboard=unnamed
in my ~/.vimrc. Then "yy", "D", etc, yank directly to the Windows clipboard. It also works in MacVim. For Linux gvim, you have to remember to prefix these operations with "+

I don't see any harm in using Windows command keys in GVim. Alternatively, you can also use the hotkey "+y for yanking (copying) and "+p for pasting to and from the system clipboard. This works on most platforms (Vim instances that are not directly attached to an X server on unix are a bit more difficult).

as per above answers:
"*y
"*p
Using ctrl-v will make entering control characters tough in insert mode, and ctrl-v is visual-block in normal mode, although so is ctrl-q.
Personally have found the following quite natural & little finger friendly
vmap <a-c> "*y
imap <a-p> "*p

Don't use windows bindings as you then won't be able to be as good in Vim on other platforms.
Use "*y - copy to system clipboard. It works well on Mac Os, Windows, Linux.

If you want to copy from a window (or from vim), try :
:set paste
But be careful other options may be modified. Everything is detailed in :
:help paste
Hope it helps.

For Windows 7, you need to edit the vim config file at:
C:\users\<User>\vimfiles\vimrc
just add the following line to the config file:
set clipboard=unnamed

Save the file, open it in another editor that uses standard Windows conventions, then copy and paste as you usually would.

Related

How to copy(External Sources) and paste on Vim [duplicate]

Unlike other editors, vim stores copied text in its own clipboard. So, it's very hard for me to copy some text from a webpage and paste it into the current working file. It so happens I have to either open gedit or type it manually.
Can I make vim paste from and to the system's clipboard?
Be aware that copying/pasting from the system clipboard will not work if :echo has('clipboard') returns 0. In this case, vim is not compiled with the +clipboard feature and you'll have to install a different version or recompile it. Some linux distros supply a minimal vim installation by default, but if you install the vim-gtk or vim-gtk3 package you can get the extra features nonetheless.
The "* and "+ registers are for the system's clipboard (:help registers). Depending on your system, they may do different things. For instance, on systems that don't use X11 like OSX or Windows, the "* register is used to read and write to the system clipboard. On X11 systems both registers can be used. See :help x11-selection for more details, but basically the "* is analogous to X11's _PRIMARY_ selection (which usually copies things you select with the mouse and pastes with the middle mouse button) and "+ is analogous to X11's _CLIPBOARD_ selection (which is the clipboard proper).
If all that went over your head, try using "*yy or "+yy to copy a line to your system's clipboard. Assuming you have the appropriate compile options, one or the other should work.
You might like to remap this to something more convenient for you. For example, you could put vnoremap <C-c> "*y in your ~/.vimrc so that you can visually select and press Ctrl+c to yank to your system's clipboard.
You also may want to have a look at the 'clipboard' option described in :help cb. In this case you can :set clipboard=unnamed or :set clipboard=unnamedplus to make all yanking/deleting operations automatically copy to the system clipboard. This could be an inconvenience in some cases where you are storing something else in the clipboard as it will override it.
To paste you can use "+p or "*p (again, depending on your system and/or desired selection) or you can map these to something else. I type them explicitly, but I often find myself in insert mode. If you're in insert mode you can still paste them with proper indentation by using <C-r><C-p>* or <C-r><C-p>+. See :help i_CTRL-R_CTRL-P.
It's also worth mentioning vim's paste option (:help paste). This puts vim into a special "paste mode" that disables several other options, allowing you to easily paste into vim using your terminal emulator's or multiplexer's familiar paste shortcut. (Simply type :set paste to enable it, paste your content and then type :set nopaste to disable it.) Alternatively, you can use the pastetoggle option to set a keycode that toggles the mode (:help pastetoggle).
I recommend using registers instead of these options, but if they are still too scary, this can be a convenient workaround while you're perfecting your vim chops.
See :help clipboard for more detailed information.
You can paste into vim by gnome-terminal's shortcut for paste.
Place the file in insert mode and use
Ctrl+Shift+v.
Remember beforehand to
:set paste
to avoid messing with the indentation.
I believe that this question deserves a more objective and pictorial answer:
Entering Paste Mode
ESC
:set paste
press i
SHIFT + Insert (with a text copied on your clipboard)
Leaving Paste Mode
ESC
:set nopaste
press i
You pasted the text and you're able to type again.
For my that configuration works for copying and pasting
" copy and paste
vmap <C-c> "+yi
vmap <C-x> "+c
vmap <C-v> c<ESC>"+p
imap <C-v> <ESC>"+pa
Linux
On my Linux system, the + and * registers map to an X11 selection, which can be pasted with the middle mouse button. When :set clipboard=unnamed and :set clipboard=unnamedplus are used, then the registers map to the clipboard, and can be pasted with CTRL-V.
The specifics seem to be somewhat configuration and system dependent, so your mileage will definitely vary. It should definitely get you pointed in the right direction, though.
See Also
http://vim.wikia.com/wiki/Accessing_the_system_clipboard
This would be the lines you need in your vimrc for this purpose:
set clipboard+=unnamed " use the clipboards of vim and win
set paste " Paste from a windows or from vim
set go+=a " Visual selection automatically copied to the clipboard
clipboard
There is a special register for storing this selection, it is the "*
register. Nothing is put in here unless the information about what text is
selected is about to change (e.g. with a left mouse click somewhere), or when
another application wants to paste the selected text. Then the text is put
in the "* register. For example, to cut a line and make it the current
selection/put it on the CLIPBOARD:
"*dd
Similarly, when you want to paste a selection from another application, e.g.,
by clicking the middle mouse button, the selection is put in the "* register
first, and then 'put' like any other register. For example, to put the
selection (contents of the CLIPBOARD):
"*p
registers E354
> There are nine types of registers:
> 1. The unnamed register ""
> 2. 10 numbered registers "0 to "9
> 3. The small delete register "-
> 4. 26 named registers "a to "z or "A to "Z
> 5. four read-only registers ":, "., "% and "#
> 6. the expression register "=
> 7. The selection and drop registers "*, "+ and "~
> 8. The black hole register "_
> 9. Last search pattern register "/
Paste from clipboard
1. Clipboard: Copy
2. Vim insertmode, middle mouse key
Check for X11-clipboard support in terminal
When you like to run Vim in a terminal you need to look for a version of Vim that was compiled with clipboard support.
Check for X11-clipboard support, from the console, type:
% vim --version
If you see "+xterm_clipboard", you are good to go.
http://vim.wikia.com/wiki/Accessing_the_system_clipboard
The X server maintains three selections, called:
PRIMARY, SECONDARY and CLIPBOARD
The PRIMARY selection is conventionally used to implement copying and
pasting via the middle mouse button. The SECONDARY and CLIPBOARD
selections are less frequently used by application programs.
http://linux.die.net/man/1/xsel
Copy To OS Clipboard
Select text in visual mode, press "*y
Paste From OS Clipboard
Press "*p
Didn't have +clipboard so I came up with this alternative solution using xsel:
Add to your ~/.vimrc:
vnoremap <C-C> :w !xsel -b<CR><CR>
Shift + Right Click -> Paste
did the trick for me
I tried the suggestions above and none of them worked in my environment. (Windows PuTTY clone over ssh)
Some additional googling turned up:
https://unix.stackexchange.com/questions/110684/copy-paste-into-sshd-vim-from-local-windows-clipboard
One of the comments suggested using SHIFT+INSERT which did the trick for pasting from my desktop's clipboard into Vim's buffer. Ctrl-C was already working to copy to the desktop's clipboard from Vim.
The simplest solution to this, that also works between different Linux machines through ssh is:
Check whether vim supports X-11 clipboard: vim --version | grep clipboard. If it reports back -clipboard and -xterm_clipboard you should install either vim-gtk or vim-gnome (gvim on arch linux)
Add the following lines to your .vimrc:
set clipboard=unnamedplus
set paste
If you login on a different machine via ssh, use the option -Y: ssh -Y machine
Now copying and pasting should work exactly as expected on a single, and across different machines by only using y for yank and p for paste. NB modify .vimrc on all machines where you want to use this feature.
What simply worked for me in Linux (Ubuntu 20.04)
Copying to system clipboard:
Select what you want to copy in Visual mode.
Type "+y
Press Enter
Paste something form system's clipboard:
Move to the place where you want to paste the copied text in vim.
Just type
"+P to paste before cursor OR
"+p to paste after cursor.
To know more how this works: Copy and Paste to/from Vim from/to Other Programs!
A quick note for people whose Vim installation does not support the * and + registers. It is not necessary to download a new Vim installation to paste from the clipboard. Here is an alternative method:
Install parcellite (a clipboard manager with a low memory footprint);
In your .vimrc file, add the following:
command Clip r !parcellite -c
Restart vim.
Now when you type in :Clip as an ex command, the contents of the clipboard will be pasted in at the cursor. You can also map the new command to a function key so as to be able to do this with one keystroke.
These key combinations work on any OS.
Select target Text using the mouse, and refer to the key sequences to copy, cut, and paste.
copy: Ctrl + Insert
paste: Shift + Insert
cut: Shift + Del
paste: Shift + Insert
This works for me: Ctrl+Shift+V
If you are using a mouse first do
:set paste
Then right click mouse and the contents in buffer will be pasted
I ran into this issue on a mid-2017 Macbook Pro running vim within iTerm2 as my primary development environment.
As other answers have suggested, I ran vim --version and noticed that it returns -clipboard, which means that the version of vim that shipped with my machine hasn't been compiled with the clipboard option.
The homebrew package for vim appears to compile with the clipboard option, so the fix for me was to:
Run brew install vim
Add set clipboard+=unnamed to my ~/.vimrc file
Close and reopen iTerm2
Following on from Conner's answer, which was great, but C-R C-p + and C-R C-p * in insert mode is a bit inconvenient. Ditto "*p and "+p from command mode.
a VIM guru suggested the following to map C-v to what C-r C-p + does.
You could have :inoremap <C-v> <C-o>"+p for insert mode only
if you really wanted to override blockwise visual mode (not recommended by him as visual
mode is good) you could have map <C-v> "+p
With Vim 8+ on Linux or Mac, you can now simply use the OS' native paste (ctrl+shift+V on Linux, cmd+V on Mac). Do not press i for Insert Mode.
It will paste the contents of your OS clipboard, preserving the spaces and tabs without adding autoindenting. It's equivalent to the old :set paste, i, ctrl+shift+V, esc, :set nopaste method.
You don't even need the +clipboard or +xterm_clipboard vim features installed anymore. This feature is called "bracketed paste". For more details, see Turning off auto indent when pasting text into vim
If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.
install vim:
brew install vim --with-lua --with-override-system-vim
install gui verion of vim:
brew install macvim --with-lua --with-override-system-vim
restart the terminal to take effect.
append the following line to ~/.vimrc
set clipboard=unnamed
now you can copy the line in vim with yy and paste it system-wide.
If you have it, try removing this from your vimrc:
set mouse=a
It messes with the paste functionality.
On top of the setting :set clipboard=unnamed, you should use mvim -v which you can get with brew install macvim if you're using vim on Terminal.app on Mac OS X 10.9. Default vim does not support clipboard option.
Based on #lis2 answer, I use a simpler configuration that will not force Insert mode at the end:
" Copy and paste
if has('clipboard') && !has('gui_running')
vnoremap <C-c> "+y
vnoremap <C-x> "+d
vnoremap <C-v> "+p
inoremap <C-v> <C-r><C-o>+
endif
Mind that all these override default Vim mappings:
v_CTRL-C: stop Visual mode
v_CTRL-X: subtract [count] from number
v_CTRL-V: blockwise Visual mode
i_CTRL-V: insert next non-digit literally, which is also mapped to i_CTRL-Q
As an alternative, one can use keys inspired in the "yank", "delete" and "put" Vim verbs: <C-y>, <C-d> and <C-p> respectively. These would only override one default mapping:
i_CTRL-P: backwards search keyword for completion
The other solutions are good if you want to change your vimrc, etc... However I wanted an simple way to copy from vim to my system keyboard. This is what I came up with.
Select the text you want to copy with visual mode v
Press : (it will automatically expand to show :'<,'>)
Type y * or y + (depending on your system) to yank the selected text to the system clipboard
Since vim 8 right click enables visual mode by default. This prevents the "normal" copy & paste (call it a "defect by design" https://github.com/vim/vim/issues/1326).
Fix it by doing:
echo "set mouse-=a" >> ~/.vimrc .
Exit and restart vim.
It may also be worth mentioning, on OSX using Vim, you can select text with the mouse, Cmd-C to copy to OSX system clipboard, and the copied text will be available in the clipboard outside of Vim.
In other words, OSX treats it like it were a regular window, and this is where the much-maligned Apple "Command" button comes in handy.
B-30
There are two simple ways to do this. Make your file in insert mode and
1) press the middle button (the scroll wheel) in your mouse, or
2) Ctrl + Shift + V
What you really need is EasyClip. It will do just that and so much more...
After entering the vim window, press I to enter into insert mode. Then move your cursor to the desire location and press Ctrl + Insert button simultaneously to paste from the clipboard.

gvim copy to and paste from external clipboard (Windows 7) using y and p keys?

My current gvim copy to and paste from external clipboard is set to ctrl+y and ctrl+p based on a tip I've found on the Internet last year. Is there a way to change these keys to y and p using vim's default yank and paste keys? This way, I don't have to select + copy the text twice (once for vim memory and another for clipboard memory).
I've tried to find the answer on the Internet, but wasn't able to find the answer to my exact problem.
Thank you.
You can create mapping, there is an alternative, however I don't have any windows system, so I cannot test it on win7, if it works. At least it works for gvim.
There is an option clipboard, you can set unnamedplus, to let vim use + as "default" register.
set clipboard=unnamedplus
:h 'clipboard' to check details.
This works on my windows gvim...
:map y "+Y
:map p "+gP
Personally, I just always type "+gP when I want to clipboard paste. It's not a hard muscle memory.

How to stop Vim from writing onto system clipboard when visually selecting texts

I am using Vim 7.4.423 on a Windows 7 machine.
I notice that Vim will copy to system clipboard of whatever texts that I have "highlighted" through Visual mode. Is there a way to stop him from do this?
The "overwriting of clipboard upon enter visual mode" does not differ whether I use mouse click or the V/v operator. Nothing on the system clipboard will be left once I enter the visual mode.
PS: I did not find mswin in my _vimrc.
Thank you!
This sounds like you either have an 'a' in your 'guioptions' option, or you have "autoselect" in your 'clipboard' option.
Check the output of this command to see which is the case and then fix it accordingly:
:verbose set clipboard? guioptions?
Solution, thanks to Ben's advice on guioptions.
Remove the following line:
set guioptions+=a
And make sure that <C-C> is behaving "normally". (Normally as for windows OS.)
vnoremap <C-C> "+y
The second mapping means to "feed onto system clipboard".

Cutting and pasting from vim and tmux

Is cutting and pasting from a vim session started from tmux completely broke?
If I want to cut from a github web into my vim session or vice versa, it rarely works or if it does, it is completely broke.
I have had others confirm that they find this difficult.
I am running on the following:
OS X 10.8.2
Vim 7.3
tmux 1.7
I am referring to the normal cut and paste commands Cmd + c and Cmd + v.
Are there any fixes or workarounds?
In Vim, you don't use Cmd+c/Cmd+v to "copy" and "paste": you use y/p, possibly with a register ("*y/"ap) to "yank" and "put".
If your Vim has clipboard support built-in, "*y should be enough to yank from Vim and "*p should be enough to put from another application. * is the "clipboard" register.
Again, supposing Vim has clipboard support, adding set clipboard^=unnamed to your ~/.vimrc should synchronize Vim's default register and the clipboard register; allowing you to simply use y˘and p.
The tmux/vim combo has a long standing issue with system clipboard on Mac OS X. It is fortunately very quick and easy to fix.
To see if your Vim build has clipboard support, type this command in your shell:
$ vim --version | grep clipboard
A + before a feature means "supports", - means "doesn't support".
just to add a little bit help.
getting vim with clipboard support might be helpful

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.
While setting the paste mode with paste/nopaste/pastetoggle is perfectly fine, you still have to manually enable paste mode before pasting and disable paste mode after pasting. Being the lazy person that I am, below is the best solution that I've found so far, which automatically toggles the paste mode when you paste.
Here's a little trick that uses terminal's bracketed paste mode to
automatically set/unset Vim's paste mode when you paste. Put following
in your .vimrc:
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"
inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction
Now you can paste without explicitly turning paste mode on/off - it is
handled automatically for you.
Source: Coderwall
Note: This solution doesn't work in WSL (Windows 10 Subsystem for Linux). If anyone has a solution for WSL, please update this answer or add it in the comments.
Tmux If using tmux, then the declarations need to be double escaped. The code for this is also in Coderwall
Mac users can avoid auto formatting by reading directly from the pasteboard with:
:r !pbpaste
Here is a post by someone who figured out how to remap the paste event to automatically turn paste mode on and then back off. Works for me in tmux/iTerm on MacOSX.
I just put set clipboard=unnamed in my .vimrc. That makes the default paste buffer map to X's clipboard.
So, if I mark a bit of text in a terminal, I can simply press p to paste it in vim. Similarly, I can yank things in vim (e.g. YY to yank the current line into the buffer) and middle click in any window to paste it.
I don't know. I find it super convenient.
Add this to your ~/.vimrc and you will only have to press F2 before and after pasting:
set pastetoggle=<F2>
I am a Python user who sometimes copy and paste into Vim. (I switched from Mac to Windows WSL) and this was one of the glitches that bothered me.
If you touch a script.py and then vi script.py, Vi will detect it is a Python script and tried to be helpful, autoindent, paste with extra indents, etc. This won't happen if you don't tell it is a Python script.
However, if that is already happening to you, the default autoindent could be a nightmare when you paste already fully indented code (see the tilted ladder shape below).
I tried three options and here are the results
set paste # works perfect
set noai # still introduced extra whitespace
set noautoindent # still introduced extra whitespace
When working inside a terminal the vim-bracketed-paste vim plugin will automatically handle pastes without needing any keystrokes before or after the paste.
It works by detecting bracketed paste mode which is an escape sequence sent by "modern" x-term compatible terminals like iTerm2, gnome-terminal, and other terminals using libvte. As an added bonus it works also for tmux sessions. I am using it successfully with iTerm2 on a Mac connecting to a linux server and using tmux.
Another answer I did not see until now:
:se paste noai
Stick this in your ~/.vimrc and be happy:
" enables :Paste to just do what you want
command Paste execute 'set noai | insert | set ai'
Edit: on reflection, :r !cat is a far better approach since it's short, semantic, and requires no custom vimrc. Use that instead!
Another way to paste is via <C-r> in insert mode and dropping the contents of the register (here the global register). See: :h i_ctrl-r and h i_CTRL-R_CTRL-O.
From the vim help documentation:
Insert the contents of a register literally and don't auto-indent. Does the same as pasting with the mouse. Does not replace characters! The '.' register (last inserted text) is still inserted as typed.{not in Vi}
So to paste contents into vim without auto indent, use <C-r><C-o>* in most unix systems.
You can add a mapping in the your vimrc inoremap <C-r> <C-r><C-o> so you can paste the contents of the * register normally without the auto indent by using <C-r>*.
Note: this only works if vim is compiled with clipboard.
Although :pastetoggle or :paste and :nopaste should be working fine (if implemented - they are not always as we can see from the discussion) I highly recomment pasting using the direct approach "+p or "*p and reading with "+r or "*r:
Vim has acess to ten types of registers (:help registers) and the questioner is interested in quotestar and quoteplus from section
Selection and drop registers "*, "+ and "~
Use these registers for storing and retrieving the selected text for the GUI.
See quotestar and quoteplus. When the clipboard is not available or not
working, the unnamed register is used instead. For Unix systems the clipboard
is only available when the +xterm_clipboard feature is present. {not in Vi}
Note that there is only a distinction between "* and "+ for X11 systems.
:help x11-selection further clarifies the difference of * and +:
quoteplus quote+
There are three documented X selections: PRIMARY (which is expected to
represent the current visual selection - as in Vim's Visual mode), SECONDARY
(which is ill-defined) and CLIPBOARD (which is expected to be used for
cut, copy and paste operations).
Of these three, Vim uses PRIMARY when reading and writing the "* register
(hence when the X11 selections are available, Vim sets a default value for
'clipboard' of "autoselect"), and CLIPBOARD when reading and writing the "+
register. Vim does not access the SECONDARY selection.
Examples: (assuming the default option values)
Select an URL in Visual mode in Vim. Go to your browser and click the
middle mouse button in the URL text field. The selected text will be
inserted (hopefully!). Note: in Firefox you can set the
middlemouse.contentLoadURL preference to true in about:config, then the
selected URL will be used when pressing middle mouse button in most places in the window.
Select some text in your browser by dragging with the mouse. Go to Vim and
press the middle mouse button: The selected text is inserted.
Select some text in Vim and do "+y. Go to your browser, select some text in
a textfield by dragging with the mouse. Now use the right mouse button and
select "Paste" from the popup menu. The selected text is overwritten by the
text from Vim.
Note that the text in the "+ register remains available when making a Visual
selection, which makes other text available in the "* register. That allows
overwriting selected text.
This works for me ( case for + register, what i use like exchange buffer between aps ):
imap <silent> <S-Insert> <C-O>:set noai<CR><C-R>+<C-O>:set ai<CR>
From vim: ]p
From outside: "*]p or "+]p
This issue has already been answered, but I though I could also add my own solution:
If you simply want to disable auto-indent system wise, for every file type (basically, disable the auto-indent feature completely), you can do the following:
Backup the indent.vim file:
sudo mv /usr/share/vim/vim81/indent.vim /usr/share/vim/vim81/indent.vim.orig
Create a new empty indent.vim file:
sudo touch /usr/share/vim/vim81/indent.vim
If you are on a mac, macvim seems to handle it well without having to toggle paste.
brew install macvim --override-system-vim
Please read this article: Toggle auto-indenting for code paste
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 fastest way I’m aware of to quickly go to paste-insert mode for a one-shot paste is tpope’s unimpaired, which features yo and yO, presumably mnemonics for “you open”. They’re only documented in his vimdoc, as:
A toggle has not been provided for 'paste' because the typical use case of
wrapping of a solitary insertion is so wasteful: You toggle twice, but
you only paste once (YOPO). Instead, press yo or yO to invoke o or O with
'paste' already set. Leaving insert mode sets 'nopaste' automatically.
Native paste / bracketed paste is the best and simplest way since vim 8 (released in 2016). It even works over ssh! (Bracketed paste works on Linux and Mac, but not Windows Git Bash)
Make sure you have vim 8+ (you don't need the +clipboard or +xterm_clipboard options).
vim --version | head -1
Simply use the OS native paste command (e.g. ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode.
Test
Copy (ctrl+shift+C or cmd+C) the output of this (2 lines with a tab indent) to the system clipboard:
echo -e '\ta\n\tb'
Launch a clean vim 8+ with autoindent:
vim -u NONE --noplugin -c 'set autoindent'
Paste from the system clipboard (ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode. The a and b should be aligned with a single tab indent. You can even do this while ssh-ing to a remote machine (the remote machine will need vim 8+).
Now try the old way, which will autoindent the second line with an extra tab: Press i for Insert Mode. Then paste using ctrl+shift+V or cmd+V. The a and b are misaligned now.
Installing Vim 8
Ubuntu 18.04 - comes with Vim 8 by default.
Ubuntu 16.04 - install from a PPA.
sudo add-apt-repository ppa:jonathonf/vim
sudo apt update
sudo apt install vim
Mac: brew install vim
The following vim plugin handles that automatically through its "Bracketed Paste" mode: https://github.com/wincent/terminus
Sets up "Bracketed Paste" mode, which means you can forget about manually setting the 'paste' option and simply go ahead and paste in any mode.
Sadly I found the vim plugin mentioned not to be working with iTerm2 3.0.15 (to be fair I don't know if this broke on older versions) - but I found this hack instead.
Map command-p to do the paste and using iTerm2 vim keys. Obviously this only works for iTerm2.
How it works. I use "jk" to enter escape mode so you will also need:
:inoremap jk
in your .vimrc.
Then it just invokes P to enter paste mode, "+p to paste from the clipboard and then P to disable paste mode. hth.
If you use the vim above v8.2, you can check with :help tmux-integration.
If you experience issues when running Vim inside tmux, here are a few hints.
You can comment-out parts if something doesn't work (it may depend on the
terminal that tmux is running in):
if !has('gui_running') && &term =~ '^\%(screen\|tmux\)'
" Better mouse support, see :help 'ttymouse'
set ttymouse=sgr
" Enable true colors, see :help xterm-true-color
let &termguicolors = v:true
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
" Enable bracketed paste mode, see :help xterm-bracketed-paste
let &t_BE = "\<Esc>[?2004h"
let &t_BD = "\<Esc>[?2004l"
let &t_PS = "\<Esc>[200~"
let &t_PE = "\<Esc>[201~"
" Enable focus event tracking, see :help xterm-focus-event
let &t_fe = "\<Esc>[?1004h"
let &t_fd = "\<Esc>[?1004l"
" Enable modified arrow keys, see :help xterm-modifier-keys
execute "silent! set <xUp>=\<Esc>[#;*A"
execute "silent! set <xDown>=\<Esc>[#;*B"
execute "silent! set <xRight>=\<Esc>[#;*C"
execute "silent! set <xLeft>=\<Esc>[#;*D"
endif

Resources