Vim auto set paste mode and nopaste mode

There has been a lot of time that i encountered a paste issue in vim insert mode. When copying some plain text and then go to terminal vim, set vim in insert mode, press Command+V, i always get extra characters after the text i copied.
For example: copy the code below

double d = 10.0;
Type t = d.GetType();
Console.WriteLine("the type of d is {0}", t.FullName);

to terminal vim, i get this:

double d = 10.0;
            Type t = d.GetType();
                    Console.WriteLine("the type of d is {0}", t.FullName);"}"))

Note the indentation is corrupted and some extra chars "}")) are appended to the original text. This is extremely annoying and can be avoided by setting paste mode in vim before pasting. But we need to recover the nopaste mode in most cases when using vim. So is there a way to auto set paste mode and nopaste mode before and after pasting? The answer is yes! Just put the lines below to your .vimrc:

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

References:
https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode

发表评论

邮箱地址不会被公开。 必填项已用*标注