I'm trying to answer a question in U&L, which involves a very complex and long regex substitution.

I would like to copy to clipboard the command, or save it in a file, so I don't have to make a transcription, prone to errors.


:s/foo/bar/ ← command to copy

Is this possible?

  • Welcome to Vi and Vim!
    – D. Ben Knoble
    Mar 9 at 16:51
  • @D.BenKnoble Thanks! This is my second question though :) Mar 9 at 16:52
  • Hm, doesn't look like it on your profile (not counting deleted questions…), so that could be why it showed up in Review. No worries, keep asking questions! (and maybe answering them!)
    – D. Ben Knoble
    Mar 9 at 16:55
  • @D.BenKnoble The question was off- topic :| maybe that's the reason it doesn't show up. Mar 9 at 16:58

To past the content of a register you can prefix your p command with "[register_name], that's what ["x] mean in ["x]p in :h p:

["x]p       Put the text [from register x] after the cursor
            [count] times.

You command is stored in the : register: If you want to put it in a buffer you can do ":p, and after that you can handle it like any text in any register.

  • 2
    What I usually do is after testing a vim command, copying it to the clipboard in order to paste it into stackexchange. So after running the vim ex command, storing it in the clipboard using :let @+=@: Mar 9 at 16:05
  • Good way to do it indeed. Personnaly I prefer to confirm what I'm doing by pasting in a scratch buffer but your version is more efficient.
    – statox
    Mar 9 at 16:17

If the command you wanted to copy wasn't the last one, it can be helpful to open the command-line window with q: or :<C-f>. Then you can do, e.g., "*yy or :yank + or however you prefer.

(Personally, I use my pbcopy plugin to yank to the clipboard with <C-y>; mapping is configurable, though it does always use the * register.)

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.