2

Vim safe copy paste without bad indentation

The Horror

One thing that was always great with Linux desktop X11 (and continued with Ubuntu 12.10) was copying text with a mouse selection and just pasting it with the middle button. That’s why I became horrified when it started to not work with Vim!

I was evaluating a Perl Module and when I copy/pasted a block of an example code this happened

 

Borked Paste

It has to be a way to have a clean copy/paste again!

The Solution

Fortunately Vim has the notion of paste and so has a mode to activate it and ignore indentations and other features. You just activate it with :set paste

normal-set-paste-500

paste-mode-500

Change to insert mode

paste-mode-insert-500

and now just paste the text the way it was supposed.

Paste Ok

Hurray! Now press Esc and get back to our helpful indentations with :set nopaste.

paste-set-nopaste-500

normal-set-nopaste-500

Less typing, may I ?

Of course there’s a pragmatic way of doing all these. We can define a keyboard key to just make the copy/paste a safe operation. I’m using key F12.

:set pastetoggle=

In insert mode you can toggle the paste mode so you don’t despair with the wrong indentation. Add it to your .vimrc

Another way it’s to just paste what you want into the line you are at in visual mode.

map  :r! xsel

xsel is a command line X11 tool to manipulate its “clipboard”.
This mapping reads into Vim the output of xsel which is the clipboard copy buffer. I’m using this one.

You may need to install it but it’s simple

$ sudo apt-get install xsel

Conclusion

Vim customization and plugins broke a plain simple copy/paste. However we got a no brain and fast solution with our F12 key.

2 Comments

  1. Great! Really helped me out

    btw, love your statusline, would you mind to share?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.