Getting the Host Name of the Current Browser Page

A while ago I wrote about coding some Elisp to grab the URL of the current Web page and turn it into an Org link. It doesn’t seem like it would reduce friction by that much but it really has made linking in my blog posts much more efficient. So much so that now I hate to make links to the site and then to a particular post like

abo abo over (or emacs has a nice video on using Hydra.

because now I have to switch focus to Safari to cut the site name of the blog and then paste it into a link just like I used to do for links to individual posts.

So I looked for some URL parsing functions in Emacs and found url-generic-parse-url that breaks a URL into its constituent parts. I used that to modify jcs-get-link to return a link to just the host name if it’s called with the universal argument:

(defun jcs-get-link (hostp)
  "Retrieve URL from current Safari page and prompt for description.
With the universal argument, return a link to the host only.
Insert an Org link at point."
  (interactive "P")
  (let* ((link (read-from-minibuffer "Link Description: "))
         (result (shell-command-to-string
                  "osascript -e 'tell application \"Safari\" to return URL of document 1'"))
         (urlobj (url-generic-parse-url result))
         (host (concat (url-type urlobj) "://" (url-host urlobj))))
    (insert (format "[[%s][%s]]" (if hostp host (org-trim result)) link))))

It’s a bit of a hack because the host name may not be the same as the site name so the new function may not give the right site link. Ironically, an example of this is Irreal. If you want the address for the blog itself, it’s http://irreal.org/blog not http://irreal.org as the above code returns.

Still, this problem isn’t that common and even handling it as a special case is still less friction that changing focus to the browser.

This entry was posted in Programming and tagged . Bookmark the permalink.