Open URL under cursor in Vim with browser

Vim

Vim Problem Overview


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?

Vim Solutions


Solution 1 - Vim

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

Solution 2 - Vim

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 demo operate

Solution 3 - Vim

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:
  1. Mac has :!open
  2. Linux has :!xdg-open
  3. 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.

Solution 4 - Vim

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.

Solution 5 - Vim

Add following line to .vimrc file:

nmap <leader><space> yiW:!xdg-open <c-r>" &<cr>

So in normal mode it pressing <space> 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).

Solution 6 - Vim

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>

Solution 7 - Vim

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>¬

Solution 8 - Vim

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.

Solution 9 - Vim

I'm pretty late to this party, but here's another way of doing this that works especially well on Windows 7.

  1. 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.)

  2. 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.

Solution 10 - Vim

You should take a quick look to this vim plugin

henrik/vim-open-url

It's basically what has been explained in some other responses, but specific configuration needed if you use a plugin manager :)

Solution 11 - Vim

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

Solution 12 - Vim

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

Solution 13 - Vim

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"

Solution 14 - Vim

For MacOS user:

nmap <silent> gx :!open <cWORD><cr>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMauro MoralesView Question on Stackoverflow
Solution 1 - VimtungdView Answer on Stackoverflow
Solution 2 - VimjsvisaView Answer on Stackoverflow
Solution 3 - VimchrizView Answer on Stackoverflow
Solution 4 - VimkevView Answer on Stackoverflow
Solution 5 - VimValdisView Answer on Stackoverflow
Solution 6 - VimMauro MoralesView Answer on Stackoverflow
Solution 7 - VimpappixView Answer on Stackoverflow
Solution 8 - VimFelipeCView Answer on Stackoverflow
Solution 9 - VimRustavoreView Answer on Stackoverflow
Solution 10 - VimMoOxView Answer on Stackoverflow
Solution 11 - VimVictoria StuartView Answer on Stackoverflow
Solution 12 - VimlaloView Answer on Stackoverflow
Solution 13 - VimDr NeoView Answer on Stackoverflow
Solution 14 - VimPegasusView Answer on Stackoverflow