A little Vim trick I learned today
I learned a neat new trick today that greatly improves my work with Vim when I’m editing code.
I like to copy and paste snippets of existing code into new code to save time and effort. The way pasting works when Vim has identified the file I’m editing as code of some sort, is to indent each new line by the default number of spaces. That means each pasted line is indented further towards the right of the screen. Also, once this autoindent feature detects a comment line, all lines after that are converted to comments. The results look like Figure 1. The amount of additional indent for each line is the Vim default of 8 spaces.
# This is data before the point at which I paste the new lines of code
code
code
code
# New code pasted below here
Line 1
Line 2
Line3
Line4
etc...
Figure 1: Each line is indented further when pasting code.
This is not what I want when editing code with Vim. Instead of struggling with this yet again, I spent some time researching the Vim configuration. The fix to this is simple. When I want to paste code into a document I set the paste option with the command, :set paste, in Vim command mode. To turn it off, I use the command, :set nopaste.
The set commands don’t make an option change permanent. The original Vim configuration will be restored when Vim is restarted. The change can be made permanent for your own account in your ~/vimrc file, and globally for all users in /etc/vimrc.
You can check the current status of all settings with the command :set all. The results are sorted alphabetically by columns. The status of the paste option can be checked with :set paste? — or any other option, too.