Skip to content

Instantly share code, notes, and snippets.

@adamnew123456
Created July 2, 2018 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamnew123456/49679b097f5dc0d7aef088831544085c to your computer and use it in GitHub Desktop.
Save adamnew123456/49679b097f5dc0d7aef088831544085c to your computer and use it in GitHub Desktop.
Elisp Scripts
(require 'browse-url)
(require 'helm)
(require 'seq)
(require 'url)
(defun xml-node (node)
"Returns the symbol for the node type (e.g. 'li for <li>...</li>)"
(car node))
(defun xml-attr (node attr)
"Returns the attributes of an XML node as an alist"
(cdr (assoc attr (nth 1 node))))
(defun xml-chardata (node)
"Returns the text content of an XML node"
(nth 2 node))
(defun zip2 (a b)
"Zips two lists into one list of pairs"
(mapcar* #'cons a b))
(defun find-xml-tags (tree tag)
"Retrieves all the elements at the top-level of the tree that have the given tag"
(seq-filter (lambda (x)
(and (listp x) (equal (xml-node x) tag)))
tree))
(defun traverse-xml (tree tags)
"Searches the entire tree for the given 'path' of tags, similar to basic XPath"
(seq-reduce (lambda (trees tag)
(apply #'append
(mapcar (lambda (tree) (find-xml-tags tree tag)) trees)))
tags
(list tree)))
(defun fetch-xml-from-url (url)
"Downloads the URL and parses the contents as XML"
(with-current-buffer (url-retrieve-synchronously url)
;; The first blank line is after the header section, just before the body starts
(goto-char 0)
(xml-parse-region (re-search-forward "^$") (point-max))))
(defun visit-rss-link (url)
"Fetches the given RSS feed, and displays the article links in Helm"
(let* ((dom (fetch-xml-from-url url))
(links (mapcar #'xml-chardata (traverse-xml dom '(rss channel item link))))
(titles (mapcar #'xml-chardata (traverse-xml dom '(rss channel item title))))
(rss-source (helm-build-sync-source "RSS Source"
:candidates (zip2 titles links)
:action '(("Open" . browse-url)))))
(helm :sources rss-source)))
(defun visit-atom-link (url)
"Fetches the given Atom feed, and displays the article links in Helm"
(let* ((dom (fetch-xml-from-url url))
(titles (mapcar #'xml-chardata (traverse-xml dom '(feed entry title))))
(links (mapcar (lambda (node) (xml-attr node 'href))
(traverse-xml dom '(feed entry link))))
(atom-source (helm-build-sync-source "ATOM Source"
:candidates (zip2 titles links)
:action '(("Open" . browse-url)))))
(helm :sources atom-source)))
(visit-rss-link "https://xkcd.com/rss.xml")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment