Get vim to paste content without modification

Clipboard_lockedWhen content is pasted into vim, it tries to automatically detect and re-indent the content. This works most of the time but sometimes it does not, and that can be annoying, but vim would not be so popular if there wasn’t a way around this!

Experience shows that with some types of file, vim does not re-indenting them correctly. For example, the result of pasting  a configuration section into an ssh config file can end up like this.

Advertisements

vim_paste_with_autointend

The screenshot shows the pasted section is entirely commented out, and not only that, but it is also incorrectly indented. Correcting this by editing the result can be painful, thankfully there is no reason to do this, as there is a way to paste the content correctly.

Why is vim behaving like this? It’s simple, vim tries to assist when writing the file. So when a line starts with a hash “#” it knows to highlight it as comment. When you press Enter to get into the new line, vim assumes you want to continue to write comments and starts the next line with a hash symbol automatically. This can be really nice for writing in the editor. In the same way, vim will indent depending on the syntax you write, like loops in a shell script

Vim provides an option called “paste” to help in pasting text unmodified. To change the way vim handles the pasted content, enter the following command.

:set paste

When the option is set to “paste”, the INSERT mode will show an indication “(paste)” to indicate this state. When now the same content is pasted into the editor, the result is as expected.

vim_paste_without_autointend

To switch back afterwards, enter the following command.

:set nopaste

This will set the option back so that the automatic indentation will be used again while entering more content.


Read more of my posts on my blog at https://blog.tinned-software.net/.

This entry was posted in Linux Administration and tagged , . Bookmark the permalink.