Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an easy way to copy a word above and paste it at the current cursor position in Vim

Tags:

vim

I wonder if there is a command to straight away copy a character or a word above the cursor and paste it at the current position?

Example:

sig1   : in   std_logic;
sig2   : in   std_logic;
sig3   : ^

Consider the situation above, and my cursor is at the ^ position, I would like to duplicate the in std_logic; and paste it at current position. A way that I know of that can work is:

1. Move cursor up
2. Go into visual mode and highlight
3. Yank
4. Move cursor down
5. Paste

Is there any easier way to do so? Or I'm left with the only option of writing a mapping in vimrc that execute the whole sequence for me?

Edit: I found a mapping on the internet:

imap <F1> @<Esc>kyWjPA<BS>
nmap <F1> @<Esc>kyWjPA<BS>
imap <F2> @<Esc>kvyjPA<BS>
nmap <F2> @<Esc>kvyjPA<BS>

but it seems that Greg's solution is easier!

like image 995
I'm a frog dragon Avatar asked Nov 19 '12 02:11

I'm a frog dragon


People also ask

How do I copy and paste text in Vim?

We can use the “+p and <Ctrl+r>+ in normal and command mode, respectively. However, it might be more convenient if we use the <Ctrl+Shift+v> hotkey since it does the same thing as “+p. Similarly, <Ctrl+Shift+c> will yank the text into the + register to be available for pasting outside of Vim.

How do I paste a line above and below the cursor line in Vim?

The command p pastes below the cursor and P pastes above the cursor.


2 Answers

In insert mode, you can use Ctrl+Y to copy characters from the corresponding character position on the previous line. Just hold down the key and wait for the keyboard repeat to get you to the end of the line.

like image 55
Greg Hewgill Avatar answered Nov 27 '22 20:11

Greg Hewgill


Although Greg's answer is spot on I have modified my ctrl+y to copy word-wise as I find it more helpful in my workflows. I have the following in my ~/.vimrc file:

inoremap <expr> <c-y> pumvisible() ? "\<c-y>" : matchstr(getline(line('.')-1), '\%' . virtcol('.') . 'v\%(\k\+\\|.\)')

Basically this expression mapping copies the a word from the line above by if the insert completion menu (see :h ins-completion-menu) is not visible. Checking for this case allows for accepting of the current completion and leave completion mode (See :h complete_CTRL-Y).

If the insert completion menu is not visible then the following occurs:

  • getline(line('.')-1) returns the previous line
  • virtual('.') the current positions column position
  • '\%' . virtcol('.') . 'v\%(\k\+\\|.\)' match a word from the cursors position or any character
  • matchstr() returns the matching portion of the previous line that matches the pattern.

For more help see:

:h :map-<expr>
:h pumvisible(
:h matchstr(
:h getline(
:h line(
:h virtcol(
:h /\%v
:h /\k
like image 23
Peter Rincker Avatar answered Nov 27 '22 21:11

Peter Rincker