@alvaro
sign in · lmno.lol

Get Emacs to gather links in posts

Comments in posts can be a great source of recommendations. Here's a way to extract post links using Emacs and enlive.

(require 'enlive) ;; https://github.com/zweifisch/enlive
(require 'org)

(defun ar/input-clipboard-url-or-prompt ()
  "Return a URL from clipboard or prompt user for one."
  (let* ((clipboard (current-kill 0))
         (url (if (string-match "^https?://" clipboard)
                  clipboard
                (read-string "URL: "))))
    (unless (string-match "^https?://" url)
      (error "Not a URL"))
    url))

(defun ar/url-fetch-anchor-elements (url)
  "Fetch anchor elements in URL as list of alist:
\((title . \"my title\")
 (url . \"http://some.location.com\"))."
  (let ((elements (enlive-query-all (enlive-fetch url) [a])))
    (mapcar (lambda (element)
              `((title . ,(enlive-text element))
                (url . ,(enlive-attr element 'href))))
            elements)))

(defun ar/url-view-links-at ()
  "View external links in HTML from prompted URL or clipboard."
  (interactive)
  (with-current-buffer (get-buffer-create "*links*")
    (org-mode)
    (view-mode -1)
    (erase-buffer)
    (mapc (lambda (anchor)
            (let-alist anchor
              (when (and .url (string-match "^http" .url))
                (insert (org-make-link-string .url
                                              .title) "\n"))))
          (ar/url-fetch-anchor-elements
           (ar/input-clipboard-url-or-prompt)))
    (delete-duplicate-lines (point-min) (point-max))
    (goto-char (point-min))
    (toggle-truncate-lines +1)
    (view-mode +1)
(switch-to-buffer (current-buffer))))

UPDATE(2019-04-13): Refreshed post with latest code from my init. Thanks to Gijs for pinging.