Sometimes, when pasting code into Vim, I've found that each new line gets indented, so that if the text I copied started out like this:
My nice list:
Foo
Bar
Moo
Zoo
It ends up looking like this:
My nice list:
Foo
Bar
Moo
Zoo
It's a pretty annoying problem, especially if you're pasting in a lot of text that was neatly aligned or indented to begin with and which would now have to be re-aligned/indented all over again. Fortunately, it's an easy problem to solve.
The reason it happens is that Vim has an automatic indentation feature. This feature is useful for programming, because if you indent a line of code that you're writing, Vim will remember the indentation and apply it again when you begin the next line, which is ideal if that first indented line was the start of an indented block of code. Unfortunately, it's a slightly dumb feature in the sense that it's unintelligent. It just blindly indents the start of each new line as much as the previous one.
In the list above, because each item in the list was on a line that began with some indenting whitespace, Vim - if it had autoindent turned on - would indent the first item by the amount of whitespace it already possessed, and would then start the next line with that same amount of whitespace before pasting in the contents of the line. So the second item ends up with double the indentation of the first, and so on.
If this is happening to you, it probably means you've got a line in your .vimrc file which reads, set ai or set autoindent (these two commands are exactly equivalent: ai
is just an alias for autoindent
). If you don't need the autoindent feature switched on, just delete that line from your .vimrc. Alternatively, if you want it on most of the time, but not when you're pasting in text that's already indented, just make sure you're in command mode (by pressing the <ESC> key) and type:
:set noai
(note the colon at the beginning). Then hit <Enter>, and you'll have switched off autoindenting. Now enter insert mode where you want to paste your text (that is, use the keyboard to move your cursor to the appropriate place, and press i). Then paste your text, e.g. using Ctrl+v if you're on Windows or Apple-v if you're on a Mac. The indentations in the pasted text should have been preserved!
Now restore autoindent by going back to command mode (press <ESC> again), and type:
:set ai
Hit <Enter> again, and you're done!
Aha, it seems there’s an even easier way: paste mode! You can even bind this to a function key to save you having to issue the full command each time.