Open url in Emacs with external browser

  |   Source

Here is some handy elisp function which use browse-url-generic to open the url in external browser (firefox, for example).

The key point is how to detect the url. If we are in w3m-mode, we will use the link under cursor or the URI of current web page. Or else, we will let browse-url-generic to detect the url.

(defun w3mext-open-link-or-image-or-url ()
  "Opens the current link or image or current page's uri or any url-like text under cursor in firefox."
  (interactive)
  (let (url)
    (if (string= major-mode "w3m-mode")
        (setq url (or (w3m-anchor) (w3m-image) w3m-current-url)))
    (browse-url-generic (if url url (car (browse-url-interactive-arg "URL: "))))
    ))
(global-set-key (kbd "C-c b") 'w3mext-open-link-or-image-or-url)

To specify the external browser like firefox, add below code into ~/.emacs:

;; `C-h v browse-url-generic-program RET` to see the documentation

;; *is-a-mac* and *linux* is the boolean constants defined by me

(setq browse-url-generic-program
      (cond
       (*is-a-mac* "open")
       (*linux* (executable-find "firefox"))
       ))
Comments powered by Disqus