Last Updated: November 19, 2020
·
81.13K
· sickill

Automatically set paste mode in Vim when pasting in insert mode

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()

Related protips:

Basic Vim commands - For getting started

5 Responses
Add your response

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

over 1 year ago ·

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

over 1 year ago ·

Thanks for your posting. It was helpful.

over 1 year ago ·

This worked for me, thanks.

over 1 year ago ·

Thank you for this! The 'non-tmux' version now works in tmux. In fact, I made a plugin out of it:

https://github.com/ryanpcmcquen/fix-vim-pasting

over 1 year ago ·