Recently I have been documenting a lot of code which are usually in markdown files (.md). And I frequently come across texts where I have to retype previously written word. Like,

cp file_1 file_2
mv -v file1 file2
git clone --bare repo_name repo_name.git
etc ...

Currently, I have been using the following sequence to achieve copying and pasting the previous word without using mouse:

some_word Esc+v+b+y+A+Esc+p+A rest of the sentence.

BUT this seems rather having to press more keys strokes than the word itself (< 8 strokes), and doesn't seems like a wise thing to do.

So the question,

  1. Is there a better way to achieving this using default VIM sequences. Kindly do not suggest key mapping unless there is no other alternative.
  2. Can I copy-paste text without leaving the vim insert mode?
  • 2
    so by previous word you mean the one immediately before the cursor? have you tried ctrl+p? – Mass May 2 '18 at 17:00
  • @Mass yes! And excellent answer. That's exactly I was looking for. Kindly post it in the answer with some cool info on this functionality. – Avi Mehenwal May 2 '18 at 17:04

One of the easiest ways to insert words from the buffer is using keyword completion. This is done using the keys CTRL+n and CTRL+p, or CTRL+x CTRL+n and CTRL+x CTRL+p in insert mode. The exact behavior depends on the options completeopt and complete, so I will assume you have set the defaults.

The difference between these is

  1. CTRL+p targets words before the cursor ("previous") and CTRL+n targets words after the cursor ("next") and

  2. using CTRL+x first targets the current buffer only but without CTRL+x it targets all buffers. This behavior can be changed using complete (see :help 'complete').

Thus, by default, to insert the word before the cursor you merely need to type CTRL+p or CTRL+x CTRL+p once. The latter may be slightly faster if you have many buffers open.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.