2

In Vim, I can use gx in normal mode to open the URL under the cursor. Instead of opening the URL, how can I copy the URL?

I am looking for something faster than entering into visual mode, selecting the URL, and yanking the selected URL.

0
2

You should be able to use the same mechanism that can capture file paths, <cfile>:

<cfile>    is replaced with the path name under the cursor (like what |gf| uses)

This special keyword can be resolved to its associated value on the command line using the function expand(). For example, to put the URL in a register:

:let @0 = expand('<cfile>')

If you want to put the URL in the clipboard use "* or "+ register (depending on your system and its configuration).

Add it to a mapping...

:nnoremap <leader>u :let @* = expand('<cfile>')<CR>

...and with a couple key presses you can now paste the URL wherever you need it.


Update: A couple Q&As excerpted from the comments that may be useful to others...

Q: When I press p in normal mode to paste the URL, why is nothing pasted?

A: The type of environment (OS, window manager, GUI vs terminal) you're in usually dictates which register is tied to the system clipboard. If paste/put is working for you otherwise look at the register being used there and use the same in the mapping. If you're using *nix the "quote-plus" register (@+) may be what you need. (ed- It was.) For more details on clipboard use :h 'clipboard' is a good place in Vim help to start.

Q: How can I prevent the mapped command from appearing in the status bar? :nnoremap <leader>u :silent let@* ... doesn't work.

A: Instead of using :silent add <silent> after nnoremap.

:nnoremap <silent> <leader>u :let @* = expand('<cfile>')<CR>

<silent> is simply used to prevent a mapped command from being displayed when the mapped keys are entered. If the mapped command also has output that you don't want to see you'll need :silent in addition to <silent>.

3
  • Is there a way to make this silent? I tried nnoremap <leader>u :silent let @* = expand('<cfile>')<CR> in my vimrc, but it doesn't seem to make the keybinding silent. – Flux Oct 19 '20 at 12:17
  • I tried your solution, but when I press p in normal mode to paste the URL, nothing is pasted. – Flux Oct 19 '20 at 12:20
  • Okay. Thank you. It works now. I was actually looking for one solution for pasting into Vim and another for pasting outside it. I should have mentioned that in my question. Anyway, nnoremap <silent> <leader>u :let @+ = expand('<cfile>')<CR> works perfectly for pasting outside Vim. For pasting inside Vim, I replaced the @+ with @". I am using terminal Vim on Ubuntu. – Flux Oct 20 '20 at 7:46

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.