gvim auto copy selected text to system clipboard (to share it with apps ) - vim

I wonder, how i can enable auto copy of selected text into '+'
register in Ubuntu (to share clipboard between apps)?
On win XP, i have
set guioptions+=a
and its works perfectly, but not in Ubuntu 11.10.
Also, i tried
set clipboard=unnamedplus,unnamed,autoselect,exclude:cons\|linux.
but without success.
Please do not offer hand-click solutions like
vmap <C-Insert> "+y and mouse copy/paste.
test case (with "behave mswin" option):
open gvim
shift-v, move cursor and Esc (select lines in visual mode)
go to firefox and click ctrl-v or ctrl-Insert to paste text
Solution
In this thread, problem was solved.
You need to apply patch from Christian Brabandt.
Also, if you have problem with paste with shift-insert after recompilation in ubuntu, you can add this in your vimrc:
if has("gui_running")
map <silent> <S-Insert> "+p
cmap <S-Insert> <C-R>+
imap <silent> <S-Insert> <Esc>"+pa
endif

Does "+y work? It's not a suggestion: if this command doesn't work, you may have some underlying problems that prevent a simple solution. So it needs to be checked first, even if it sounds stupid.
set clipboard+=unnamedplus is enough if your version of Vim supports it. Mine is 7.3.35 and it doesn't work (Vim doesn't complain, though).
I don't know exactly which patch introduced unnamedplus but you can do :help 'clipboard' (with the single quotes) to have a list of available options. If unnamedplus is listed, the snippet above should fix your problem. If it's not there you won't be able to use it (obviously): time to re-assess your "do not offer hand-click solutions like vmap "+y and mouse copy/paste" requirement or compile a more recent version of Vim.

Try following:
set guioptions+=P
Explanation:
TLDR: a puts text into "* register. P puts text into "+ register
From :help guioptions
'a' Autoselect: If present, then whenever VISUAL mode is started,
or the Visual area extended, Vim tries to become the owner of the
windowing system's global selection. This means that the Visually
highlighted text is available for pasting into other applications as
well as into Vim itself. When the Visual mode ends, possibly due to
an operation on the text, or when an application wants to paste the
selection, the highlighted text is automatically yanked into the "*
selection register. Thus the selection is still available for
pasting into other applications after the VISUAL mode has ended.
If not present, then Vim won't become the owner of the windowing system's global selection unless explicitly told to by a
yank or delete operation for the "* register. The same applies to
the modeless selection.
'P' Like autoselect but using the "+ register instead of the "*
register.

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.

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".

Map shift-tab in vim to inverse tab in Vim

