I'm a frog dragon
I'm a frog dragon

Reputation: 8805

Looking for an easy way to copy a word above and paste it at the current cursor position in 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!

Upvotes: 8

Views: 1314

Answers (2)

Peter Rincker
Peter Rincker

Reputation: 45087

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

Upvotes: 8

Greg Hewgill
Greg Hewgill

Reputation: 992717

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.

Upvotes: 14

Related Questions