Vim копировать / вставить испортить отступ

2426
Luke

Всякий раз, когда я копирую что-то из другого приложения и затем вставляю это в vim, это портит отступ.

Например, только что я попытался скопировать файл manifest.json из учебника hello-world для создания расширений chrome.

Это выглядит так:

{ "manifest_version": 2,  "name": "One-click Kittens", "description": "This extension demonstrates a browser action with kittens.", "version": "1.0",  "permissions": [ "https://secure.flickr.com/" ], "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" } } 

но когда я вставляю его в vim, это выглядит так: Vim копировать / вставить испортить отступ

Мой vimrc выглядит следующим образом:

"se t_Co=256 syntax enable  set nowrap set mouse=a set tabstop=4 set softtabstop=4 set shiftwidth=4 set expandtab  set number set showcmd set cursorline set showmatch  execute pathogen#infect() "filetype plugin indent on  "folding settings set foldmethod=indent "fold based on indent set foldnestmax=10 "deepest fold is 10 levels set nofoldenable "dont fold by default set foldlevel=1   set clipboard=unnamed "share one clipboard for everyhting  

Это как-то связано с этой строкой:

execute pathogen#infect() "filetype plugin indent on 

Если я это закомментирую, проблема решена. Тем не менее, это то, что я использую для достижения автоматического отступа, когда я пишу код на python. Есть ли другой способ получить авто-отступ?

5
Как вы вставляете, с помощью средней кнопки мыши? Прочитайте `: help 'paste'` для объяснения и переключите эту опцию до / после вставки или вставьте изнутри Vim (через регистр` + `, например`' + p`. Ingo Karkat 9 лет назад 0
Ого, так что я всегда вставлял, щелкая правой кнопкой мыши и выбирая вставку, но я просто попробовал это с помощью средней кнопки мыши, и это сработало, как и ожидалось. Luke 9 лет назад 0
Ах, отлично! Я расширил свой комментарий в правильный ответ; пожалуйста, подтвердите, нажав на отмеченную галочку рядом с ним. Ingo Karkat 9 лет назад 0

4 ответа на вопрос

6
Ingo Karkat

In the terminal, Vim cannot distinguish between typed text (where you want automatic indenting), and pasted text. So there's the 'paste' option (and 'pastetoggle' to simplify handling), which when set disables auto-formatting and -indenting. An alternative is using graphical GVIM, which can detect that.

Or, you use Vim's clipboard access (if configured and working, which you need to try out), and use the "* / "+ registers for the selection / system clipboard, e.g. via "+p or :put +. Maybe pasting with the middle mouse button also just works; try it out!

5
Dirk

:set paste

or see http://vim.wikia.com/wiki/Toggle_auto-indenting_for_code_paste

(herearesomecharsbecausesuperuser.comthinksshortanswersarenotanygoodanswers)

Это не решило проблему Luke 9 лет назад 0
Это сработало для меня. Вне режима вставки я набрал команду `: set paste`, нажал ввод, затем команду + v (я на Mac), чтобы вставить, и он вставил мой контент, не испортив отступ. : set paste не делает это сам, он просто настраивает, чтобы вы могли это сделать. Вероятно, после этого необходимо `: установить nopaste`, чтобы вернуть обычные функции vim. RustyToms 5 лет назад 0
1
wallyk

One possibility, which may not be an option for you, is to use gvim instead of vim. The latter is able to distinguish pasting from rapid text typing. From vim's help for :paste:

'paste' boolean (default off) global Put Vim in Paste mode. This is useful if you want to cut or copy some text from one window and paste it in Vim. This will avoid unexpected effects. Setting this option is useful when using Vim in a terminal, where Vim cannot distinguish between typed text and pasted text. In the GUI, Vim knows about pasting and will mostly do the right thing without 'paste' being set. The same is true for a terminal where Vim handles the mouse clicks itself. This option is reset when starting the GUI. Thus if you set it in your .vimrc it will work in a terminal, but not in the GUI. Setting 'paste' in the GUI has side effects: e.g., the Paste toolbar button will no longer work in Insert mode, because it uses a mapping. When the 'paste' option is switched on (also when it was already on): - mapping in Insert mode and Command-line mode is disabled - abbreviations are disabled - 'textwidth' is set to 0 - 'wrapmargin' is set to 0 - 'autoindent' is reset - 'smartindent' is reset - 'softtabstop' is set to 0 - 'revins' is reset - 'ruler' is reset - 'showmatch' is reset - 'formatoptions' is used like it is empty These options keep their value, but their effect is disabled: - 'lisp' - 'indentexpr' - 'cindent' NOTE: When you start editing another file while the 'paste' option is on, settings from the modelines or autocommands may change the settings again, causing trouble when pasting text. You might want to set the 'paste' option again. When the 'paste' option is reset the mentioned options are restored to the value before the moment 'paste' was switched from off to on. Resetting 'paste' before ever setting it does not have any effect. Since mapping doesn't work while 'paste' is active, you need to use the 'pastetoggle' option to toggle the 'paste' option with some key. 
0
Andrew

One of the best solutions to this issue that I've encountered is to use the bracketed paste plugin: https://github.com/ConradIrwin/vim-bracketed-paste - this allows you to paste directly into vim without worrying about the indentation going awry .. and without needing to hit different keys prior to pasting etc etc