DEV Community

Andy Huynh
Andy Huynh

Posted on

create a shortcut to toggle paste mode with Vim

copy cat

Vim has a paste mode you can toggle on or off - :set paste and :set nopaste. What if you can do this with less keystrokes?

Essentially, these commands prevent weird formatting when pasting text into your editor.

I will say - copy/pasting isn't a trivial action. Expect to perform copy/paste tenfold throughout your career. Typing out these commands gets cumbersome. If only we can shortcut this to improve your workflow.

Below is a leader command to which you can add to.vimrc (config file). Leader commands are merely a fancy shortcut native to Vim.


function! TogglePaste()
    if(&paste == 0)
        set paste
        echo "Paste Mode Enabled"
        set nopaste
        echo "Paste Mode Disabled"

map <leader>p :call TogglePaste()<cr>
Enter fullscreen mode Exit fullscreen mode

No Vimscript knowledge necessary. Just "copy/paste" this snippet to your .vimrc.

Ensure your terminal shell of choice knows about your updates. I either restart my terminal session or source my .vimrc.

Toggle on paste mode: hit the key combination \ + p. If this doesn't work... ensure you're in Vim normal mode (not insert or visual).

Toggle off paste mode: \ + P.

Top comments (2)

moopet profile image
Ben Sinclair

You can use ! to toggle the state of an option, so I have this:

inoremap <F3> <esc>:set paste!<cr>i
nnoremap <F3> :set paste!<cr>
Enter fullscreen mode Exit fullscreen mode

It doesn't give me feedback as a message, but I have the PASTE option in my statusbar so it's always visible.
My config has F2 - whitespace and 80-column hint, F3 - paste mode, F4 -indentlines. This is because They're otherwise unused functions between F1 (which is often shadowed by the terminal emulator) and F5 (which is conventionally for debugging).

andy4thehuynh profile image
Andy Huynh

Did not know this! Thank you.

I'm using the newer macs that come w/ a touchbar. I rarely have F2, F3 etc at my fingertips. Will come back to this if I use a different machine.