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.
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityIn 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.
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>
.
nnoremap <leader>u :silent let @* = expand('<cfile>')<CR>
in my vimrc, but it doesn't seem to make the keybinding silent.
p
in normal mode to paste the URL, nothing is pasted.
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.