programming (and other) musings
17 Feb 2021

in no particular order xviii

Interesting bits elsewhere:

Tags: sundry
11 Feb 2021

in no particular order xvii

Interesting bits elsewhere:

Tags: sundry
08 Feb 2021

in no particular order xvi

Interesting bits elsewhere:

Tags: sundry
01 Feb 2021

consulting hunks

I use Dmitry Gutov's diff-hl to highlight (with fringe marks) modified hunks in my files under git revision control. The package comes with a command, diff-hl-next-hunk, that one can use to navigate them. So, taking a peek at consult-lines, it was straightforward to put together a consult function to navigate, with completion and preview (although i disable the latter) the hunks in the current file:

(defun jao-consult--diff-lines (&optional backward)
  (let ((candidates)
        (width (length (number-to-string
                        (line-number-at-pos (point-max)
                                            consult-line-numbers-widen)))))
    (save-excursion
      (while (ignore-errors (diff-hl-next-hunk backward))
        (let* ((str (buffer-substring (line-beginning-position)
                                      (line-end-position)))
               (no (line-number-at-pos (point)))
               (no (consult--line-number-prefix (point-marker) no width)))
          (push (concat no str) candidates))))
    (if backward candidates (nreverse candidates))))

(defun jao-consult-hunks ()
  "Search for modified hunks in the current buffer."
  (interactive)
  (let ((candidates (append (jao-consult--diff-lines)
                            (jao-consult--diff-lines t))))
    (unless candidates (error "No changes!"))
    (consult--jump
     (consult--read "Go to hunk: " candidates
                    :category 'consult--encode-location
                    :sort nil
                    :require-match t
                    :lookup #'consult--line-match
                    :preview (consult--preview-position)))))

i am sure i've taken one or two detours there that can be coded better using consult's API, but it was so nice to be able to have a working command in fifteen minutes that i couldn't resist showing off :)

Tags: emacs
26 Jan 2021

in no particular order xv

Interesting bits elsewhere:

Tags: sundry
21 Jan 2021

consulting spotify in a better way

After my latest adventures writing a small spotify library and learning in the process a bit more about consult, its author, Daniel Mendler, was kind enough to comment on how i had implemented the asynchronous search using consult's API, showing me better ways.

You can read the full discussion in this issue over at codeberg (where you can also find the latest version of the library), but the gist of it, regarding consult, is as follows.

To define a new asynchronous consult command, one wants to use consult--read, passing to it a function that generates our dynamic list of completion candidates. To create that function, one can use a pipeline of closures that successively create and massage those candidates. In the case of espotify that layering might look like this1:

(thread-first (consult--async-sink)
  (consult--async-refresh-immediate)
  (espotify--async-search type filter)
  (consult--async-throttle)
  (consult--async-split))

where we only have to implement espotify--asynch-search to construct the generator of completion candidates (more about it in a moment). The rest are helpers already provided by consult:

Consult offers also a few more closure generators that we haven't used (yet):

Back to our candidates generator. It must be a function that takes a continuation closure (the async after you in the pipeline) and returns an action dispatcher, that is, a function takiing that action as its single argument (possibly passing its results, or simply delegating, to the next handler in the pipeline). So our dispatcher generator is going to look something like this template, where we display all possible actions to be dispatched:

