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

10

Automatically set paste mode in Vim when pasting in insert mode

7895 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

Add a comment