How to maintain tabs when pasting in Vim


I use the tab key to indent my python code in Vim, but whenever I copy and paste a block Vim replaces every tab with 4 spaces, which raises an IndentationError

I tried setting :set paste as suggested in related questions but it makes no difference

Other sites suggest pasting 'tabless' code and using the visual editor to re-indent, but this is asking for trouble when it comes to large blocks

Are there any settings I can apply to vim to maintain tabs on copy/paste?

Thanks for any help with this :)


I am copying and pasting within vim using the standard gnome-terminal techniques (ctrl+shift+c / mouse etc.)

my .vimrc is:

syntax on
set ts=4
if has("terminfo")
let &t_Co=8
let &t_Sf="\e[3%p1%dm"
let &t_Sb="\e[4%p1%dm"
let &t_Co=8
let &t_Sf="\e[3%dm"
let &t_Sb="\e[4%dm"

I looked up that ts -> Sets tab stops to n for text input, but don't know what value would maintain a tab character

5/15/2013 3:21:03 PM

Accepted Answer

See :h tabstop for all the options and how they interact with each other.

These are good settings if you prefer tabs:

set tabstop=4
set shiftwidth=4
set noexpandtab

With these settings, you hit <Tab> and you get <Tab>.

These are good settings if you prefer spaces:

set tabstop=4
set shiftwidth=4
set expandtab

With these settings, you hit <Tab> and you get <Space><Space><Space><Space>.

Whatever you choose, you should not use your terminal key bindings for copying/pasting. Inside Vim, you should "yank" with y and "put" with p or P; optionally using a specific register like "ay/"ap to yank/put to/from the content of @a or "+y/"+p to yank/paste to/from the system clipboard (if your Vim is built with clipboard support).

As a side note, you should use the long form names of your settings as they are more readable than their short counterpart. Your future self will thank you.

9/25/2012 3:35:31 PM

What romainl said. Also, there are a few other settings that I find useful. Here is an excerpt from my .vimrc:

set autoindent " always set autoindenting on"
set smartindent " use smart indent if there is no indent file"
set tabstop=4 " <tab> inserts 4 spaces"
set softtabstop=4 " <BS> over an autoindent deletes 4 spaces."
set smarttab " Handle tabs more intelligently"
set expandtab " Use spaces, not tabs, for autoindent/tab key."
set shiftwidth=4 " an indent level is 4 spaces wide."
set shiftround " rounds indent to a multiple of shiftwidth"

In vim, enter :h <setting> for each of these settings to learn more about what they do,

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow