Sunday, August 31, 2014

Avoiding automatic indentation when pasting code into vim

I am a vi user and use vim almost daily. One issue that has troubled me is that vim automatically inserts indentations to already well-indented text when I paste the text, e.g., bibtex entry, program segments, into vim because I enabled "autoindent". A solution to address the problem is to inform vim that you are about to paste and then vim will simply paste the text as is,

  1. In vim command mode, type
    :set paste

  2. Then, in vim edit mode, paste the text
  3. Finally, in vim command mode, type
    :set nopaste

The credit goes to this Stackoverflow post.

To make switch the paste option on or off easier, we may map the commands to a key or a key sequence. For instance, we can define a mapping ",p" to switch the paste option on or off in the vim command mode by adding the following code snippet into the .vimrc file (located at the $HOME directory),


let mapleader = ","
nmap <silent> <leader>p :set paste!<CR>
 \ <Bar>:echo "Paste: " . strpart("OffOn", 3 * &paste, 3)<CR>
set nopaste

The "echo" part above displays an indicator to show whether the paste option is on or off.

1 comment:

  1. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete