Where developers come to connect, share, build and be inspired.

9

Automatically set paste mode in Vim when pasting in insert mode

7350 views


When you want to paste something in terminal (non-gui) Vim you often want to run the following command before pasting:

set paste

And following after pasting:

set nopaste

This prevents Vim from auto-indenting the pasted code. Some people use pastetoggle to make it a little easier:

set pastetoggle=<F2>

Now you hit F2 key to toggle the paste before and after pasting.

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.

Note that if you use Vim inside of a Tmux session then you need to double escape the codes in tSI/tEI. The above config for Tmux users looks like this:

function! WrapForTmux(s)
  if !exists('$TMUX')
    return a:s
  endif

  let tmux_start = "\<Esc>Ptmux;"
  let tmux_end = "\<Esc>\\"

  return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
endfunction

let &t_SI .= WrapForTmux("\<Esc>[?2004h")
let &t_EI .= WrapForTmux("\<Esc>[?2004l")

function! XTermPasteBegin()
  set pastetoggle=<Esc>[201~
  set paste
  return ""
endfunction

inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()

Comments

  • User-avatar

    nice trick.

    my solution to this has been to paste in normal mode from the X-clipboard-register '+'. This also preserves formatting, but it is a bit of a finger stretcher on my keyboard :)

    See http://vim.wikia.com/wiki/Accessing_the_system_clipboard

    One thing is great about getting the X clipboard register into your fingers, though. It also works the other way around, you can yank to X the same way: "+y

  • User-avatar

    Hey, pretty new to Vim, was wondering how can I tweak it to exit insert mode after the operation?

  • 4b9ec8c8d167bbef276355fff6db59b7

    Thanks for your posting. It was helpful.

  • 9b029fbe569b3af35c235aedb2420b7b

    This worked for me, thanks.

Add a comment