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

I wonder if there is a command to copy a character or 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 in position ^ , I would like to duplicate in std_logic; and paste it in the current position. The way I know may work:

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

Is there an easier way to do this? Or am I left with the only option of writing a mapping in vimrc that does the whole sequence for me?

Edit: I found a mapping on the web:

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

but it seems that the Greg solution is easier!

+4
source share
2 answers

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

+4
source

Although Greg’s answer is accurate, I modified my ctrl + y to copy the word, as I find it more useful in my workflows. In my ~/.vimrc file, I have the following:

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

Basically this expression matching copies the word from the line above if the insert completion menu is not displayed (see :h ins-completion-menu ). Checking this case allows you to accept the current completion and exit the completion mode (see :h complete_CTRL-Y ).

If the insert completion menu is not displayed, the following occurs:

  • getline(line('.')-1) returns the previous line
  • virtual('.') column position of current positions
  • '\%' . virtcol('.') . 'v\%(\k\+\\|.\)' '\%' . virtcol('.') . 'v\%(\k\+\\|.\)' matches a word from the cursor position or any character
  • matchstr() returns the corresponding part 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 
+4
source

Source: https://habr.com/ru/post/1446850/


All Articles