I'm using Twitvim for the first time. Seeing all the URLs in there made me wonder, is there any way to open the URL under the cursor in your favorite browser or a specified one?
16 Answers
Updated: from tpope's tweet today
Press gx
. You can customize the browser. On Gnome and Mac OS X it's already use gnome-open
/open
. Generally you can set g:netrw_browsex_viewer
to anything you want.
Original answer:
Don't remember where I get this function. There is a bug with hash (#) in the url, but the function works well enough that I won't bother fixing it.
function! HandleURL()
let s:uri = matchstr(getline("."), '[a-z]*:\/\/[^ >,;]*')
echo s:uri
if s:uri != ""
silent exec "!open '".s:uri."'"
else
echo "No URI found in line."
endif
endfunction
map <leader>u :call HandleURL()<cr>
Note: If you are not on the Mac, use gnome-open
/xdg-open
for Linux, or 'path to your web browser' for Windows
-
I think I'll use your solution :) thanks ... I do would like to see if there is a way to get only the url under the cursor, but don't know much vimscript so I'll have to work on that. Feb 27, 2012 at 23:18
-
22
gx
is so powerful, thanks! It also opens files with appropriate applications™.– blinryJan 23, 2013 at 14:26 -
2I like to open a url with a ? and a # in it. I think netrw is using cfile instead of cWORD now, so urls with '?' are not longer openable using that method. I tried your solution here and '#' in the url would be replaced by the alternate file name. exec "!open ".shellescape(uri, 1) seems to have fixed the problem. Jun 25, 2014 at 21:15
-
5The aforementioned tweet is here: twitter.com/tpope/status/289234166770434048, just in case anyone is interested in the discussion. Nov 15, 2016 at 10:40
-
1I added a sort of improved version of this script here: stackoverflow.com/a/53817071/7631731 This improvements correctly handles URLs containing "#" and also keeps the vim context active.– pappixDec 17, 2018 at 15:28
If you are using Vim 7.4 or later, in normal mode, put your cursor below the URL, then click gx
, the URL will be opened in browser automatic
-
how are you setting the browser to be Chrome in this example? (or whatever browser that is)– jm3May 11, 2016 at 22:06
-
1@jm3 Try
:h netrw_gx
: * for Windows 32 or 64, the url and FileProtocolHandler dlls are used. * for Gnome (with gnome-open): gnome-open is used. * for KDE (with kfmclient) : kfmclient is used * for Mac OS X : open is used. * otherwise the netrwFileHandler plugin is used.– kbaMay 27, 2016 at 22:06 -
1off topic a little, but how do you record the screen into a gif? love it! Oct 24, 2016 at 15:47
-
-
4@PeterPerháč I'm using github.com/keycastr/keycastr to record Keyboard input, cockos.com/licecap to record screen as gif– jsvisaFeb 16, 2017 at 1:29
Solution for people that unloaded netrw
This is a solution for people who removed netrw
(:help netrw-noload
) in vim/neovim. For example, they use a different file-manager like vim-dirvish
TLDR:
👉 :!open <c-r><c-a>
or map gx
:
👉 nmap gx :!open <c-r><c-a>
So just a bit of background:
I was searching for a solution to this problem too since I actually removed netrw from being loaded in vim completely and replace it with vim-dirvish
. This plugin has around 500~ LOC, compared to netrw
's (11,000+ LOC).
I don't use remote editing much so vim-dirvish
is powerful enough to manage my workflow (It's actually faster than netrw
~ the author claims 2x, I feel it's faster than that - it's really instantaneous ⚡) very useful on large codebase/repositories. I even tried it in a 10K file repo, listing files via -
still instant! Someone tested vim-dirvish
against Nerdtree
, you can see the difference.
I dropped vim-vinegar
too because vim-dirvish have the -
binding anyway, and most of the configuration of vim-vinegar
is netrw
specifics. It's just doesn't need it. Two birds in one stone!
The beauty of this plugin is it embraces the philosophy of VINE (Vim is not Emacs). Where it leverages the power of other programs in the terminal to do file manipulations, instead of trying to do everything by itself. The important part is how natural these external programs interact with vim. And that is achieve by :Shdo
, and it has a convenient key of .
(dot command, which is mnemonic for the repeat command), do that on both selection or the actual line on a vim-dirvish
buffer. And type !rm
for remove, !mv
for rename.
Since I disable netrw, (:help netrw-noload
) I found myself reaching gx
for time to time. I didn't want to load a plugin to get the gx
functionality back.
Now for the solution, there's a binding in command mode, ctrl-r then ctrl-a (:help c_CTRL-R_CTRL-A
), to paste whatever you have in your cursor to the command line, so if you combine that with :!xdg-open
/ :!open
(for mac), you pretty much set.
There's a reason why :w
doesn't have normal bindings. I'm surprised most solution doesn't leverage command workflow, I use ex-command a lot, :s
, :g
, :v
, :argdo
, :cdo
, and friends. Combining this with different modes, taps the full power of vim. So don't just stay in one mode, try to leverage the full power of vim.
So the full workflow. While you have your cursor on top of the url, is just a single step: 😊
👉 :!open <c-r><c-a>
Notice the !
which indicates leveraging the power of external programs outside of vim. VINE!
If you want the gx
functionality back, you can just map using the same command:
nmap gx :!open <c-r><c-a>
I like to silent my bindings, so adding <silent>
and :sil
will do the trick (:help :map-silent
)
👉 nmap <silent>gx :sil !open <c-r><c-a><cr>
Note on platform-specific programs to open a url:
- Mac has
:!open
- Linux has
:!xdg-open
- Windows (WSL2) has
:!wslview
I use all three platforms and they work great. You can just use one of them for your vim bindings, eg. :!open
and just alias in your bashrc/zshrc/fish config
the open
command to whatever platform-specific program you have.
eg. alias open = wslview
That way, my vimrc
stays platform-agnostic, and I'll just deal with the inconsistencies via bashrc/zshrc/fish config
.
-
-
1Any idea how to support makrdown links? The
<c-r><c-a>
approach breaks for links like[Example page](https://example.com)
. Jan 27 at 8:53 -
just curious. when you removed netrw. did you feel any improvment in speed? and did it impact any other plugins (i.e. fzf etc.. which might use netrw)? Feb 11 at 18:53
-
-
@UltraMaster if you are using Windows Terminal you can open external links by ctrl + clicking the link.– chrizFeb 26 at 11:15
I use this script to search gooogle for keyword
under cursor:
nmap <leader>g :call Google()<CR>
fun! Google()
let keyword = expand("<cword>")
let url = "http://www.google.com/search?q=" . keyword
let path = "C:/Program Files/Mozilla Firefox/"
exec 'silent !"' . path . 'firefox.exe" ' . url
endfun
You should use getline('.')
and matchstr()
to extract url under cursor. The rest is the same.
-
I think this will point me to the solution I'm looking for eventually ... plus this function will become very handy. Thanks! Feb 27, 2012 at 23:20
-
Thanks for awesome sharing. I'll use it to make a translation in google translate. Oct 30, 2020 at 1:56
Add following line to .vimrc file:
nmap <leader><space> yiW:!xdg-open <c-r>" &<cr>
So in normal mode it pressing \ it selects current word and open it as address in web browser.
Leader by default is \ (but I've mapped it to , with let mapleader = ","
). Similarly, using imap you can map some key sequence in insert mode (but then, if it is 2 key sequence, it probably will override some default behaviour).
Ok so using the answers from @tungd and @kev and a little research I ended up with this script, which works just the way I need to. Like @tungd said the # can give a problem if inside a url but I'm cool with that, if anyone has a better expression for the url then it will be welcomed.
function! OpenUrlUnderCursor()
let path="/Applications/Safari.app"
execute "normal BvEy"
let url=matchstr(@0, '[a-z]*:\/\/[^ >,;]*')
if url != ""
silent exec "!open -a ".path." '".url."'" | redraw!
echo "opened ".url
else
echo "No URL under cursor."
endif
endfunction
nmap <leader>o :call OpenUrlUnderCursor()<CR>
This is a sort of improved version of the script originally proposed by @tungd here https://stackoverflow.com/a/9459366/7631731. Keeps vim context and handles correctly URLS containing "#".
function! HandleURL()
let s:uri = matchstr(getline("."), '[a-z]*:\/\/[^ >,;()]*')
let s:uri = shellescape(s:uri, 1)
echom s:uri
if s:uri != ""
silent exec "!open '".s:uri."'"
:redraw!
else
echo "No URI found in line."
endif
endfunction
nnoremap <leader>w :call HandleURL()<CR>¬
I removed all the code that wasn't necessary from netrw and ended up with only one line of code:
nnoremap <silent> gx :execute 'silent! !xdg-open ' . shellescape(expand('<cWORD>'), 1)<cr>
This achieves the same as netrw, only better. Replace xdg-open
with open
in macOS, and start
in Windows.
I'm pretty late to this party, but here's another way of doing this that works especially well on Windows 7.
Install both vim-shell and vim-misc in vim I recommend doing this via ever-awesome Pathogen plugin and then simply
cd ~/vimfiles/bundle & git clone [email protected]:xolox/vim-misc.git & git clone [email protected]:xolox/vim-shell.git
from msysgit. (These two plugins open urls in your default browser without creating any extra command prompts or other silly nonsense usually required in windows. You can open urls in Vim like this::Open http://duckduckgo.com
. Try it. You'll like it.)Create some vim mappings so that you can quickly get the line under the cursor into the browser. I'd map this to u (for me, that's
,u
from normal mode). Here's how:nnoremap u :exec "Open ".getline(".")
To use this mapping, type your Leader key from normal mode + u. It should read the line under your cursor and open it in your default browser.
You should take a quick look to this vim plugin
It's basically what has been explained in some other responses, but specific configuration needed if you use a plugin manager :)
As described above by @kev, modified for Linux environments.
Aside: when this function was executed (Vim 8.1) in my terminal, the Vim screen was obfuscated (mostly "blanked;" i.e., the text was there but not visible). The :redraw!
command (see https://stackoverflow.com/a/1117742/1904943) redraws the screen.
Add to ~/.vimrc
:
nmap <leader>g :call Google()<CR>:redraw!<CR>
fun! Google()
let keyword = expand("<cword>")
let url = "http://www.google.com/search?q=" . keyword
let path = "/usr/bin/"
exec 'silent !"' . path . 'firefox" ' . url
endfun
This is simple, just replace "start" with whatever your OS uses
GU for go url!
" Open url
if (has('win32') || has('win64'))
nmap gu :exec "!start <cWORD>"<cr>
else
nmap gu :exec "!open <cWORD>"<cr>
endif
macOS searching google for keyword.
I slightly changed @kev solution to implement the same on Mac,
nmap <leader>gw :call Google()<CR>
fun! Google()
let keyword = expand("<cword>")
let url = "http://www.google.com/search?q=" . keyword
let path="/Applications/Firefox.app"
"exec 'silent ! path url'
silent exec "!open -a ".path." '".url."'" | redraw!
endfun
if you are using Lua.init, wrap the function using
local cmd = vim.cmd
cmd [[
nmap <leader>gw :call Google()<CR>
fun! Google()
let keyword = expand("<cword>")
let url = "http://www.google.com/search?q=" . keyword
let path="/Applications/Firefox.app"
"exec 'silent ! path url'
silent exec "!open -a ".path." '".url."'" | redraw!
endfun
]]
Note
To use Safari
instead use
let path="/Applications/Safari.app"
There are good ideas about starting a search from vim, here is a command implementation :
""" Browser
command! -bar -nargs=1 S call Google(<q-args>)
function! Google(search) range
let url = "http://www.google.com/search?q=" . a:search
exec '!firefox-developer-edition "' . url . '"'
endfunction
Usage :
:S film tom medina
Here's a netrw-independent solution for neovim implemented in lua that uses <cfile>
instead of <C-r><C-a
so that it works for URLs surrounded by non-whitespace characters. All this is done asynchronously using jobstart
so nvim isn't blocked while the external process tries to open <cfile>
. If the invoked program, for whatever reason, still runs after 5 seconds, it is killed using jobstop
.
On windows it effectively uses cmd /c start <cfile>
so it opens all kinds of files/URLS with the system-associated app. However, if no associated default-app is found, or the file doesn't exist, Windows tries to show a modal dialog, waiting for user input indefinitely. This dialog is hidden so the process would just linger in the background forever for no reason. This was the main reason for using jobstop
.
local function open_external(file)
local sysname = vim.loop.os_uname().sysname:lower()
local jobcmd
if sysname:match("windows") then
jobcmd = ("start %s"):format(file)
else
-- Note sure if this is correct. I just copied it from the other answers.
jobcmd = { "open", file }
end
local job = vim.fn.jobstart(jobcmd, {
-- Don't kill the started process when nvim exits.
detach = true,
-- Make relative paths relative to the current file.
cwd = vim.fn.expand("%:p:h"),
})
-- Kill the job after 5 seconds.
local delay = 5000
vim.defer_fn(function()
vim.fn.jobstop(job)
end, delay)
end
vim.keymap.set("n", "gx", function()
open_external(vim.fn.expand("<cfile>"))
end)
gx
appears utterly broken in vim 8.2 due to a bug: vi.stackexchange.com/questions/22459/…