index all rss twitter github linkedin email

Álvaro Ramírez

06 June 2020 Emacs, search hackingwithswift.com

hws.gif

Paul Hudson authors excellent Swift material at hackingwithswift.com. I regularly land on the site while searching for snippets from the browser. I was wondering if I could search for snippets directly from Emacs.

Turns out, hackingwithswift uses a JSON HTTP request for querying code examples. With this in mind, we can use ivy-read like Oleh Krehel's counsel-search and search for Swift snippets from our favorite editor:

(require 'request)
(require 'json)

(defun ar/counsel-hacking-with-swift-search ()
  "Ivy interface to query hackingwithswift.com."
  (interactive)
  (ivy-read "hacking with swift: "
            (lambda (input)
              (or
               (ivy-more-chars)
               (let ((request-curl-options (list "-H" (string-trim (url-http-user-agent-string)))))
                 (request
                   "https://www.hackingwithswift.com/example-code/search"
                   :type "GET"
                   :params (list
                            (cons "search" input))
                   :parser 'json-read
                   :success (cl-function
                             (lambda (&key data &allow-other-keys)
                               (ivy-update-candidates
                                (mapcar (lambda (item)
                                          (let-alist item
                                            (propertize .title 'url .url)))
                                        data)))))
                 0)))
            :action (lambda (selection)
                      (browse-url (concat "https://www.hackingwithswift.com"
                                          (get-text-property 0 'url selection))))
            :dynamic-collection t
            :caller 'ar/counsel-hacking-with-swift-search))