Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

edit:

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"
else
let &t_Co=8
let &t_Sf="\e[3%dm"
let &t_Sb="\e[4%dm"
endif

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

like image 976
Awalias Avatar asked Sep 25 '12 13:09

Awalias


People also ask

How do I paste properly in Vim?

vim Inserting text Disable auto-indent to paste code And if you want to paste as is from the clipboard. Just press F3 in insert mode, and paste. Press F3 again to exit from the paste mode.


2 Answers

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.

like image 178
romainl Avatar answered Sep 20 '22 04:09

romainl


I was middle-click-pasting into a terminal vim instance. I have this in my vimrc:

set tabstop=2           " (ts)
set softtabstop=2       " (sts) Turned off with 0
set shiftwidth=2        " (sw)  Used for autoindent, and << and >>
set expandtab           " (et)  Expand tabs to spaces

I ran

:set paste
:set noexpandtab

and vim preserved the tabs that were in the source text. Without overriding my expandtab setting, vim was auto-expanding the tabs in the source text.

like image 32
djeikyb Avatar answered Sep 24 '22 04:09

djeikyb