I've done some searching and found a wealth of information on binding keys in vim, but I can't find out, for sure, how to map shift-tab. Or what command I need to map it to for it to "tab backwards".
This is what I have at the moment:
map <S-tab> <S-,><S-,>
Possibly Relevant Information:
I'm running Debian with Terminal 2.22.3. with VIM - Vi IMproved 7.1
Vim already has built-in key commands for insert mode to shift the current line left or right one &shiftwidth. They are (in insert mode):
Ctrl-t : shift right (mnemonic "tab")
Ctrl-d : shift left (mnemonic "de-tab")
If you still want to use shift-tab, this is how you do it:
" for command mode
nnoremap <S-Tab> <<
" for insert mode
inoremap <S-Tab> <C-d>
Debugging why shift-tab in vim isn't performing an inverse tab in Vim
If you placed the code inoremap <S-Tab> <C-d> into your .vimrc and vim still isn't responding in insert mode, then that means your Shift-tab is being intercepted, gobbled, and ignored somewhere in the perilous 4-part journey between your keyboard and vim. You need to figure out where your Shift-Tab is getting silently orphaned.
Four stage journey of Shift+Tab between keyboard and vim
Keyboard -> Operating System
The first step of a keystroke's journey is the operating system that intercepts all keys and stops some of them to perform a behaviors for the Operating system. For example Alt+Tab which often means "change focus of current window to the next". If you send Alt+Tab into vim, vim will not respond because the operating system gobbled it. You have to find this keymapping area on your operating system. Windows, Mac and Linux are all different, and they have different programs that manage which keys are intercepted and which pass through to applications. Find this area and make sure your Shift+tab is set to pass-though to the Terminal you use.
Operating System -> Terminal Application
Step 2 assumes the OS allowed your Shift+Tab to pass through to your terminal Application that has focus. Your terminal application should have a configuration menu option (Most have more than one, that fight each other) under Settings -> shortcuts, or settings -> keymaps. There are hundreds of terminal apps out there and each have different ideologies for which keystrokes to trap and gobble and perform some action native to the app, or which to pass through to the shell. Find this area and make sure your Shift+tab is allowed to pass through and is passing through.
Terminal Application -> your Shell
Step 3 assumes your Terminal application allowed Shift+Tab to pass through to the shell. There is an area that defines which key combos are intercepted to perform an action on the shell, which pass through to the application that is on the front. For me this is inputrc but mac and Windows have different areas. You'll have to find this file and clear out anything that may be gobbling your Shift+Tab and erase that, or add a rule that says pass through.
Shell -> vim
Now we're at the level of Vim where the .vimrc can hear, trap and or rebroadcast the Shift+Tab to the next step in the command chain, and do whatever you want while it does so. Vim has the map keyword that controls this.
There's even a 5th step in the journey if we're talking about Browsers or webpages, who have interpreter engines that allow client side code to remap keys. But that's for a different post.
Debug chain instructions to isolate where your Shift+Tab is orphaned:
Make sure your OS isn't gobbling your Shift+tab and performing no-action. Try a different application like Eclipse, Browser or Notepad, and see if Shift+Tab performs any action. If it does then The OS is likely passing through your Shift+tab unaffected to applications.
Make sure your terminal app can receive and is receiving the Shift+Tab. Verify this by going to settings -> Shortcuts and erase any keymap that has Shift, or Tab in the name, then make a new keymapping that intercepts Shift+tab and performs some simple action like new tab doesn't matter. Save it, put focus in the terminal and press it, if a new tab appears then Terminal can hear and respond.
Make sure your terminal is passing through Shift+Tab to shell. Erase anything smelling of Tab or Shift in Settings -> keymaps and Settings -> Shortcuts. The default action (should be) do nothing and pass through.
Open any other shell program like nano, ed, or emacs. If any of these perform any action when you press Shift+Tab, then it's likely that the terminal is passing through Shift+tab to vim.
At this point we know vi/vim is receiving Shift+Tab, but not responding to it. To isolate the problem, blow away all your vim config files like .vimrc, .profile and anything under .vim. The problem could even be with vim or under /etc You run vanilla vim using vim -u NONE and make sure you're running vim. Vim's default behavior is straight pass through. So if Shift+Tab isn't doing something, then vi is bugged.
Uninstall vim with a blank config files/directories and re-install. If this doesn't work, then your operating system is bugged. Reinstall the operating system. If this doesn't work, throw the computer in the trash.
To test if vim actually gets your shift+tab go into insert mode
ctrl+v then tab and it should create a tab character
ctrl+v then shift+tab and it should create an inverse tab character (which appears as ^[[Z)
If it does not, then vim is not receiving the shift+tab input
In my case it was my terminal.
In the terminal window -> settings -> shortcuts
search shift+tab and unmap
OP's question specifies map, which applies to normal, visual, select, and operator-pending modes (see :h mapmode-nvo). I'm not sure such a mapping makes any sense in operator-pending mode, but it's very useful in visual and select modes. I'll also add forward indentation for completeness:
" both visual and select modes at once. gv means reselect the last selection
vnoremap <Tab> >gv
vnoremap <S-Tab> <gv
" just visual mode. this is unsurprisingly the same as vnoremap
xnoremap <Tab> >gv
xnoremap <S-Tab> <gv
" just select mode. <C-o> leaves select mode for visual mode, where the
" command is performed, and <C-g> reenters select mode from visual mode
snoremap <Tab> <C-o>>gv<C-g>
snoremap <S-Tab> <C-o><gv<C-g>
Please do note that Tab and CTRL-i map to each other in most terminal emulators, so mapping Tab can have unexpected results. See this question for more.
The following can be used with Vim tabs:
map <TAB> <ESC>gt<CR>
map <S-TAB> <ESC>gT<CR>

gvim: Easy copying into system clipboard

I am using gVim on Ubuntu 10.10. I want to copy (yank) text to the system clipboard, so that the copied text is available in other applications.
This works with "+y. But I want to have it working with y.
I have tried to map y to "+y but then yy doesn't work anymore (since it produces "+y"+y).
I have also tried
:set clipboard=unnamed
but this works only the other direction: Text in the system clipboard I can paste with p.
Did you try to map with this command:
noremap y "+y
? This mapping contains a serious mistake: it maps y in normal, visual and operator-pending modes, while you need only normal and visual modes. Use the following:
nnoremap y "+y
vnoremap y "+y
Also try set clipboard=unnamedplus (it requires at least vim-7.3.74). set clipboard=unnamed works in both directions, but it sets «mouse» (*) register which is different from clipboard register (+).
Most online solutions simply tell you to map y to "+y. But sometimes the issue is "+y doesn't even work. You do need to check what features your vim has been compiled with.
Try the steps below:
Open your terminal, run vim –-version | grep xterm_clipboard
Check the sign before xterm_clipboard, if it’s a + (plus sign), go to step 4.
If it’s a - (minus sign), run sudo apt-get install vim-gnome, then sudo update-alternatives –config vim, select vim.gnome in the list (You should use the proper command that corresponds to your system). Run command vim –-version | grep xterm_clipboard again, now you should be able to get + (plus sign).
Check whether your system clipboard uses + (plus sign) or * (star sign) register of vim, this depends on the OS you're using, sometimes they’re equivalent. How to check? Just copy some random text, then open vim and type :reg, check which register shows the string you just copied. If it’s a + (plus sign), add set clipboard=unnamedplus to your .vimrc. If it’s a * (star sign), add set clipboard=unnamed.
Test it out. Copy something inside vim, and then type :reg to check if the system clipboard has changed. If it does, your will get whatever is in that register when you paste outside of vim.
I have the very same idea as you, but I did it for years.
nnoremap yy yy"+yy
vnoremap y ygv"+y
Note that now yy command does two things: First it yank to register as normal, and then it yank to " register (system clipboard). The y command does the same thing. This is because I want to keep the multiple clipboard functionality of Vim.
For pasting from system clipboard, I used to have noremap gp "+p (global pasting), but now I use the excellent plugin Yankring.
Select some text in visual mode and it will be inserted into the system clipboard (the one where you middle-click to paste, I cannot recall the exact name).
If you set mouse=a you can use the mouse for visual selection like you would in many other applications.
In my case, I can sometimes copy from gvim to the system clipboard and sometimes not. I found a workaround, though I don't understand the underlying problem. If I copy text in another application (e.g. Notepad, as I am on Windows 7), then I can copy text from gvim and paste it elsewhere. It looks I need do this for each copy out of gvim.

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