How to paste in vim

How to paste in vim

Как копировать, вырезать и вставлять в Vim / Vi

How to Copy, Cut and Paste in Vim / Vi

В этой статье показано, как копировать, вырезать и вставлять в редакторе Vim / Vi.

При работе с текстовыми файлами копирование, вырезание и вставка текста является одной из наиболее часто выполняемых задач.

Vim или его предшественник Vi предустановлен на MacOS и почти во всех дистрибутивах Linux. Знание основ Vim полезно в ситуации, когда ваш любимый редактор недоступен.

Копировать, вырезать и вставить в обычном режиме

Когда вы запускаете редактор Vim, вы находитесь в обычном режиме. В этом режиме вы можете запускать команды Vim и перемещаться по файлу.

Чтобы вернуться в обычный режим из любого другого режима, просто нажмите Esc клавишу.

Копирование (Yanking)

Чтобы скопировать текст, поместите курсор в нужное место и нажмите y клавишу, а затем команду перемещения. Ниже приведены некоторые полезные команды для восстановления:

Вырезка (удаление)

В обычном режиме d это клавиша для вырезания (удаления) текста. Переместите курсор в нужное положение и нажмите d клавишу, а затем команду перемещения. Вот некоторые полезные команды удаления:

Вставка (Putting)

Чтобы поместить выдернутый или удаленный текст, переместите курсор в нужное место и нажмите, p чтобы поместить (вставить) текст после курсора или P поместить (вставить) перед курсором.

Копирование, вырезание и вставка в визуальном режиме

Визуальный режим Vim позволяет выбирать текст и управлять им.

Поместите курсор на линию, которую хотите начать копировать или резать.

Визуальный режим имеет три подтипа.

Вход в визуальный режим также отмечает начальную точку выбора.

Переместите курсор в конец текста, который вы хотите скопировать или вырезать. Вы можете использовать команду перемещения или клавиши со стрелками вверх, вниз, вправо и влево.

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

Нажмите, y чтобы скопировать или, d чтобы вырезать выделение.

Переместите курсор в то место, куда вы хотите вставить содержимое.

Нажмите, P чтобы вставить содержимое перед курсором или p вставить его после курсора.

Вывод

В этом руководстве мы показали, как копировать, вырезать и вставлять в Vim.

Если вы новичок в Vim, посетите сайт Open Vim, где вы можете попрактиковаться в Vim с помощью интерактивного учебного пособия.

How to Cut, Copy and Paste in Vim / Vi

Home » SysAdmin » How to Cut, Copy and Paste in Vim / Vi

Vim is a commonly used open-source text editor installed by default on most Unix distributions. You can use the text editor in two modes, from a command-line interface or as an independent application in a GUI.

While working in Vim, copying, cutting and pasting text are frequently used shortcuts.

In this tutorial learn how to copy, cut and paste in Vi / Vim editor.

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

Note: If you don’t have Vim on your system, you may want to check out our guides on How to Install Vim on Ubuntu or How to Install Vim on CentOS 7.

Copy, Cut and Paste in Normal Mode

Before you start, make sure you are in normal mode (text editing/command mode). The best way to do so is to press Esc. This mode allows you to move through the text easily.

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

Copying in Vim

Copying text in Vim is also referred to as yanking. Use the y key on the keyboard when performing this operation.

There are a number of yank commands, mainly differing on the amount of text you want to copy.

Once in normal mode, move the cursor to the needed place and use the appropriate command.

The command stands for “yank till x”. Replace x with the character to which you want to copy to. The character x will not be included.

This instructs Vim to “find x”.

Cutting in Vim

Cutting text is referred to as deleting in Vim. Use the d key when performing this operation.

If you are using Vim in normal mode, you can easily cut or delete text using the d command. Here are some ways you can cut content:

Pasting in Vim

Once you have selected text in Vim, no matter whether it is using the yank or the delete command, you can paste it in the wanted location.

In Vim terminology, pasting is called putting and the function is utilized with the p command.

You can paste (or put) text by moving the cursor to the wanted position and pressing:

Using this command pastes the selected text after the cursor.

To add text before the cursor, type the capitalized command instead:

Note: Refer to our tutorial on how to show lines in Vim to learn how to display absolute, relative and hybrid line numbers.

Copy, Cut and Paste in Visual Mode

Alternatively, you can copy and edit text using the visual selection feature. This mode allows you to select text by navigating around.

Use Esc to exit out of the previously used mode and enable visual selection by pressing:

After you have selected the wanted text you can press:

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

Once you have edited in Vim, make sure to save the file before you exit.

Now you know how to copy, cut and paste in Vim. You may often find yourself needing to make configuration changes to your packages. Most of these can quickly be done in Vim using cut & copy paste.

Next, you can explore the many options VIM to offer, such as Vim color schemes.

Copy, cut and paste

created August 13, 2002 · complexity intermediate · version 6.0

Here is how to cut-and-paste or copy-and-paste text using a visual selection in Vim. See Cut/copy and paste using visual selection for the main article.

Copy and paste is performed with the same steps except for step 4 where you would press y instead of d :

Contents

Copying and cutting in normal mode [ ]

In normal mode, one can copy (yank) with y , where is a Vim motion. For example, yw copies to the beginning of the next word. Other helpful yanking commands include:

Cutting can be done using d , including:

To copy into a register, one can use » immediately before one of the above commands to copy into the register . See pasting registers for more information on register syntax.

Pasting in normal mode [ ]

In normal mode, one can use p to paste after the cursor, or P to paste before the cursor.

The variants gp and gP move the cursor after the pasted text, instead of leaving the cursor stationary.

To select a register from which to paste, one can use «p to paste from the register . See pasting registers.

Pasting in insert mode [ ]

The contents of a register can be pasted while in insert mode: type Ctrl-r then a character that identifies the register. For example, Ctrl-r then » pastes from the default register, and Ctrl-r then 0 pastes from register zero which holds the text that was most recently yanked (copied). See pasting registers.

Copying and cutting in command-line mode [ ]

Command-line mode occurs after typing : to enter a command. By default, while in the command line, typing Ctrl-f opens the command-line window where commands can be edited using normal mode. For example, part of one command can be copied then pasted into another command. See using command-line history.

Pasting in command-line mode [ ]

There are two approaches to pasting in command-line mode. The first is to open the command-line window with Ctrl-f, then use normal-mode commands to paste. See the previous section.

The second approach is to type Ctrl-r then a character to paste the contents of the register identified by the character. See Pasting in insert mode above.

Copy, cut, and paste from the system clipboard [ ]

If your installation of Vim was not compiled with clipboard support, you must either install a package that has clipboard support, or use an external command such as xclip as an intermediary. See Accessing the system clipboard for detailed information.

Multiple copying [ ]

Deleted or copied text is placed in the unnamed register. If wanted, a register can be specified so the text is also copied to the named register. A register is a location in Vim’s memory identified with a single letter. A double quote character is used to specify that the next letter typed is the name of a register.

For example, you could select the text hello then type «ay to copy «hello» to the a register. Then you could select the text world and type «by to copy «world» to the b register. After moving the cursor to another location, the text could be pasted: type «ap to paste «hello» or «bp to paste «world». These commands paste the text after the cursor. Alternatively, type «aP or «bP to paste before the cursor.

Windows clipboard [ ]

When using Vim under Windows, the clipboard can be accessed with the following:

Different instances [ ]

How does one copy and paste between two instances of Vim on different Linux consoles?

After copying text, open a new buffer for a new file:

Increasing the buffer size [ ]

By default, only the first 50 lines in a register are saved, and a register is not saved if it contains more than 10 kilobytes. :help ‘viminfo’

In the example below, the first line displays the current settings, while the second line sets:

How to paste yanked text into the Vim command line

I’d like to paste yanked text into Vim’s command line. Is it possible?

11 Answers 11

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

Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.

Registers are basically storage locations for strings. Vim has many registers that work in different ways:

See :help registers for the full reference.

But you can also do the following (and I probably forgot many uses for registers).

Do not confuse » used here (which is a register name) with the » from the previous example, which was a Normal-mode command.

cf. :help :@ and :help quote_quote

Don’t confuse :@ (command that plays Vim commands from a register) and @ (normal-mode command that plays normal-mode commands from a register).

Define a search pattern manually: :let @/ = ‘foo’

Note that doing that, you needn’t to escape / in the pattern. However you need to double all single quotes of course.

Using a capital register name makes the register work in append mode

cf. :help strftime()

Once again, what can be confusing:

:@ is a command-line command that interprets the contents of a register as vimscript and sources it

@ in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use : register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).

» in normal mode command that helps you select a register for yank, paste, delete, correct, etc.

» is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register names

How to copy paste contents in the vi editor

I tried using Ctrl + V for pasting contents in a vi editor document, but Ctrl + V is not interpreted as a paste.

13 Answers 13

You can also type :set paste in vim before you paste to disable automated indenting, etc. Then :set nopaste after you’ve pasted the content.

Also check this question on stackoverflow.com for more information.

If you want to copy/paste lines in vim (as opposed to pasting clipboard content), you’ll want to check out the yank command. Here is a cheat sheet that might help.

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

Vi (and Vim) works very differently compared to a normal text editor such as Gedit. It also has a pretty steep learning curve. If you want to learn some basic commands, start with this interactive tutorial.

However, to answer you question. The system clipboard’s content can be accessed through the plus register. So to paste something from the system clipboard you can, from the Normal mode, press: «+p (Not at the same time, but one after another).

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

I always use Shift + Insert when I want to paste text into the terminal, works in all terminal programs.

(Which is also the reason why I never get a laptop where you can’t press Insert without pressing a secondary key)

How to paste in vim. Смотреть фото How to paste in vim. Смотреть картинку How to paste in vim. Картинка про How to paste in vim. Фото How to paste in vim

If you want to copy paste contents across terminals, open the first file, yanking the text you want, then open your second file within vim (e.g. :tabnew /path/to/second/file ) and press p to paste it.

If you want to copy paste contents from vim to an external program, you need to access the system clipboard. I assume you use Ubuntu. The GUI version of vim always has clipboard support, however, if you like to use Vim from a terminal, you will have to check for X11-clipboard support.

From the console, type:

If you find -xterm_clipboard, you have two options:

1) Compile vim yourself, with the xterm_clipboard flag on

2) Uninstall vim, install gvim (vim-gtk or vim-gnome) instead. You can stick to non-gui vim by calling vim from the terminal, the same way you did before. This time when you check you should find +xterm_clipborad.

These are 4 basic copy & paste conditions related to vim. I hope this helps.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *