Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open URL under cursor in Vim with browser

Tags:

vim

People also ask

How do I open a URL in Vim?

If you have Vim and Netrw, you can open a URL in your browser of choice, right from the editor. Place the cursor on the URL and type gx . This will invoke your file handler; open for OSX. As a result, it also works with file types such as images, GIFs, and videos.

How do you jump in front of a line in Vim?

Press 0 to go to the beginning of a line, or ^ to go to the first non-blank character in a line.

How open HTML file in Vim?

Visually select the full path of a local html file or a URL, then type \h to preview the file or web page. Copy the full path of a local html file or a URL in another application, then type \h to preview the file or web page in 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


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


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


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>

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