Vim how to copy
Vim how to copy
How to copy selected lines to clipboard in vim
How to copy selected lines to clipboard in vim. I know how to do it for all text files, but I want to do in for selected lines. Thanks!
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
SHIFT V puts you in select lines mode. Then » + y yanks the currently selected lines to the + register which is the clipboard. There are quite a few different registers, for different purposes. See the section on selection and drop registers for details on the differences between * and + registers on Windows and Linux. Note that there is only a distinction between «* and «+ for X11 systems. Under MS-Windows, use of «* and «+ is actually synonymous and refers to the gui-clipboard. So, on windows * (sharp) register can be used as well: » * y
If you’re on Linux and are using a VIm version 7.3.74 or higher (the version that gets installed in Ubuntu 11.10 onwards satisfies this), you can do
which will place yanked text into the global clipboard, and allow you to paste from the global clipboard, without having to use any special registers. Unlike ldigas’s solution, this will also work on non-gui versions of VIm.
For GVIM, hit v to go into visual mode; select text and hit Ctrl+Insert to copy selection into global clipboard.
Install «xclip» if you haven’t.
sudo apt-get install xclip
Xclip puts the data into the «selection/highlighted» clipboard that you middle-click to paste as opposed to «ctrl+v»
While in vim use ex commands:
Then just middle-click to paste into any other application.
If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.
install vim:
install gui verion of vim:
restart the terminal to take effect.
append the following line to
now you can copy the line in vim with yy and paste it system-wide.
First check if your vim installation has clipboard support.
If clipboard support is installed you will see:
If clipboard support is not installed you will see:
To install clipboard support:
Once you have verified that clipboard support is installed do the following:
Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrl c selected text will be copied to system clipboard. And when you press Ctrl p system clipboard text is copied to vim. To create shortcuts :
Position your cursor to the first line you want to copy.
Press Shift v to enter visual mode.
Press ↓ to select multiple lines
Press Ctrl c to copy the selected text to system clipboard.
Now you can copy the selected text to browser, text editor etc.
Press Ctrl p if you want to copy system clipboard text to vim.
How can I copy text to the system clipboard from Vim?
Is there a way to copy a block of text to the system clipboard, so I can paste it in another program?
13 Answers 13
For X11-based systems (ie. Linux and most other UNIX-like systems) there are two clipboards which are independent of each other:
OS X and Windows systems only have one clipboard.
For X11 systems there are also number of tools that synchronize these clipboards for you; so if they appear to be the same, you may have one of them running.
Vim has two special registers corresponding to these clipboards:
You can use these registers as any register. For example, using the PRIMARY clipboard * with the y and p commands:
You could maybe use this as more convenient keybinds:
If you want to «automatically» interface with the system’s clipboard instead of referring to it manually all the time, you can set the clipboard variable:
Now, just using yy will go to the system’s clipboard, instead of Vim’s unnamed register, and p will paste the system’s clipboard.
You can also assign to these registers just like any register with let :
The clipboard setting has some more options (such as exclude filters); but these are the basics. See :help ‘clipboard’ for the full story 😉
You can also use a clipboard on remote machines if you enable X11 forwarding over SSH. This is especially useful with the above tip since you can then use xclip to access your desktop’s clipboard. The Vim on the machine you’re ssh-ing to will still need the +clipboard feature.
This requires the ForwardX11Trusted setting, and should only be done with trusted servers, as this gives the server almost complete control over your X11 session:
Neovim
Copy and paste content from one file to another file in vi
I am working with two files, and I need to copy a few lines from one file and paste into another file. I know how to copy (yy) and paste (p) in the same file. But that doesn’t work for different files. How is this done?
Also, is there a way to cut-paste? I have tried googling, but most of the resources only talk about copy-paste.
19 Answers 19
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Since you already know how to cut/yank text, here are a few ideas for pasting it back into another file:
If you are using Vim on Windows, you can get access to the clipboard (MS copy/paste) using:
The lets you paste between separate Vim windows or between Vim and PC applications (Notepad, Microsoft Word, etc.).
Use the variations of d like dd to cut.
To write a range of lines to another file you can use:
Where and are numbers (or symbols) that designate a range of lines.
For using the desktop clipboard, take a look at the +g commands.
» buffer_name, copies to the buffer. Y is yank and P is put. Hope that helps!
Here’s one way to do it;
As for cutting, d cuts and places the cut stuff in the yank buffer. d d will «cut» a line.
I just found that if you add the following line into your vimrc file,
then Vim is using the system clipboard.
I just found the yank way won’t work on the way where I copy contents between different Vim instance windows. (At least, it doesn’t work based on my Vim knowledge. I don’t know if there is another way to enable it to work).
The yank way only works on the way where multiple files are opened in the same window according to my test.
While editing the file, make marks where you want the start and end to be using
Then, to copy that into another file, just use the w command:
These remaps work like a charm for me:
So, when I’m at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use «*y as well, but I think this is hard to remember sometimes.
This is also useful to copy text from Vim to clipboard.
Goal: save a piece of one file to another file.
Solution:
Save selected text to the new file. Type : w Space and the name of the new file. Actually you’ll see
Then press Enter
Copying text between two buffers (== files) that are opened in the same instance of Vim is no problem:
How to open two files in the same instance of Vim depends on your system:
Cut, Copy, & Paste in Vim
Before we get to any of these, remember that in a graphical Vim client like MacVim all your normal OS cut, copy, and paste commands like вЊx, вЊc, and вЊv (on the Mac) will work just fine when combined with mouse selections. The following commands will make a huge difference in your speed because, they’ll enable you to efficiently rearrange code without ever reaching for the mouse. While you don’t need to start using these immediately I would strongly encourage you to practice with them until they’re comfortable and normal.
Vim’s got some odd verbs for Cut, Copy, and Paste. This is probably because it was written long before those were common terms. Instead of Cut, Copy, and Paste we have Yank ( y ), Delete ( d ), and Put ( p ). These are the most common of Vim’s verb. You combine them with various motion commands to quickly select the text you want to manipulate.
Quick Usage
The simplest, and most common way of interacting with Yank, Delete, and Put is by line. For example: Imagine you have the following function.
You might decide that it’s crap and you want to delete the whole thing. One way is to put your cursor on the first line and tell vim you want to delete that line and the next two. d2 The number is always the number of lines after the current one that you want included. What if you wanted only the current line? dd
If wanted to move it you’d, again, delete it from where it is, move your cursor to where you want it to go, and Put it with p
Yank (Copy) works exactly the same as delete except it leaves the text in place and you use y instead of d
Yeah. Mental math is not my forte. If you’re like me, then read the line numbers post to see a trivial way to switch your sidebar to relative line numbers, and save yourself the headache.
Ready for more? I’m going to cover a bunch of common use cases here, but definitely check out the post on movement, and remember that pretty much anything you can do to move the cursor can be combined with these verbs so… dn Just keep whacking those two keys and it’ll keep deleting up to the next match. No counting required.
Delete (Cut)
Deleting Lines
d is the key to _d_eleting lines. As noted above, you can just whack it twice ( dd ) to affect just the current line. If you want to delete the current line and the 4 after it you type d4
Deleting parts of lines.
Deleting to the end of the line
Deleting arbitrary sections
Let’s say we have our cursor on the “i” in “is” and we want to delete everything up to, but not including, “test”. We can “Delete To ’t’” by typing dtt and the sentence will become “This test sentence.” Deleting up to “sentence” is a little trickier. dts would “Delete To ’s’” and the first “s” is in “is”. So, we’d have to say 3dts because the “s” in sentence is the 3rd “s”.
Counting letters sucks, so don’t do it.
Remember when I said that searching was “…a tool for extending your selection, deleting chunks, and more”? Well, here’s where we use that.
You want to Delete everything up to (but not including) “sentence”, so hit d then start a search for “sentence” ( d/ ) as you type in your search string Vim will highlight it it as you go. When I’ve typed the “s” it’s matching the “s” at the end of “is”…
as soon as I add the “e” it jumps ahead to the first “se” which happens to be exactly what I’m looking for.
Advanced form…
What if you want the next search result? You can’t type n for next because vim will think you want “n” as the next letter of your search term, and you can’t hit on the first match because it’ll delete everything up to that, which isn’t enough.
You’ve got a couple options here. If you literally want the “next” match you can say 2d/ which will delete to the 2nd match of the search term. Of course, now we’re right back to counting things. There’s a simpler way but it’s not quite as efficient.
When you delete with a search that search is now defined as the last thing you searched for (duh), but that means that n will work for finding the next one, and since n is a way to move your cursor, and I said you can combine movement with these verbs.
Deleting characters
x deletes whatever is currently selected. Keep whacking it and it’ll keep deleting whatever’s under the cursor. X deletes the character before the one that’s selected. Neither can be combined with motion commands.
Yank (Copy)
y is the key to copying things. Like Delete you can just whack it twice ( yy ) to affect just the current line. All things that you can do to select multiple lines for Deletion work for Yanking.
Yank to end of line
Like with Deletion you can combine y with the command to move to the end of the line to Yank to the end of the line: y$
Put (Paste)
p will put whatever you have Yanked or Deleted into the doc wherever the cursor is currently located. If you have a line on the vim’s clipboard (not the OS’s clipboard) it will paste it on the line below the cursor. If just you have some characters, they will it will paste after the cursor.
P will paste lines above the current line and charters before the cursor.
Noticing a pattern? Many of Vim’s commands have upper case versions that do something very similar.
Vim, of course, has a way to address this.
run set paste when you’re about to paste from the system clipboard and set nopaste when you’re done. You only have to do this in the terminal. The GUI versions like MacVim can tell when you’re pasting and handle it correctly.
Interacting with the system clipboard.
Beginners should skip this section. Seriously. All you need to know is that your normal system’s cut and copy functionality interacts with the system clipboard as you would expect. Or to put it another way: use вЊc and вЊx and everything will work just fine.
What follows will seem overwhelming to a beginner and “oh, just a quote mark?” to people already comfortable with yank and delete. I don’t want you to feel overwhelmed.
Vim has a series of registers where it stores things you’ve recently yanked or deleted. Your system also has a clipboard (usually just one) where it stores stuff you’ve recently copied or cut. These are not the same “clipboard” but Vim does have access to the system clipboard.
Yanking & Deleting to the system clipboard
But Vim a special register just for interacting with the system clipboard. It’s named * Now, I have to step back a bit and explain that whenever you yank, or delete you’re putting that text into a register. If you want to use this functionality I recommend you see the buffers post for details, but here’s the quick, no-frills version.
Graphical Vim’s and Cut / Copy / Paste
The only gotcha with the graphical clients is that each window should be considered its own world. The OS level cut / copy / paste will transfer things between windows, but the built in commands noted below will only transfer stuff between buffers or tabs within the same window. This is, presumably, because every terminal window is its own little world, and the same functionality carried over to the graphical clients.
Additional Reading
When you’ve recovered from reading far too many words about Cut, Copy, and Paste you should check out the somewhat related Change, Replace, & Substitute. It’s much shorted I promise, and I find “change” to be very useful.
Как копировать, вырезать и вставлять в Vim / Vi
При работе с текстовыми файлами копирование, вырезание и вставка текста — одна из наиболее часто выполняемых задач.
Vim или его предшественник Vi предустановлен на macOS и почти во всех дистрибутивах Linux. Знание основ Vim полезно в ситуации, когда ваш любимый редактор недоступен.
В этой статье показано, как копировать, вырезать и вставлять в редакторе Vim / Vi.
Копирование, вырезание и вставка в нормальном режиме
Когда вы запускаете редактор Vim, вы находитесь в обычном режиме. В этом режиме вы можете запускать команды Vim и перемещаться по файлу.
В Vim есть собственная терминология для копирования, вырезания и вставки. Копирование называется yank ( y ), вырезание называется delete ( d ), а вставка называется put ( p ).
Копирование (Янкинг)
Чтобы скопировать текст, поместите курсор в желаемое место и нажмите клавишу y а затем команду перемещения. Ниже приведены некоторые полезные команды восстановления:
Резка (Удаление)
Команды движения, применяемые для восстановления, также действительны для удаления. Например, dw удаляет до начала следующего слова, а d^ удаляет все от курсора до начала строки.
Склеивание (Вставка)
Чтобы поместить извлеченный или удаленный текст, переместите курсор в желаемое место и нажмите p чтобы вставить (вставить) текст после курсора, или P чтобы поместить (вставить) перед курсором.
Копирование, вырезание и вставка в визуальном режиме
Визуальный режим Vim позволяет выбирать текст и управлять им.
Поместите курсор на линию, с которой вы хотите начать копирование или резку.
Визуальный режим имеет три подтипа.
Переход в визуальный режим также отмечает начальную точку выбора.
Переместите курсор в конец текста, который вы хотите скопировать или вырезать. Вы можете использовать команду перемещения или клавиши со стрелками вверх, вниз, вправо и влево.
Нажмите y чтобы скопировать, или d чтобы вырезать выделение.
Переместите курсор в то место, куда вы хотите вставить содержимое.
Нажмите P чтобы вставить содержимое перед курсором, или p чтобы вставить его после курсора.
Выводы
В этом руководстве мы показали вам, как копировать, вырезать и вставлять в Vim.
Если вы новичок в Vim, посетите сайт Open Vim, где вы можете попрактиковаться в Vim с помощью интерактивного руководства.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.