12

When I copy and past a block of code in Vim, every line gets indented by one. For example, I have this source:

    print "Hello"
    print "World"
    print "I'm copying"
    print "and pasting"

Which gets jumbled when pasting into Vim:

print "Hello"
        print "World"
            print "I'm copying"
                print "and pasting"

For copying long lines of code, it's very frustrating because everything gets out of alignment (not good for python).

Here is my vimrc. It currently auto-indents on newlines, and replaces tabs with the standard 4 spaces.

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

While this config works, something is causing the copy-paste problem. How can this be fixed, but still retain the behaviors that I've defined?

MauroPorras
  • 5,079
  • 5
  • 30
  • 41
vuvume
  • 125
  • 1
  • 7
  • have you tried using the paste option? `:set paste` before you paste the code in vim – Imran Ali Dec 12 '16 at 16:30
  • 2
    Possible duplicate of [Turning off auto indent when pasting text into vim](http://stackoverflow.com/questions/2514445/turning-off-auto-indent-when-pasting-text-into-vim) – Imran Ali Dec 12 '16 at 16:52
  • `:r !cat` followed by `^D` avoids the need to switch in an out of any modes or set/unset an options. – sideshowbarker Dec 13 '16 at 01:12

1 Answers1

17

Use :set paste to switch to paste mode.

This article explains paste mode

It was made specifically for pasting text into vim so it doesn't trigger any input mappings. Remember to :set nopaste when you are done to get your mappings back.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • When pasting text Vim doesn't have any way to differentiate between a sequence of key strokes that you typed and pre-formatted lines that you are pasting unless you tell it. The author of the linked article seems unaware that TAB characters are *not* something any "sane" Python programmer would use. TAB characters should never be used in Python source code. https://peps.python.org/pep-0008/ Unfortunately popular discussion of this matter seems very badly informed: https://stackoverflow.com/questions/120926/why-does-python-pep-8-strongly-recommend-spaces-over-tabs-for-indentation – NeilG May 26 '23 at 07:39