(defun espotify--async-search (next-async ...)
  ;; return a dispatcher for new actions
  (lambda (action)
    (pcase action
      ((pred stringp) ...) ;; if the action is a string, it's the user input
      ((pred listp) ...)   ;; if a list, candidates to be appended
      ('setup ...)
      ('destroy ...)
      ('flush ..)
      ('get ...))))

For each action, we must decide whether to handle it ourselves or simply pass it to next-async, or maybe both. Or we could ask next-async to perform new actions for us. In our case, we only care about generating a list of tracks when given a query string that ends on a marker character2, and making sure it reaches the top level. Thus, our async has only work to do when it receives a string, simplifying my original implemetation to:

(defun espotify--async-search (next type filter)
  (lambda (action)
    (pcase action
      ((pred stringp)
       (when (string-suffix-p "=" action)
         (espotify-search-all
          (lambda (items)  ;; search results callback
            (funcall next 'flush)
            (funcall next (mapcar #'spotify--format-item items)))
          (substring action 0 (- (length action)
                                 (length espotify-search-suffix)))
          type
          filter)))
      (_ (funcall next action)))))

As you can see, when we receive a search string, we launch an asynchronous search and, upon receiving its results, we flush the layer above us (so that it discards previous candidates) and pass the new candidate list to it. It is ultimately the closure returned by consult--async-sink the one keeping track of those candidates, and making them accessible to consult--read. The latter is expecting candidates to be strings (possibly with properties), while our search callback is receiving, via its items parameter, a list of alists: that's why we need to map over them with espotify--format-item. If we prefer, we can make that transformation explicit by simply returning items in that callback (via (funcall next items)) and inserting consult--async-map in our pipeline, which would now look like:

(thread-first (consult--async-sink)
  (consult--async-refresh-immediate)
  (consult--async-map #'espotify--format-item)
  (espotify--async-search type filter)
  (consult--async-throttle)
  (consult--async-split))

With all that, our code looks tidier and easier to understand (i at least understand much better its workings) 3. You can always check its latest version, in literate version, here (C-c C-v t in the org buffer will generate espotify.el for you).

Thanks Daniel!

Footnotes:

1

thread-first is the elisp equivalent of clojure's handy -> macro; as you might expect, there's also thread-last matching ->>, but i miss a bit some of the other clojure threading macros (which i'm sure are provided in one package or the other, but i digress).

2

We manually throttle network connections in this way, with the user telling us when she wants to start a search, instead of relying on timers input via consult--async-refresh-timer.

3

The immediate next thing was to add Marginalia annotations to the candidates and a couple of embark actions for good measure, but those are topics for a future post (although you can always peek under the rug).

Tags: emacs
21 Jan 2021

an emacs packages hat trick

i've found these last days a handful of really useful little emacs packages:

Tip of the hat to Daniel Mai, for a couple of the above. You might find some other interesting tidbits in his config.

Tags: emacs
11 Jan 2021

an even better video wharf

A couple of days ago, i was writing about embark and my first experiment defining a new embarking to play remote video streams. Omar Antolín Camarena, embark's author, has been kind enough to not only read it, but comment on a couple of significant improvements that i think well deserve this follow-up.

First, you'll remember that we were defining a function to detect a video URL:

(defun jao-video-finder ()
  "Check whether we're looking at a video URL.
Return (video-url . <URL>) if so."
  (when-let ((url (thing-at-point-url-at-point)))
    (when (string-match-p jao-video-url-rx url)
      (cons 'video-url url))))

Once we've got a non-null url value, even if it's not a video URL, it's still certainly a URL, and embark has a url category, so we could save a new parsing by the default URL finder by saying:

(when-let ((url (thing-at-point-url-at-point)))
  (cons (if (string-match-p jao-video-url-rx url) 'video-url 'url) url))

This has the potential drawback that we're overriding embark's finder, embark-target-url-at-point, and we might prefer to keep the latter.

Turns out that we can do that thanks to embark's target transformers. One can add to embark-transformers-alist an arbitrary function to be applied to a target of any given category, and embark will apply its actions to the transformed value. Omar calls this process, very aptly, a refinement of the target; here's how we would do it:

(defun jao-refine-url-type (url)
  "Refine type of URL in case it is a video."
  (cons (if (string-match-p jao-video-url-rx url) 'video-url 'url) url))

(add-to-list 'embark-transformer-alist '(url . jao-refine-url-type))

With this strategy, we don't need jao-video-finder at all, and it also makes lots of sense, conceptually, to have our video-url defined as a refinement rather than a new target1. Omar's second suggestion is also in line with this concept: surely we want all actions available for url also for our video-url, don't we? Well, that's exactly the reason why the embark-define-keymap macro we used to define our actions can inherit all the actions already defined in another keymap, using the :parent keyword2:

(embark-define-keymap jao-video-url-map
  "Actions on URLs pointing to remote video streams."
  :parent embark-url-map
  ("p" jao-play-video-url))

(add-to-list 'embark-keymap-alist '(video-url . jao-video-url-map))

It is worth noting that this ability to inherit a keymap is not really an embark add-on: vanilla Emacs keymaps already have it, via the standard function set-keymap-parent. You could actually define jao-video-url-map without using embark-define-keymap at all, and it'd work exactly the same.

So, our code has become shorter and more featureful: thanks, Omar!

Footnotes:

1

There's a scenario where keeping jao-video-finder could make sense, namely, if we want to alter the URL detection function. For instance, i use emacs-w3m, and there often a URL is stored as a text property (the actual text being the link text). To retrieve the URL at point there, one needs to call w3m-anchor, and embark-target-url-at-point will miss it. For that scenario, i ended up writing (and using) jao-video-finder defined with:

(when-let ((url (or (w3m-anchor) (thing-at-point-url-at-point))))
  (cons (if (string-match-p jao-video-url-rx url) 'video-url 'url) url))

Another way of accomplishing the same thing (with another tip of the hat to Omar) would be to add a specific finder for w3m anchors (and keep using the transformer for video-url):

(defun jao-w3m-url-finder ()
  (when-let ((url (w3m-anchor)))
    (cons 'url url)))

(add-to-list 'embark-target-finders #'jao-w3m-url-finder)

This way is more modular and, depending on your taste, more elegant. These functions are small and there's not a big difference between the two approaches, but if one keeps adding finders, things can easily get uglier with the former approach.

2

In my original example, i was adding also browse-url and browse-url-firefox to the video map. The former is no longer necessary, because it's already present in embark-url-map. If we wanted to make browse-url-firefox available to all URLs, we could add it to embark-url-map (remember, embark's keymaps are just Emacs keymaps). That's yet another simple way of extending embark.

Tags: emacs
09 Jan 2021

embarking videos

Inspired by Prot's musings on completion, i've, ahem, embarked in a reconsideration of my completions setup (as you might have intuited from my recent experiments with the spotify API and consult). As it happens, i'm starting to feel quite at home with a combination of selectrum, prescient and consult, and the ideas to augment what i have with contextual actions using embark seem really natural to me.

The main premise of embark is pretty simple: one has categories of targets that can be acted upon (URLs, regions, files, buffers…), and, for each category, a collection of commands that take an instance of the target and do something with it (that is, a collection of actions on target instances). As you may imagine, user-defined categories and actions are a thing in embark.

A little application of those ideas immediately popped to my mind when i started reading about embark: streaming videos from video hosting platforms. For many reasons, i try to avoid switching my context to graphical browsers and prefer to play those kind of videos by passing their URLs to mpv, which in turn will use youtube-dl to stream the contents.

Now, it's very easy to recognise when a URL is a video URL, we just need to match it against an appropriate regular expression. For example:

(defvar jao-video-url-rx
  (format "^https?://\\(?:www\\.\\)?%s/.+"
          (regexp-opt '("youtu.be"
                        "youtube.com"
                        "blip.tv"
                        "vimeo.com"
                        "infoq.com")
                      t))
  "A regular expression matching URLs that point to video streams")

Given that regular expression, we can write a "video-url target" finder function, using for instance the Emacs standard library thing-at:

(defun jao-video-finder ()
  "Check whether we're looking at a video URL.
Return (video-url . <URL>) if so."
  (when-let ((url (thing-at-point-url-at-point)))
    (when (string-match-p jao-video-url-rx url)
      (cons 'video-url url))))

Once we have a URL in our hands, playing it with mpv is very easy 1:

(defun jao-play-video-url (&optional url)
  (interactive "sURL: ")
  (let ((cmd (format "mpv %s" (shell-quote-argument url))))
    (start-process-shell-command "mpv" nil cmd)))

Now, we can put both things together with embark and tell it, first, that we have a new kind of target (video-url), and, second, what actions are associated to it (jao-play-video-url, among others).

The new target category definition is accomplished by adding its finder function to embark-target-finders alist:

(add-to-list 'embark-target-finders #'jao-video-finder)

Similarly, registering the possible actions for a target is done by adding a keymap for it to embark-keymap-alist. Embark provides the utility macro embark-define-keymap for easily defining new keymaps, so, putting both things together we have:

(embark-define-keymap jao-video-url-map
  "Actions on URLs pointing to remote video streams."
  ("p" jao-play-video-url)
  ("b" browse-url)
  ("f" browse-url-firefox))

(add-to-list 'embark-keymap-alist '(video-url . jao-video-url-map))

Besides our default, jao-play-video-url, i've thrown in for good measure a couple other actions. Note that they don't need to be specially defined, they're just stock Emacs commands taking one argument; and also that jao-video-url-map is just a run-of-the-mill Emacs keymap. As such, it can also be used and modified via the standard Emacs utilities: embark will just use the final result 2.

With that in place, we're done3: one can invoke M-x embark-act (most probably via a keyboard shortcut) when point is around (or right before) a video stream URL, and then press, say, p, to call mpv on it.

You might be thinking that writing a single Emacs command doing the same thing for us and binding it to a key is very easy too, so why bother? Well, as a matter of fact, "writing a standard Emacs command and binding it to a key" is exactly what we did, so, for starters, making it all part of the embark system is not giving us much additional trouble, if any (a couple of calls to add-to-list, all in all). In exchange, we reap the benefits of making our new action interplay with the generic utilities and integrations provided by embark (for instance, you'll see that a host of other generic actions are available and readily accessible for free for our new video URL target). This is, again, a good illustration of (and a homage to) the modularity and orthogonality of a system composed of pieces such as embark and friends.

Footnotes:

1

Note how we're defining jao-play-video-url as an interactive function, that is, as a command, so that it can be used as an action.

2

That's an illustration of a point highlighted several times by Prot in his talks: a key feature of these utilities is their smooth integration with existing Emacs vanilla APIs, in a modular way that confers them notable power. I cannot overemphasise how right on the money he is!

3

Well, this being Emacs, one is never done. We can build upon these ideas and add new tricks. For instance, i was musing about adding some kind of metadata to these video URLs, which would then be slurped by Marginalia and then be automatically available to all the other little elfs in this completion forest.

Tags: emacs
08 Jan 2021

consulting spotify

Note: you can tangle this file (e.g., with C-c C-v t inside Emacs) into three elisp packages, namely espotify.el, consult-spotify.el, and ivy-spotify.el.

We have two kinds of interaction with Spotify: via its HTTP API to perform operations such as search, and via our local DBUS to talk to client players running in our computer, such as the official client, spotifyd or mopidy-spotify. Our goal is to obtain via the former a track or album identifier that we can send then to the latter to play, with emacs completion mechanisms (consult and friends in this case) providing the glue between both worlds.

Let's start with an umbrella customization group:

(defgroup espotify nil
  "Access to Spotify API and clients"
  :group 'multimedia)

Access to Spotify's REST APIs

Authentication

We start defining a couple of end-points:

(defvar espotify-spotify-api-url
  "https://api.spotify.com/v1"
  "End-point to access Spotify's REST API.")

(defvar espotify-spotify-api-authentication-url
  "https://accounts.spotify.com/api/token"
  "End-point to access Spotify's authentication tokens.")

And we're going to need as well a client id and secret for our application, which i am again defining as variables since i expect them to be set in some secure manner instead of via customize:

(defcustom espotify-client-id ""
  "Spotify application client ID."
  :type 'string)

(defcustom espotify-client-secret ""
  "Spotify application client secret."
  :type 'string)

To get valid values for them, one just needs to register a Spotify application. From them we can derive a base64-encoded credentials value:

(defun espotify--basic-auth-credentials ()
  "Get credentials."
  (let ((credential (concat espotify-client-id ":" espotify-client-secret)))
    (concat "Basic " (base64-encode-string credential t))))

The return value of the function above is to be used as the "Authorization" header of our requests to the authorization end-point, which is going to answer with an authorization token that we can then use to further requests. Let's define a function to wrap that operation:

(defvar url-http-end-of-headers)

(defun espotify--with-auth-token (callback)
  "Use CALLBACK with a token."
  (let ((url-request-method "POST")
        (url-request-data "&grant_type=client_credentials")
        (url-request-extra-headers
         `(("Content-Type" . "application/x-www-form-urlencoded")
           ("Authorization" . ,(espotify--basic-auth-credentials)))))
    (url-retrieve espotify-spotify-api-authentication-url
                  (lambda (_status)
                    (goto-char url-http-end-of-headers)
                    (funcall callback
                             (alist-get 'access_token (json-read)))))))

For instance:

(espotify--with-auth-token
 (lambda (token) (message "Your token is: %s" token)))

obtains an auth token and prints it as a message. Note that body is evaluated asynchronously by url-retrieve, so invocations to espotify-with-auth-token evaluate to the request's buffer and are usually discarded.

Search queries

We are interested in performing a search for some term, of items of a given types (:track, :album, :artist, etc.), possibly with an additional filter. That's specified in a GET request's URL as constructed by this function:

(defun espotify--make-search-url (term types &optional filter)
  "Use TERM, TYPES and FILTER to create a URL."
  (when (null types)
    (error "Must supply a non-empty list of types to search for"))
  (let ((term (url-encode-url term)))
    (format "%s/search?q=%s&type=%s&limit=50"
            espotify-spotify-api-url
            (if filter (format "%s:%s" filter term) term)
            (mapconcat #'symbol-name types ","))))

For instance:

(espotify--make-search-url "dream blue turtles" '(album))

If we have an authorisation token and a search URL in our hands, we can use them as in the following helper function, which will calls the given callback with the results of the query:

(defun espotify--with-query-results (token url callback)
  "Call CALLBACK with the results of browsing URL with TOKEN."
  (let ((url-request-extra-headers
         `(("Authorization" . ,(concat "Bearer " token)))))
    (url-retrieve url
                  (lambda (_status)
                    (goto-char url-http-end-of-headers)
                    (funcall callback
                             (let ((json-array-type 'list))
                               (thread-first
                                   (buffer-substring (point) (point-max))
                                 (decode-coding-string 'utf-8)
                                 (json-read-from-string))))))))

So we can combine this macro with espotify--with-auth-token in a single search function that takes a callback that will be applied to a given query, specified as a triple of term, types and filter:

(defun espotify-get (callback url)
  "Perform a GET query to URL, receiving its results with CALLBACK."
  (espotify--with-auth-token
     (lambda (token)
       (espotify--with-query-results token url callback))))

(defun espotify-search (callback term types &optional filter)
  "Perform a search query for TERM, receiving its results with CALLBACK.

The types of resource we want is given by TYPES, and we can add an additional
query FILTER."
  (espotify-get callback (espotify--make-search-url term types filter)))

For instance:

(defvar espotify-query-result nil)
(espotify-search (lambda (res) (setq espotify-query-result res))
                 "dream blue turtles"
                 '(album artist))
(sit-for 0)
(mapcar 'car espotify-query-result)

So Spotify is returning a results entry per type, which in turn, contains an items with the list of actual results. So let's provide an interface for a callback that takes as many lists of items as types it asks for:

(defun espotify--type-items (res type)
  "Auxiliary function for RES and TYPE."
  (alist-get 'items (alist-get (intern (format "%ss" type)) res)))

(defun espotify-search* (callback term types &optional filter)
  "Like `espotify-search', but CALLBACK receives lists of items types.
   TERM FILTER TYPES for checkdoc compliance."
  (let* ((types (if (listp types) types (list types)))
         (cb (lambda (res)
               (let ((its (mapcar (lambda (tp)
                                    (espotify--type-items res tp))
                                  types)))
                 (apply callback its)))))
    (espotify-search cb term types filter)))

For example:

(defvar espotify-query-result nil)
(espotify-search* (lambda (al ar)
                    (message "Found %s albums, %s artists"
                             (length al) (length ar))
                    (setq espotify-query-result (cons al ar)))
                 "blue turtles"
                 '(album artist))
(sit-for 0)
(list (mapcar 'car (car (car espotify-query-result)))
      (mapcar 'car (car (cdr espotify-query-result))))

Another strategy would be to search for several types and pass to our callback the concatenation of all items:

(defun espotify-search-all (callback term &optional types filter)
  "Like `espotify-search', but CALLBACK receives a single list of results.
   TERM, FILTER to make checkdoc happy."
  (let ((types (or types '(album track artist playlist))))
    (espotify-search* (lambda (&rest items)
                        (funcall callback (apply #'append items)))
                      term
                      types
                      filter)))

Formatting and comparing search results

Search results as completion candidates

As we've seen in the previous section, our search callbacks will receive search results as alists, which we've been calling items, describing their properties. In completion functions manipulating those items we'll need ways of representing them as completion candidates, i.e., as strings with metadata attached as text properties. Thus, it's useful to define in our generic library a function, espotify-format-item to create such as string, as well as an accessor to the associated metadata:

(defun espotify--additional-item-info (item)
  "Helper creating a string description of ITEM's metadata."
  (let ((names (mapcar (lambda (a) (alist-get 'name a))
                       (cons (alist-get 'album item)
                             (alist-get 'artists item))))
        (dname (alist-get 'display_name (alist-get 'owner item))))
    (mapconcat 'identity
               (seq-filter #'identity (append names (list dname)))
               ", ")))

;;;###autoload
(defun espotify-format-item (item)
  "Format the search result ITEM as a string with additional metadata.
The metadata will be accessible via `espotify-candidate-metadata'."
  (propertize (format "%s%s"
                      (alist-get 'name item)
                      (if-let ((info (espotify--additional-item-info item)))
                          (format " (%s)" info)
                        ""))
              'espotify-item item))

;;;###autoload
(defun espotify-candidate-metadata (cand)
  "Extract from CAND (as returned by `espotify-format-item') its metadata."
  (get-text-property 0 'espotify-item cand))

Comparing search terms

Since our API involves HTTP calls using user terms that are going to be completed, we need a criterion to decide whether to launch one of those queries. An idea is to compare the current search term with the previous one and act only when it differs sufficiently. We will also introduce the convention that we're launching a search when the input string ends in "=".

(defvar espotify-search-suffix "="
  "Suffix in the search string launching an actual Web query.")

(defvar espotify-search-threshold 8
  "Threshold to automatically launch an actual Web query.")

(defun espotify--distance (a b)
  "Distance between strings A and B."
  (if (fboundp 'string-distance)
      (string-distance a b)
    (abs (- (length a) (length b)))))

(defun espotify-check-term (prev new)
  "Compare search terms PREV and NEW return the one we should search, if any."
  (when (not (string-blank-p new))
    (cond ((string-suffix-p espotify-search-suffix new)
           (substring new 0 (- (length new)
                               (length espotify-search-suffix))))
          ((>= (espotify--distance prev new) espotify-search-threshold) new))))

Sending commands to local Spotify players

Once we now the URI we want to play (that uri entry in our candidates), sending it to a local player via DBUS is fairly easy. Let's define a couple of customizable variables pointing to the service name and bus:

(defcustom espotify-service-name "mopidy"
  "Name of the DBUS service used by the client we talk to.

The official Spotify client uses `spotify', but one can also use
alternative clients such as mopidy or spotifyd."
  :type 'string)

(defcustom espotify-use-system-bus-p t
  "Whether to access the spotify client using the system DBUS."
  :type 'boolean)

and then using the Emacs DBUS API to send methods to it is a breeze:

(defun espotify--dbus-call (method &rest args)
  "Tell Spotify to execute METHOD with ARGS through DBUS."
  (apply #'dbus-call-method `(,(if espotify-use-system-bus-p :system :session)
                              ,(format "org.mpris.MediaPlayer2.%s"
                                       espotify-service-name)
                              "/org/mpris/MediaPlayer2"
                              "org.mpris.MediaPlayer2.Player"
                              ,method
                              ,@args)))

;;;###autoload
(defun espotify-play-uri (uri)
  "Use a DBUS call to play a URI denoting a resource."
  (espotify--dbus-call "OpenUri" uri))

We can also define a helper function that will play the URI associated to a formatted candidate, when present:

;;;###autoload
(defun espotify-play-candidate (cand)
 "If CAND is a formatted item string and it has a URL, play it."
 (when-let (uri (alist-get 'uri (espotify-candidate-metadata cand)))
   (espotify-play-uri uri)))

Although we're not going to use them explicitly below, we can define a couple more commands that may come in handy:

;;;###autoload
(defun espotify-play-pause ()
  "Toggle default Spotify player via DBUS."
  (interactive)
  (espotify--dbus-call "PlayPause"))

;;;###autoload
(defun espotify-next ()
  "Tell default Spotify player to play next track via DBUS."
  (interactive)
  (espotify--dbus-call "Next"))

;;;###autoload
(defun espotify-previous ()
  "Tell default Spotify player to play previous track via DBUS."
  (interactive)
  (espotify--dbus-call "Previous"))

Other actions on search results

In addition to the default action (play the URI in the selected candidate), we can define other actions on completion candidates. For instance, we could print the full item alist in its own buffer, or always look for an underlying album to play. These actions just need to access the rich metadata attached to the candidate, and will be defined as regular one-argument functions.

;;;###autoload
(defun espotify-show-candidate-info (candidate)
  "Show low-level info (an alist) about CANDIDATE."
  (pop-to-buffer (get-buffer-create "*espotify info*"))
  (read-only-mode -1)
  (delete-region (point-min) (point-max))
  (insert (propertize candidate 'face 'bold))
  (newline)
  (when-let (item (espotify-candidate-metadata candidate))
    (insert (pp-to-string item)))
  (newline)
  (goto-char (point-min))
  (read-only-mode 1))

;;;###autoload
(defun espotify-play-candidate-album (candidate)
  "Play album associated with selected CANDIDATE."
  (when-let (item (espotify-candidate-metadata candidate))
    (if-let (album (if (string= "album" (alist-get 'type item ""))
                       item
                     (alist-get 'album item)))
        (espotify-play-uri (alist-get 'uri album))
      (error "No album for %s" (alist-get 'name item)))))

;;;###autoload
(defun espotify-yank-candidate-url (candidate)
  "Add to kill ring the Spotify URL of this CANDIDATE."
  (when-let (item (espotify-candidate-metadata candidate))
    (if-let (url (alist-get 'spotify (alist-get 'external_urls item)))
        (kill-new url)
      (message "No spotify URL for this candidate"))))

You can use these actions in your programs. For instance, if you use embark, we could associate them with a new espotify-search-item target with:

(embark-define-keymap spotify-item-keymap
  "Actions for Spotify search results"
  ("y" espotify-yank-candidate-url)
  ("a" espotify-play-candidate-album)
  ("h" espotify-show-candidate-info))

(add-to-list 'embark-keymap-alist
             '(spotify-search-item . spotify-item-keymap))

Search front-end using consult

Anatomy of a consult async generator

To define a new asynchronous consult command, one wants to use consult--read, passing to it a function that generates our dynamic list of completion candidates. Our top-level consult ommand will thus have this form:

(defvar consult-spotify-history nil)

(defun consult-spotify-by (type &optional filter)
  "Consult spotify by TYPE with FILTER."
  (consult--read (consult-spotify--search-generator type filter)
                 :prompt (format "Search %ss: " type)
                 :lookup 'consult-spotify--consult-lookup
                 :category 'spotify-search-item
                 :history 'consult-spotify-history
                 :initial consult-async-default-split
                 :require-match t))

where we can write an asynchronous generator of search results as a pipeline of closures that successively create and massage completion candidates. In our case, that pipeline might look like this:

(defun consult-spotify--search-generator (type filter)
  "Generate an async search closure for TYPE and FILTER."
  (thread-first (consult--async-sink)
    (consult--async-refresh-immediate)
    (consult--async-map #'espotify-format-item)
    (consult-spotify--async-search type filter)
    (consult--async-throttle)
    (consult--async-split)))

The above follows a generic consult pattern, where consult-spotify--async-search must be an asynchronous dispatcher closure that must generate and handle a list of result items, which are in turn formated as candidates by espotify-format-item. The rest are helpers already provided by consult:

  • consult--async-split: splits the input string, one part for async, one part for filtering
  • consult--async-throttle: throttles the user input
  • consult--async-refresh-immediate: refreshes when candidates are pushed
  • consult--async-sink: collects the candidates and refreshes

Consult offers also a few more closure generators that we haven't used (yet):

  • consult--async-map: transform candidates
  • consult--async-refresh-timer: refreshes, when candidates are pushed, throttles with a timer
  • consult--async-filter: filter candidates
  • consult--async-process, a source generator handy when your candidates come from the output of executing a local process

Candidates generator for espotify searches

Back to our candidates generator. It must be a function that takes a continuation closure (the async after you in the pipeline) and returns an action dispatcher, that is, a function takiing that action as its single argument (possibly passing its results, or simply delegating, to the next handler in the pipeline). So our dispatcher generator is going to look something like this template, where we display all possible actions to be dispatched:

(defun espotify--async-search (next-async ...)
  ;; return a dispatcher for new actions
  (lambda (action)
    (pcase action
      ((pred stringp) ...) ;; if the action is a string, it's the user input
      ((pred listp) ...)   ;; if a list, candidates to be appended
      ('setup ...)
      ('destroy ...)
      ('flush ..)
      ('get ...))))

For each action, we must decide whether to handle it ourselves or simply pass it to next-async, or maybe both. Or we could ask next-async to perform new actions for us. In our case, we only care about generating a list of tracks when given a query string that ends on a marker character (or any other criteria), and making sure it reaches the top level. Thus, our async has only work to do when it receives a string. Here's how it works:

(defun consult-spotify--async-search (next type filter)
  "Async search with NEXT, TYPE and FILTER."
  (let ((current ""))
    (lambda (action)
      (pcase action
        ((pred stringp)
         (when-let (term (espotify-check-term current action))
           (setq current term)
           (espotify-search-all
            (lambda (x)
              (funcall next 'flush)
              (funcall next x))
            current
            type
            filter)))
        (_ (funcall next action))))))

We're using espotify-check-term to decide when the new term to search is going to trigger a new search, ignoring it otherwise.

Finally, we make sure that we access our formatted candidate string when consult looks up for it using the :lookup function, which we can simply define as:

(defun consult-spotify--consult-lookup (_input cands cand)
  "Find CAND in CANDS."
  (seq-find (lambda (x) (string= cand x)) cands))

User level commands

And here, finally, is our interactive command to search and play albums using consult:

;;;###autoload
(defun consult-spotify-album ()
  "Query spotify for an album using consult."
  (interactive)
  (espotify-play-candidate (consult-spotify-by 'album)))

And likewise for playlists, artists and combinations thereof:

;;;###autoload
(defun consult-spotify-artist ()
  "Query spotify for an artist using consult."
  (interactive)
  (espotify-play-candidate (consult-spotify-by 'artist)))

;;;###autoload
(defun consult-spotify-track ()
  "Query spotify for a track using consult."
  (interactive)
  (espotify-play-candidate (consult-spotify-by 'track)))

;;;###autoload
(defun consult-spotify-playlist ()
  "Query spotify for a track using consult."
  (interactive)
  (espotify-play-candidate (consult-spotify-by 'playlist)))

Adding metadata to candidates using Marginalia

Let's add metadata fields to our candidates, so that packages like Marginalia can offer it to consult or selectrum.

(defun consult-spotify--annotate (cand)
  "Compute marginalia fields for candidate CAND."
  (when-let (x (espotify-candidate-metadata cand))
    (marginalia--fields
     ((alist-get 'type x "") :face 'marginalia-mode :width 10)
     ((if-let (d (alist-get 'duration_ms x))
          (let ((secs (/ d 1000)))
            (format "%02d:%02d" (/ secs 60) (mod secs 60)))
        ""))
     ((if-let (d (alist-get 'total_tracks x)) (format "%s tracks" d) "")
      :face 'marginalia-size :width 12)
     ((if-let (d (alist-get 'release_date (alist-get 'album x x)))
          (format "%s" d)
        "")
      :face 'marginalia-date :width 10))))

(add-to-list 'marginalia-annotators-heavy
             '(spotify-search-item . consult-spotify--annotate))

Search front-end using ivy

If you are an ivy/counsel user, you don't need any of the above: counsel-spotify implements similar functionality. But i found instructive to figure out how our espotify can be used to reimplement it. It's pretty simple.

We will use ivy-read to access the completion interface, with the flag dynamic-collection set. Ivy will wait until we call ivy-candidate-updates with our items.

(defun ivy-spotify--search-by (type)
  "Perform an asynchronous spotify search, for resources of the given TYPE."
  (let ((current-term ""))
    (lambda (term)
      (when-let (term (espotify-check-term current-term term))
        (espotify-search-all
         (lambda (its)
           (let ((cs (mapcar #'espotify-format-item its)))
             (ivy-update-candidates cs)))
         (setq current-term term)
         type))
      0)))

With that, we can define our generic completing read:

(defun ivy-spotify--play-album (candidate)
  "Play album associated with selected item."
  (interactive "s")
  (let ((item (espotify-candidate-metadata candidate)))
    (if-let (album (if (string= "album" (alist-get 'type item ""))
                       item
                     (alist-get 'album item)))
        (espotify-play-uri (alist-get 'uri album))
      (error "No album for %s" (alist-get 'name item)))))

(defun ivy-spotify-search-by (type)
  (ivy-read (format "Search %s: " type)
            (ivy-spotify--search-by type)
            :dynamic-collection t
            :action `(1 ("a" ivy-spotify--play-album "Play album")
                        ("p" espotify-play-candidate ,(format "Play %s" type)))))

and our collection of searching commands:

;;;###autoload
(defun ivy-spotify-album ()
  (interactive)
  (ivy-spotify-search-by 'album))

;;;###autoload
(defun ivy-spotify-artist ()
  (interactive)
  (ivy-spotify-search-by 'artist))

;;;###autoload
(defun ivy-spotify-track ()
  (interactive)
  (ivy-spotify-search-by 'track))

;;;###autoload
(defun ivy-spotify-playlist ()
  (interactive)
  (ivy-spotify-search-by 'playlist))

Simpler than our initial consult, although it's true that we already had part of the job done. The nice "split search" that counsult offers out of the box, though, is much more difficult to get.

Packages

espotify.el (generic utilities)

;;; espotify.el --- Spotify access library  -*- lexical-binding: t; -*-

<<author-boilerplate>>
;; Package-Requires: ((emacs "26.1"))

<<license>>

;;; Commentary:

;; This package provides generic utilities to access Spotify and
;; use its query APIs, as well as controlling local players via
;; their dbus interface.  Although they can be used in other
;; programs, the functions in this package were originally
;; intended for consult-spotify and ivy-spotify.
<<spotify-app-blurb>>

;;; Code:

(require 'dbus)

<<espotify-customization>>

<<espotify-body>>

(provide 'espotify)
;;; espotify.el ends here

consult-spotify.el

;;; consult-spotify.el --- Spotify queries using consult  -*- lexical-binding: t; -*-

<<author-boilerplate>>
;; Package-Requires: ((emacs "26.1") (consult "0.5") (marginalia "0.3") (espotify "0.1"))

<<license>>

;;; Commentary:

;; This package provides functions to interactively query
;; Spotify using consult.  Its main entry points are the
;; commands `consult-spotify-album', `consult-spotify-artist',
;; `consult-spotify-playlist' and `consult-spotify-track'.
;;
;; This package is implemeted using the espotify library.
<<spotify-app-blurb>>

;;; Code:

(require 'seq)
(require 'espotify)
(require 'consult)
(require 'marginalia)

<<consult-body>>

(provide 'consult-spotify)
;;; consult-spotify.el ends here

ivy-spotify.el

;;; ivy-spotify.el --- Search spotify with ivy/counsel  -*- lexical-binding: t; -*-

<<author-boilerplate>>
;; Package-Requires: ((emacs "26.1") (spotify "0.1") (ivy "0.13.1"))

<<license>>

;;; Commentary:

;; This package provides a counsel interface to spotify's search API,
;; analogous to counsel-spotify, using the smaller espotify library.
<<spotify-app-blurb>>

;;; Code:

(require 'espotify)
(require 'ivy)

<<ivy-body>>

(provide 'ivy-spotify)
;;; ivy-spotify.el ends here

Spofity app blurb

;; For espotify to work, you need to set valid values for
;; `espotify-client-id' and `espotify-client-secret'.  To get
;; valid values for them, one just needs to register a spotify
;; application at https://developer.spotify.com/my-applications

;; All .el files have been automatically generated from the literate program
;; https://codeberg.org/jao/espotify/src/branch/main/readme.org

Author

;; Author: Jose A Ortega Ruiz <jao@gnu.org>
;; Maintainer: Jose A Ortega Ruiz
;; Keywords: multimedia
;; License: GPL-3.0-or-later
;; Version: 0.1
;; Homepage: https://codeberg.org/jao/espotify

License

;; Copyright (C) 2021  Jose A Ortega Ruiz

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

Acknowledgements

Protesilaos Stavrou's musings on completion frameworks prompted me to explore the selectrum/consult/marginalia/embark quadrivium.

The code above benefited quite a bit from Daniel Mendler's and Antolin Omar Camarena's comments, and i discussed a bit its evolution and other possibilities offered by the consult API in this blog post.

I am stealing most of the ideas on how to establish authenticated connections to the Spotify API and performing queries from counsel-spotify, with many simplifications.

Tags: emacs
Other posts
Creative Commons License
jao.io by jao is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.