index all rss twitter github linkedin email
Álvaro Ramírez

Álvaro Ramírez

24 April 2022 Plain Org v1.4 released

Plain Org v1.4 is now available on the App Store.

I was on a long flight recently 🦘, so I gave list and checkbox editing a little love. There's a couple of other minor improvements included.

If you haven't heard of Plain Org, it gives you access to org files on iPhone while away from your beloved Emacs.

I love org markup, but we (iPhone + org users) are a fairly niche bunch. If you're finding Plain Org useful, please help support this effort by getting the word out. Tell your friends, tweet, or blog about it.

On to v1.4 release notes…

Improved list/checkbox editing

Adding list or checkbox items is traditionally cumbersome via the iPhone's keyboard. This release adds new toolbar actions and smart return to simplify things.


Render form feed characters

Form feed characters are now rendered within expanded headings.


Note: There's a limitation. Form feed characters at the end of a heading aren't currently displayed.


Increased all button tap areas in edit toolbar. This should hopefully improve interaction.

15 April 2022 Plain Org v1.3 released

Plain Org v1.3 is now available on the App Store. The update receives a few features, bug fixes, and improvements.

If you haven't heard of Plain Org, it gives you access to org files on iPhone while away from your beloved Emacs.

I love org markup, but we (iPhone + org users) are a fairly niche bunch. If you're finding Plain Org useful, please help support this effort by getting the word out. Tell your friends, tweet, or blog about it.

On to v1.3 release notes…

Toggle recurring tasks

You can now toggle recurring tasks with either catchup <2022-04-15 Fri ++1d>, restart <2022-04-15 Fri .+1d>, or cumulate <2022-04-15 Fri +1d> repeaters.


Log state transitions


Fullscreen view

The navigation bar now hides on scroll. This can be enabled/disabled via View > Full Screen menu.


The previous screenshot text comes from Org Mode - Organize Your Life In Plain Text, a magnificent org resource.

Deadline and scheduled date rendered

In the past, SCHEDULED and DEADLINE were rendered (but only one of them at a time). Now both are rendered alongside each other (deadline has an orange tint).


Roundtripping fidelity

Many roundtripping fidelity improvements included in 1.3. Shoutout to u/Oerm who reported unnecessary formatting changes in unmodified areas and helped test all fixes.

Other bug fixes improvements

  • Disable raw text edit menu when file is not accessible.
  • Minor improvements to inline editing layouts (vertical height and drawers).
  • ABRT and HABIT now recognized as a popular keywords.
  • Improve state transition alignment to match org mode behaviour.
  • Fixes roundtripping state transition notes (leading to data loss).
  • Log creation from share sheet.
  • Increment DEADLINE and SCHEDULED, not just first found.
  • Roundtrip more whitespace in untouched areas.
  • Fixes org syntax inadvertently parsed within begin_src blocks (leading to data loss).

27 March 2022 Plain Org v1.2.1 released

Plain Org v1.2.1 is now available on the App Store. The update receives minor features, bug fixes, and improvements.

If you haven't heard of Plain Org, it gives you access to org files on iPhone while away from your beloved Emacs.

I love org markup, but we (iPhone + org users) are a fairly niche userbase. If you're finding Plain Org useful, please help support this effort by getting the word out. Tell your friends, tweet, or blog about it.

On to v1.2.1 release notes…


State transitions and LOGBOOK drawers are now recognized and rendered as such.

Either of the following snippets are rendered as togglable LOGBOOK drawers.

TODO Feed the fish
- State "DONE"       from "TODO"       [Friday, March 11, 2022 12:23]
TODO Feed the cat
- State "DONE"       from "TODO"       [Friday, March 11, 2022 12:23]


Add task to top/bottom

Up until now, tasks were always appended to the bottom of things. This didn't work so well if you like seeing recent items bubbling up to the top.

This version adds a new setting: Settings > Add new tasks to > Top/Bottom, giving you the choice.

Note: Top is the new default value, please change this setting if you'd like to keep the previous behaviour.


Checking for changes

Local file changes aren't always detected via state change notifications, so additional checks are now in place to offer reloading files.


Open inactive files

After adding new tasks via iOS's share sheet, if the item was added to a file other than the active one, offer to open that instead.


Other improvements

  • Color keyword red/green depending on #+TODO: position.
  • Round-trip planning order (SCHEDULED, CLOSED, DEADLINE).
  • Improve tag alignment to match org mode behaviour (best effort, sorry).
  • Improve vertical spacing prior to lists.
  • Improve share sheet reliability.
  • Fix opening local links from list items.
  • Fix indent for list items without previous content.
  • Fix race condition in adding TITLE and ID to new files.
  • Fix incorrect keyword color selection in search toolbar.
  • Fix menu inadvertently closing.
  • Fix menu tapping for iPad.

12 March 2022 Grandma's vanilla pound cake


My grandmother Hilda used to bake this for us grandkids. I don't know the origin of the recipe, by my parents, aunts, and cousins, they all bake it too. I'm a big fan, but only get to eat it when visiting. Yesterday, I changed that. Finally baked it myself \o/


  • 200g salted butter
  • 2 cups (400 g) sugar
  • 4 eggs
  • 3 cups (375 g) plain flour
  • 3 teaspoons baking powder
  • 1 tablespoon (15 ml) vanilla extract
  • 1 cup (250 ml) milk
  • 2 tablespoons (30 ml) Málaga Virgen wine (port works too)


  • Ensure all ingredients are at room temperature before you start.
  • Preheat oven at 175C.
  • Separate egg yolks and whites. Keep both.
  • Consolidate liquids into a bowl (milk + wine + vanilla).
  • Consolidate sifted powders into a bowl (flour + baking powder).


  • Beat egg whites into a snowy meringue. Set aside.


  • Beat butter in the mixer until creamy (important).
  • Add sugar and mix thoroughly ensuring creamy consistency remains (important).
  • Mix yolks in thoroughly one by one.
  • Mix in the meringue.
  • You're done with the mixer.

Hand mixing

  • With a wooden spoon, alternate hand mixing the liquids and the powders. Start with liquids and end with powders.

Pour into mould

  • Pour the mix into a non-stick baking mould.


  • Bake in oven between 60 and 70 mins, but don’t be afraid to leave longer if needed. Mileage varies across ovens.
  • Use a cake tester after 60 minutes to decide how much longer to bake for (if needed).

05 March 2022 Emacs: viewing webp images

There's a recent reddit post asking how to view webp images in Emacs. I didn't know the answer, but it's something I had wanted for some time. This post was a nice reminder to go and check things out. Was happy to contribute an answer.

Turns out, it's very simple. Just set image-use-external-converter and install relevant external tools.

(setq image-use-external-converter t)

I'm a use-package user, so I prefer to set with:

(use-package image
  ;; Enable converting external formats (ie. webp) to internal ones.
  (image-use-external-converter t))

So what are the external tools needed? C-h v image-use-external-converter gives us the info we need:

If non-nil, create-image will use external converters for exotic formats.

Emacs handles most of the common image formats (SVG, JPEG, PNG, GIF and some others) internally, but images that don't have native support in Emacs can still be displayed if an external conversion program (like ImageMagick "convert", GraphicsMagick "gm" or "ffmpeg") is installed.

This variable was added, or its default value changed, in Emacs 27.1.

I happen to be a macOS user, so I install ImageMagick with:

brew install imagemagick

21 February 2022 Emacs: Fuzzy search Apple's online docs


When building software for the Apple ecosystem, Xcode is often the editor of choice. With Emacs being my personal preference, I rarely find other iOS devs with a similar mindset.

When I saw Mikael Konradsson's post describing his Emacs Swift development setup, I reached out to say hello. While exchanging tips and tricks, the topic of searching Apple's docs came up. It had been a while since I looked into this, so it was a great reminder to revisit the space.

Back in June 2020, I wrote a snippet to fuzzy search, using Emacs's ivy completion framework. With a similar online API, we could also search Apple's docs. Turns out, there is and we can we can use it to search from our beloved editor.

;;; counsel-apple-search.el -*- lexical-binding: t; -*-

(defun ar/counsel-apple-search ()
  "Ivy interface for dynamically querying docs."
  (require 'request)
  (require 'json)
  (require 'url-http)
  (ivy-read "apple docs: "
            (lambda (input)
              (let* ((url (url-encode-url (format "" input)))
                     (c1-width (round (* (- (window-width) 9) 0.3)))
                     (c2-width (round (* (- (window-width) 9) 0.5)))
                     (c3-width (- (window-width) 9 c1-width c2-width)))
                 (let ((request-curl-options (list "-H" (string-trim (url-http-user-agent-string)))))
                   (request url
                     :type "GET"
                     :parser 'json-read
                     :success (cl-function
                               (lambda (&key data &allow-other-keys)
                                  (mapcar (lambda (item)
                                            (let-alist item
                                               (format "%s   %s   %s"
                                                       (truncate-string-to-width (propertize (or .title "")
                                                                                             'face '(:foreground "yellow")) c1-width nil ?\s "…")
                                                       (truncate-string-to-width (or .description "") c2-width nil ?\s "…")
                                                       (truncate-string-to-width (propertize (string-join (or .api_ref_data.languages "") "/")
                                                                                             'face '(:foreground "cyan1")) c3-width nil ?\s "…"))
                                               'url .url)))
                                          (cdr (car data)))))))
            :action (lambda (selection)
                      (browse-url (concat ""
                                          (get-text-property 0 'url selection))))
            :dynamic-collection t
            :caller 'ar/counsel-apple-search))

13 February 2022 Plain Org v1.2 released

Although Plain Org v1.2 has been in the App Store for a little while, the release write-up was overdue, sorry. The update receives some new features and bugfixes.

If you haven't heard of Plain Org, it gives ya access to your org files on iOS while away from your beloved Emacs.

If you're finding Plain Org useful, please help support this effort by getting the word out. Tell your friends, tweet, or blog about it.

Ok, now on to what's included in the v1.2 release…

Edit heading sections inline

v1.0 introduced outline editing (for headings only). In v1.2, we can also edit section content. Press the return key multiple times to exit out section editing.


Filter by keyword/priority/tag

From the search dialog, you can now filter by keyboard, priority, and tag.



Render drawers and properties

Drawers are now rendered and can be expanded to view their content.


Open files via the Files app's "Share" sheet

From the Files app, you can now explicitly request launching files in Plain Org by using the "Share" menu.


Render LaTeX src blocks (experimental)

This one has its rough edges at the moment, so have to mark it experimental, but… you can can now render #+begin_src latex blocks.



Insert title/id in new files

New files created via Plain Org automatically get #+TITLE: and :ID: inserted by default as follows:

#+TITLE: My favorite title
:ID:       7C845D38-8D80-41B5-BEB1-94F673807355

UPDATE: Sorry, this feature currently has a bug. You may not get these values inserted into your new document. Working on a fix.

Adding new tags quicker

Add tags quicker via the new + button.


Enable/disable sticky tags

Keywords, indent, and tags are maintained when adding new headings via outline editing. If you prefer disabling sticky tags, this can now be disabled.


Improved navigation bar

v1.2 makes the navigation bar feel more at home on your iPhone. It uses a large title which scrolls into the navigation bar.



  • Fix table rendering for iPad width.
  • Fix image's horizontal padding.
  • Fix adding new tags on new headings.
  • Fix snapshotting bug resulting in Syncthing conflicts.
  • Fix tapping menu after presenting other dialogs.
  • Filter out parenthesis in file-local keywords like TODO(t).
  • Commit pending inline changes if search is requested.
  • Fix opening local links inside tables.
  • Roundtrip whitespace in empty headings.
  • Roundtrip trailing whitespace when raw-editing heading content.
  • Tapping on body content should not toggle expansion.


03 January 2022 Happy New Year and forming new habits

Hacker News has a summary of Atomic Habits (the book). In my case, I really enjoyed reading the entire book. I liked its narrative, mixing actionable and concrete advice with personal stories and experiments.

After reading Atomic Habits during the first lockdown, I was excited to try out its actionables, specially tracking to keep me honest.

I tried a bunch of iOS apps, but wanted no friction, no tracking, no cloud, no social, no analytics, no account, etc. so eventually built Flat Habits ( Also wanted to own my habit data (as plain text), so I made sure Flat Habits stored its data locally as an org file.

I'm an Emacs nutter and can say the strength in habit tracking lies in removing daily friction from the tracking process itself. A quickly accessible mobile app can really help with that. For me, Emacs plays a less important role here. The plain text part is cherry on top (bringing piece of mind around lock-in). In my case, it's been months since I looked at the plain text file itself from an Emacs org buffer. The iOS app, on the other hand, gets daily usage.

As for forming lasting habits (the actual goal here)… it's been well over a year since I started running as a regular form of exercise. While reading Atomic Habits really changed how I think of habits, a tracker played a crucial part in the daily grind. I happen to have built a tracker that plays nice with Emacs.

It's a new year. If you're looking at forming new habits, you may want some inspiration and also practical and concrete guidance. The book Atomic Habits can help with that. You can decide on which apps and how to implement the tracking process later on. Pen and paper is also a viable option and there are plenty of templates you can download.

There's a surplus of habit-tracking apps on the app stores. I built yet another one for iOS, modeled after my needs.

today_no_filter.png today_no_filter.png today_no_filter.png

12 December 2021 Plain Org v1.1 released 🎄☃️

Plain Org v1.1 is now available on the App Store. The update receives new features and bugfixes.

If you're finding Plain Org useful, please help support this effort by getting the word out. Tell your friends, tweet, or blog about it.

What is Plain Org?

Ok, now on to what's included in the v1.1 release…

Compact mode

By default, Plain Org layout uses generous padding. The new option Menu -> View -> Compact mode packs more content into your screen.


Regroup active and inactive tasks

Regrouping tasks now bubbles active ones up. Similarly, inactive tasks drop to the bottom of their node. Changes are persisted to the org file.


Native table rendering

Tables are now rendered natively but also support displaying links and other formatting within cells.


Open local ID links

If your file provider supports granting access to folders, local ID links (ie. id:eb155a82-92b2-4f25-a3c6-0304591af2f9) can now be resolved and opened from Plain Org. Note that for ID links to resolve, other org files must live in either the same directory or a subdirectory.


Fill paragraphs

If your org paragraphs contain newlines optimizing for bigger screens, you can toggle Menu -> View -> Fill paragraph to optimize rendering for your iPhone. This rendering option makes no file modifications.


By the way, the previous screenshot text comes from Org Mode - Organize Your Life In Plain Text, a magnificent org resource.

Show/hide basic scheduling

Use the new Menu -> View -> Scheduling to toggle showing SCHEDULED or DEADLINE dates.


Show/hide tags

Similarly, the new Menu -> View -> Tags option toggles displaying tags.


Native list rendering

Lists are now rendered natively. With the exception of numbered cases, list items now share a common bullet icon. Description lists are also recognized and receive additional formatting when rendered.

- First list item
Second list item
+ Third list item
1. Numbered list item
+ Term :: Description for term


Numbered checkboxes are now recognized and receive the same formatting and interaction as their non-numbered counterparts.

1. [ ] First checkbox
2. [X] Second checkbox
3. [X] Third checkbox


Reload current file

Plain Org may not be able to automatically reload files for some syncing providers. In those instances, use Menu -> Reload to explicitly request a reload.

Open .txt files

Although .org files are plain text files, they aren't always recognized by other text-editing apps. This release enables opening .txt files, so you can choose to render them in Plain Org, while giving you the option to edit elsewhere.


  • Improve vertical whitespace handling.
  • Fixes rendering edge cases.
  • Fail gracefully when creating new files on unsupported cloud providers.
  • Prevent creating new files with redundant extensions.
  • File access improvements.
  • Replicates property spacing behaviour using Emacs's org-property-format default value.
  • Fixes keyword picker border rendering.
  • Improves rendering performance for large nodes.


28 November 2021 Emacs bends again

While adding more rendering capabilities to Plain Org, it soon became apparent some sort of screenshot/snapshot testing was necessary to prevent regressing existing features. That is, we first generate a rendered snapshot from a given org snippet, followed by some visual inspection, right before we go and save the blessed snapshot (often referred to as golden) to our project. Future changes are validated against the golden snapshot to ensure rendering is still behaving as expected.

Let's say we'd like to validate table rendering with links, we can write a test as follows:

func testTableWithLinks() throws {
    matching: OrgMarkupText.make(
      | URL                    | Org link    |
      | | [[][Flat Habits]] |
      | Regular text           | Here too    |
    as: .image(layout: .sizeThatFits))

The corresponding snapshot golden can be seen below.


This is all done rather effortlessly thanks to Point Free's wonderful swift-snapshot-testing utilities.

So what does any of this have to do with Emacs? You see, as I added more snapshot tests and made modifications to the rendering logic, I needed a quick way to visually inspect and override all goldens. All the main pieces were already there, I just needed some elisp glue to bend Emacs my way™.

First, I needed to run my Xcode builds from the command line. This is already supported via xcodebuild. Next, I needed a way to parse test execution data to extract failing tests. David House's xcodebuild-to-json handles this perfectly. What's left? Glue it all up with some elisp.

Beware, the following code snippet is packed with assumptions about my project, it's messy, surely has bugs, can be optimized, etc. But the important point here is that Emacs is such an amazing malleable power tool. Throw some elisp at it and you can to bend it to your liking. After all, it's your editor.

And so here we are, I can now run snapshot tests from Emacs using my hacked up plainorg-snapshot-test-all function and quickly override (or ignore) all newly generated snapshots by merely pressing y/n keys. Oh, and our beloved web browser was also invited to the party. Press "d" to open two browser tabs if you'd like to take a closer look (not demoed below).

Success. Emacs bends again.


;;; -*- lexical-binding: t; -*-

(defun plainorg-snapshot-test-all ()
  "Invoke xcodebuild, compare failed tests screenshots side-to-side,
and offer to override them."
  (let* ((project (cdr (project-current)))
         (json-tmp-file (make-temp-file "PlainOrg_Tests_" nil ".json"))
         (default-directory project))
    (unless (file-exists-p (concat project "PlainOrg.xcodeproj"))
      (user-error "Not in PlainOrg project"))
          (get-buffer-create "*xcodebuild*")
        (let ((inhibit-read-only t))
      "-scheme" "PlainOrg" "-target" "PlainOrgTests" "-destination" "name=iPhone 13" "-quiet" "test")
     (lambda (p e)
       (with-current-buffer (get-buffer "*xcodebuild*")
         (let ((inhibit-read-only t))
           (insert (format "xcodebuild exit code: %d\n\n" (process-exit-status p)))))
       (when (not (eq 0 (process-exit-status p)))
           "--derived-data-folder" (format "/Users/%s/Library/Developer/Xcode/DerivedData/"
                                           (user-login-name)) "--output" json-tmp-file)
          (lambda (p e)
            (with-current-buffer (get-buffer "*xcodebuild*")
              (let ((inhibit-read-only t))
                (insert (format "xcodebuild-to-json exit code: %d\n\n" (process-exit-status p)))))
            (when (= 0 (process-exit-status p))
              (with-current-buffer (get-buffer "*xcodebuild*")
                (let ((inhibit-read-only t))
                  (insert "Screenshot comparison started\n\n")))
              (plainorg--snapshot-process-json (get-buffer "*xcodebuild*") json-tmp-file)
              (with-current-buffer (get-buffer "*xcodebuild*")
                (let ((inhibit-read-only t))
                  (insert "\nScreenshot comparison finished\n"))
                (read-only-mode +1))))))))
    (switch-to-buffer-other-window "*xcodebuild*")))

(defun plainorg--snapshot-process-json (result-buffer json)
  "Find all failed snapshot tests in JSON and offer to override
 screenshots, comparing them side to side."
  (let ((hashtable (with-current-buffer (get-buffer-create "*build json*")
                     (insert-file-contents json)
     (lambda (item)
       (when (equal (gethash "id" item)
          (lambda (testCase)
            (when (and (gethash "failureMessage" testCase)
                       (string-match-p "Snapshot does not match reference"
                                       (gethash "failureMessage" testCase)))
              (let* ((paths (plainorg--snapshot-screenshot-paths
                             (gethash "failureMessage" testCase)))
                     (override-result (plainorg--snapshot-override-image
                                       "Expected screenshot"
                                       (nth 0 paths) ;; old
                                       "Actual screenshot"
                                       (nth 1 paths) ;; new
                                       (nth 0 paths))))
                (when override-result
                  (with-current-buffer result-buffer
                    (let ((inhibit-read-only t))
                      (insert override-result)
                      (insert "\n")))))))
          (gethash "testCases" item))))
     (gethash "classes" (gethash "details" hashtable)))))

(defun plainorg--snapshot-screenshot-paths (failure-message)
  "Extract a paths list from FAILURE-MESSAGE of the form:

failed - Snapshot does not match reference.


Newly-taken snapshot does not match reference.
   (lambda (line)
     (string-remove-suffix "\""
                           (string-remove-prefix "\"" line)))
    (lambda (line)
      (string-prefix-p "\"" line))
    (split-string failure-message "\n"))))

(defun plainorg--snapshot-override-image (old-buffer old new-buffer new destination)
  (let ((window-configuration (current-window-configuration))
          (switch-to-buffer (with-current-buffer (get-buffer-create old-buffer)
                              (let ((inhibit-read-only t))
                              (insert-file-contents old)
          (switch-to-buffer-other-window (with-current-buffer (get-buffer-create new-buffer)
                                           (let ((inhibit-read-only t))
                                           (insert-file-contents new)
          (while (null result)
            (setq action (read-char-choice (format "Override %s? (y)es (n)o (d)iff in browser? "
                                                   (file-name-base old))
                                           '(?y ?n ?d ?q)))
            (cond ((eq action ?n)
                   (setq result
                         (format "Keeping old %s" (file-name-base old))))
                  ((eq action ?y)
                   (copy-file new old t)
                   (setq result
                         (format "Overriding old %s" (file-name-base old))))
                  ((eq action ?d)
                   (shell-command (format "open -a Firefox %s --args --new-tab" old))
                   (shell-command (format "open -a Firefox %s --args --new-tab" new)))
                  ((eq action ?q)
                   (set-window-configuration window-configuration)
                   (setq result (format "Quit %s" (file-name-base old)))))))
      (set-window-configuration window-configuration)
      (kill-buffer old-buffer)
      (kill-buffer new-buffer))

10 November 2021 Plain Org has joined the chat (iOS)

The App Store is a crowded space when it come to markdown apps. A quick search yields a wonderful wealth of choice. Kinda overwhelming, but a great problem to have nonetheless.

For those of us with org as our markup of choice, the App Store is far less crowded. I wish we could fill more than a screen's worth of search results, so you know… I could show you another pretty gif scrolling through org results. For now, we'll settle on a single frame showcasing our 4 org options.


Beorg, MobileOrg, Flat Habits, and Orgro are all great options. Each with strengths of their own. Organice, while not on the App Store, is another option for those looking for a web alternative. Of these, I had already authored one of them. More on that in a sec… You see, about a year ago I wanted to play with Swift, SPM, and lsp itself. Also, having Swift code completion in Emacs via lsp-sourcekit sounded like a fun thing to try out, so I started using it while writing a Swift org parser.


While working on the parser, I happened to be reading Atomic Habits (awesome book btw)… It was also a great time to play around with SwiftUI, which by the way, is pretty awesome too. With Atomic Habits fresh in mind, org parser in one hand, and SwiftUI in the other, I built Flat Habits: a lightweight habit tracker powered by org.


I love being able to save habit data to plain text and easily track on my iPhone (via Flat Habits) or laptop (via Emacs). I wanted to extend similar convenience to org tasks, so I built Plain Org.

My previous post mentioned quickly adding new tasks and searching existing ones as Plain Org's driving goals. Of course, neither of those are as useful without automatic cloud syncing, so pluging into iOS's third party cloud support was a must-have.

With these baseline features in place, I started an alpha/beta group via TestFlight. Early Plain Org adopters have been wonderfully supportive, given lots of great feedback, and helped shape the initial feature set you see below.

There's plenty more that can be supported, but hey let's get v1 out the door. Gotta start somewhere.

Plain Org v1 features

  • View and edit your org mode tasks while on the go.
  • Beautifully rendered org markup.
  • Sync your org files using your favorite cloud provider.
  • Create new files.
  • Outline-style editing with toolbar
    • Keywords
    • Indent
    • Priority
    • Tags
    • Formatting: bold, italic, underline, strikethrough, verbatim, and code.
  • Add links from Safari via share extension.
  • Add new tasks via Spotlight.
  • Reorder headings via drag/drop.
  • Checkboxes
    • Interactive toggling.
    • Quickly reset multiple checkboxes.
  • Follow local links.
  • Show inline images.
  • File-local keywords and visibility.
  • Filter open/closed tasks.
  • Show/hide stars.
  • Edit raw text.
  • Light/dark mode.

Plain Org joins the chat

Today Plain Org joins the likes of Beorg, MobileOrg, Flat Habits, and Orgro on the App Store.



This post was written in org mode.

19 September 2021 Plain Org for iOS (a month later)

A month ago, I posted about my desire to bring org tasks/TODOs to iOS and make them quickly available from my iPhone.

Since then, I've received some great feedback, which I've been slowly chipping away at. My intent isn't so much to move my org workflow over to iOS, but to supplement Emacs while away from my laptop.

As of now, this is what the inline edit experience looks like:


If, like me, you prefer dark mode. The app's got ya covered:


Plain Org is not yet available on the App Store, but you can get a TestFlight invite if you send me an email address. Ping me on reddit, twitter, or email me at "plainorg" + "@" + "".

You can also check out progress over at the r/plainorg subreddit.

19 August 2021 Org habits on iOS? Check! Tasks, you're next

I'm an org mode fan. This blog is powered by org. It's more of an accidental blog that started as a single org file keeping notes. I use org babel too. Oh and org habits. My never-ending list of TODOs is also powered by org. I manage all of this from Emacs and peek at TODOs using org agenda. This all works really well while I'm sitting in front of my laptop running Emacs.

But then I'm away from my laptop… and I need to quickly record habits on the go. I need it to be low-friction. Ssh'ing to an Emacs instance from a smartphone isn't an option. I'm an iPhone user, so whatever the solution, it should play nice with Emacs and org mode. I built Flat Habits for habit tracking and I'm fairly happy with the result. As of today, my longest-tracked habit is on a 452-day streak.


Moving on to org tasks/TODOs… I want something fairly frictionless while on the go. With Flat Habits as a stepping stone, I can now reuse some parts to build Plain Org. This new app should give me quick access to my tasks. The two driving goals are: quickly add new tasks and search existing ones while away from my laptop. Ok, maybe basic editing helps too. Oh and it should sync over cloud, of course.


I now have an early implementation of sorts, available on TestFlight. If you'd like to give it a try, send me an email address to receive the the invite. Ping me on reddit, twitter, or email me at "plainorg" + "@" + "".

11 July 2021 Flat Habits 1.1 released

Flat Habits 1.1 is now available on the App Store. Flat Habits is a habit tracker that’s mindful of your time, data, and privacy. It's powered by org plain text markup, enabling you to use your favorite editor (Emacs, Vim, VSCode, etc.) to poke at your habit data.

What's new?

This release implements a few of features requested by users.

Multiday weekly habits

This is the chunkiest addition and most requested feature. You can now select multiple days when scheduling weekly habits.



Historical management

Sometimes you forget to mark a habit done or make a mistake toggling one. Either way, you can now toggle any habit day from the calendar/streak view.

Long tap

Long tap shows you the editing option available for that day.


Short tap

Short tap typically toggles between "Done" and "Not done".


Where's today?

A few folks rightfully asked for today's date to be highlighted in the calendar view, and so we now have a red circle.


Improved error messages

Hopefully you don't run into issues, but if you do, I hope the app helps ya sort them out.


  • Tapping on blur now dismisses habit edit dialog.
  • Future habits now longer editable.
  • Skipped habits no longer have a default tap action.
  • Undoing from streak/calendar view now refreshes correctly.
  • Undoing habit addition on iPad removes streak/calendar view.

11 July 2021 macOS: Show in Finder / Show in Emacs

From Christian Tietze's Open macOS Finder Window in Emacs Dired, I learned about reveal-in-osx-finder. This is handy for the few times I want to transition from Emacs to Finder for file management. I say few times since Emacs's directory editor, dired, is just awesome. I've written about dired customizations here and here, but since dired is just another buffer, you can apply your Emacs magic like multiple cursors to batch rename files in an editable dired buffer.

To transition from macOS Finder to Emacs, Christian offers an Emacs interactive command that fetches Finder's location and opens a dired buffer via AppleScript. On a similar note, I learned from redditor u/pndc that Finder's proxy icons can be dragged over to Emacs, which handily drops ya into a dired buffer.

With these two solutions in mind, I looked into a third one to offer a context menu option in Finder to show the file in Emacs. This turned out to be fairly easy using Automator, which I've rarely used.


I created a flow that runs a shell script to "Show in Emacs", revealing the selected file or folder in an dired buffer. This is similar to Christian's solution, but invoked from Finder itself. The flow also uses dired-goto-file which moves the point (cursor) to the file listed under dired.


current_dir=$(dirname "$1")
osascript -e 'tell application "Emacs" to activate'
path/to/emacsclient --eval "(progn (dired \"$current_dir\") (dired-goto-file \"$1\"))"

As a bonus, I added an "Open in Emacs" option, which does as it says on the tin. Rather than show the file listed in a dired buffer, it gets Emacs to open it in your favorite major mode. This option is not technically needed since Finder already provides an "Open With" context menu, but it does remove a few click here and there.


osascript -e 'tell application "Emacs" to activate'
/Users/alvaro/homebrew/bin/emacsclient --eval "(find-file \"$1\")"

On a side note, Emacs defaults to creating new frames when opening files via "Open With" menu (or "open -a Emacs foo.txt"). I prefer to use my existing Emacs frame, which can be accomplished by setting ns-pop-up-frames to nil.

(setq ns-pop-up-frames nil)

27 June 2021 Emacs: smarter search and replace


Not long ago, I made a note to go back and read Mac for Translators's Emacs regex with Emacs lisp post. The author highlights Emacs's ability to apply additional logic when replacing text during a search-and-replace session. It does so by leveraging elisp expressions.

Coincidentally, a redditor recently asked What is the simplest way to apply a math formula to all numbers in a buffer/region? Some of the answers also point to search and replace leveraging elisp expressions.

While I rarely need to apply additional logic when replacing matches, it's nice to know we have options available in our Emacs toolbox. This prompted me to check out replace-regexp's documentation (via M-x describe-function or my favorite M-x helpful-callable). There's lots in there. Go check its docs out. You may be pleasantly surprised by all the features packed under this humble function.

For instance, \& expands to the current match. Similarly, \#& expands to the current match, fed through string-to-number. But what if you'd like to feed the match to another function? You can use \, to signal evaluation of an elisp expression. In other words, you could multiply by 3 using \,(* 3 \#&) or inserting whether a number is odd or even with something like \,(if (oddp \#&) "(odd)" "(even)").

Take the following text:


We can label each value "(odd)" or "(even)" as well as multiply by 3, by invoking replace-regexp as follows:

M-x replace-regexp

[PCRE] Replace regex:


Replace regex [-0-9.]+:

\& \,(if (oddp \#&) "(odd)" "(even)") x 3 = \,(* 3 \#&)

1 (odd) x 3 = 3
2 (even) x 3 = 6
3 (odd) x 3 = 9
4 (even) x 3 = 12
5 (odd) x 3 = 15
6 (even) x 3 = 18

It's worth noting that replace-regexp's cousin query-replace-regexp also handles all this wonderful magic.

Happy searching and replacing!

20 June 2021 Previewing SwiftUI layouts in Emacs (revisited)

Back in May 2020, I shared a snippet to extend ob-swift to preview SwiftUI layouts using Emacs org blocks.


When I say extend, I didn't quite modify ob-swift itself, but rather advised org-babel-execute:swift to modify its behavior at runtime.

Fast-forward to June 2021 and Scott Nicholes reminded me there's still interest in org babel SwiftUI support. ob-swift seems a little inactive, but no worries there. The package offers great general-purpose Swift support. On the other hand, SwiftUI previews can likely live as a single-purpose package all on its own… and so I set off to bundle the rendering functionality into a new ob-swiftui package.

Luckily, org babel's documentation has a straightforward section to help you develop support for new babel languages. They simplified things by offering template.el, which serves as the foundation for your language implementation. For the most part, it's a matter of searching, replacing strings, and removing the bits you don't need.

The elisp core of ob-swiftui is fairly simple. It expands the org block body, inserts the expanded body into a temporary buffer, and finally feeds the code to the Swift toolchain for execution.

(defun org-babel-execute:swiftui (body params)
  "Execute a block of SwiftUI code in BODY with org-babel header PARAMS.
This function is called by `org-babel-execute-src-block'"
  (message "executing SwiftUI source code block")
    (insert (ob-swiftui--expand-body body params))
     "swift -" nil 't)

The expansion in ob-swiftui–expand-body is a little more interesting. It decorates the block's body, so it can become a fully functional and stand-alone SwiftUI macOS app. If you're familiar with Swift and SwiftUI, the code should be fairly self-explanatory.

From an org babel's perspective, the expanded code is executed whenever we press C-c C-c (or M-x org-ctrl-c-ctrl-c) within the block itself.

It's worthing mentioning that our new implementation supports two babel header arguments (results and view). Both extracted from params using map-elt and replaced in the expanded Swift code to enable/disable snapshotting or explicitly setting a SwiftUI root view.

(defun ob-swiftui--expand-body (body params)
  "Expand BODY according to PARAMS and PROCESSED-PARAMS, return the expanded body."
  (let ((write-to-file (member "file" (map-elt params :result-params)))
        (root-view (when (and (map-elt params :view)
                              (not (string-equal (map-elt params :view) "none")))
                     (map-elt params :view))))
// Swift snippet heavily based on Chris Eidhof's code at:

import Cocoa
import SwiftUI
import Foundation

let screenshotURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString + \".png\")
let preview = %s

// Body to run.

extension NSApplication {
  public func run<V: View>(_ view: V) {
    let appDelegate = AppDelegate(view)
    mainMenu = customMenu
    delegate = appDelegate

  public func run<V: View>(@ViewBuilder view: () -> V) {
    let appDelegate = AppDelegate(view())
    mainMenu = customMenu
    delegate = appDelegate

extension NSApplication {
  var customMenu: NSMenu {
    let appMenu = NSMenuItem()
    appMenu.submenu = NSMenu()

    let quitItem = NSMenuItem(
      title: \"Quit \(ProcessInfo.processInfo.processName)\",
      action: #selector(NSApplication.terminate(_:)), keyEquivalent: \"q\")
    quitItem.keyEquivalentModifierMask = []

    let mainMenu = NSMenu(title: \"Main Menu\")
    return mainMenu

class AppDelegate<V: View>: NSObject, NSApplicationDelegate, NSWindowDelegate {
  var window = NSWindow(
    contentRect: NSRect(x: 0, y: 0, width: 414 * 0.2, height: 896 * 0.2),
    styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
    backing: .buffered, defer: false)

  var contentView: V

  init(_ contentView: V) {
    self.contentView = contentView

  func applicationDidFinishLaunching(_ notification: Notification) {
    window.delegate = self
    window.contentView = NSHostingView(rootView: contentView)

    if preview {
      screenshot(view: window.contentView!, saveTo: screenshotURL)
      // Write path (without newline) so org babel can parse it.
      print(screenshotURL.path, terminator: \"\")

    window.title = \"press q to exit\"
    window.setFrameAutosaveName(\"Main Window\")
    NSApp.activate(ignoringOtherApps: true)

func screenshot(view: NSView, saveTo fileURL: URL) {
  let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
  view.cacheDisplay(in: view.bounds, to: rep)
  let pngData = rep.representation(using: .png, properties: [:])
  try! pngData?.write(to: fileURL)

// Additional view definitions.
     (if write-to-file
     (if root-view
         (format "" root-view)
       (format " {%s}" body))
     (if root-view

For rendering inline SwiftUI previews in Emacs, we rely on NSView's bitmapImageRepForCachingDisplay to capture an image snapshot. We write its output to a temporary file and piggyback-ride off org babel's :results file header argument to automatically render the image inline.

Here's ob-swiftui inline rendering in action:


When rendering SwiftUI externally, we're effectively running and interacting with the generated macOS app itself.


The two snippets give a general sense of what's needed to enable org babel to handle SwiftUI source blocks. Having said that, the full source and setup instructions are both available on github.

ob-swiftui is now available on melpa.

19 June 2021 Blurring the lines between shell and editor


I recently tweeted that Vivek Haldar's 10-year old post rings true today just the same. He writes about the levels of Emacs proficiency. All 6 levels are insightful in their own right, but for the sake of this post, let's quote an extract from level 4. Shell inside Emacs:

"And then, you learned about it: M-x shell.

It was all just text. Why did you need another application for it? Why should only the shell prompt be editable? Why can’t I move my cursor up a few lines to where the last command spewed out its results? All these problems simply disappear when your shell (or shells) simply becomes another Emacs buffer, upon which all of the text manipulation power of Emacs can be brought to bear."

In other words, we aren't merely removing shell restrictions, but opening up possibilities…

Take Emacs eshell looping, for example. I use it so infrequently, I could never remember eshell's syntax. I would refer back to EmacsWiki's Eshell For Loop or Mastering Emacs's Mastering Eshell comments for a reminder. It finally dawned on me. I don't need to internalize this eshell syntax. I have YASnippet available like any other buffer. I could just type "for" and let YASnippet do the rest for me.


All I need is a tiny YASnippet:

#name : Eshell for loop
#key : for
# --
for f in ${1:*} { ${2:echo} "$f"; $3} $0

Want a gentle and succinct YASnippet intro? Check out Jake's YASnippet introduction video.

UPDATE: Bash, Zsh, and others welcome

If you're a shell-mode user, YASnippet would have you covered in your favorite shell. The expansion snippet can be modified to a Bash equivalent, giving us the same benefit. We type "for" and let YASnippet expand and hop over arguments. Here's a Bash equivalent emphasizing the hopping a little more:


#name : bash for loop
#key : for
# --
for f in ${1:*}; do ${2:echo} $f; done $0

ps. Looks like vterm, term, or ansi-term work too. See Shane Mulligan's post: Use YASnippets in term and vterm in emacs.

16 June 2021 xcodebuild's SPM support (Xcode 11)

Had been a while since I looked into generating Xcode projects from a Swift package. On my latest use of the generate-xcodeproj subcommand, I was greeted by a nice warning surprise…

swift package generate-xcodeproj
warning: Xcode can open and build Swift Packages directly. 'generate-xcodeproj' is no longer needed and will be deprecated soon.
generated: ./FooBar.xcodeproj

Xcode can handle Swift packages directly. Similarly, xcodebuild can handle them too. This isn't new. It's likely been available since Xcode 11. I just totally missed it.

Note: I've yet to dig into Xcode 13 beta, as Swift packages may already support the build/test features I was after in xcodebuild (like build/test on Catalyst).

In any case, on to xcodebuild… but let's first create a brand new Swift package.

Creating a Swift package library

mkdir FooBar && cd FooBar
swift package init --type library
Creating library package: FooBar
Creating Package.swift
Creating .gitignore
Creating Sources/
Creating Sources/FooBar/FooBar.swift
Creating Tests/
Creating Tests/FooBarTests/
Creating Tests/FooBarTests/FooBarTests.swift

List package schemes

We can use xcodebuild to list the available schemes.

xcodebuild -list
Command line invocation:
    /Applications/ -list

User defaults from command line:
    IDEPackageSupportUseBuiltinSCM = YES

Resolve Package Graph

Resolved source packages:
  FooBar: /tmp/FooBar

Information about workspace "FooBar":

Show supported platform, architecture, etc

Similarly, we can list destinations supported for the schemes.

xcodebuild -showdestinations -scheme FooBar
Command line invocation:
    /Applications/ -showdestinations -scheme FooBar

User defaults from command line:
    IDEPackageSupportUseBuiltinSCM = YES

Resolve Package Graph

Resolved source packages:
  FooBar: /tmp/FooBar

	Available destinations for the "FooBar" scheme:
		{ platform:macOS, arch:x86_64, id:... }
		{ platform:macOS, arch:x86_64, variant:Mac Catalyst, id:... }
		{ platform:iOS Simulator, id:..., OS:14.5, name:iPhone 12 Pro }

	Ineligible destinations for the "FooBar" scheme:

macOS builds

Let's build for macOS, though let's first import UIKit into FooBar.swift. This ensures we get an expected failure when building for macOS.

import UIKit

struct FooBar {
  var text = "Hello, World!"

Now let's attempt to build it…

xcodebuild build -quiet -scheme FooBar -destination 'platform=macOS'
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, arch:x86_64, id:3D097357-EB7D-565D-9058-CE7C3135927B }
{ platform:macOS, arch:x86_64, variant:Mac Catalyst, id:3D097357-EB7D-565D-9058-CE7C3135927B }
/tmp/FooBar/Sources/FooBar/FooBar.swift:1:8: error: no such module 'UIKit'
import UIKit
note: Using new build system
note: Building targets in parallel
note: Planning build
note: Analyzing workspace
note: Using build description from disk
note: Build preparation complete

The failure expected as UIKit isn't available on your typical macOS builds.

macOS Catalyst builds

We do, however, have Catalyst available, so we can use its variant to build for macOS with UIKit support, and.. voilà!

xcodebuild build -quiet -scheme FooBar -destination 'platform=macOS,variant=Mac Catalyst' && echo \\o/

06 June 2021 Emacs org block completion on melpa

When enabled, the character "<" triggers company completion of org blocks.


I get the occasional ping to package the code from this post and publish it on melpa. Finally gave it a go. Moved the code here.

This was my first time publishing on melpa. The process was very smooth. Big thanks to melpa volunteers!

01 June 2021 Emacs DWIM: do what ✨I✨ mean

Update: There's a DWIM follow-up for searching.


I was a rather puzzled the first time I spotted DWIM in an Emacs interactive command name. Don't think I remember what the command itself was, but what's important here is that DWIM stands for do what I mean.

I love DWIM interactive commands. They enable commands to be smarter and thus pack more functionality, without incurring the typical cognitive overhead associated with remembering multiple commands (or key bindings). The Emacs manual does a great job describing DWIM for the comment-dwim command:

The word “dwim” is an acronym for “Do What I Mean”; it indicates that this command can be used for many different jobs relating to comments, depending on the situation where you use it.

It's really great to find built-in DWIM-powered Emacs commands. Third-party packages often include them too. I typically gravitate towards these commands and bind them in my Emacs config. Examples being upcase-dwim, downcase-dwim, or mc/mark-all-dwim.

But what if the DWIM command doesn't exist or the author has written a command for what they mean? This is your editor, so you can make it do what you mean.

Take for example, org-insert-link, bound to C-c C-l by default. It's handy for inserting org mode links. I used it so frequently that I quickly internalized its key binding. Having said that, I often found myself doing some lightweight preprocessing prior to invoking org-insert-link. What if I can make org-insert-link do what I mean?

What do I mean?

Use URLs when in clipboard

If the URL is already in the clipboard, don't ask me for it. Just use it.

Use the region too

If I have a region selected and there's a URL in the clipboard, just sort it out without user interaction.


Automatically fetch titles

Automatically fetch URL titles from their HTML tag, but ask me for tweaks before insertion.


Fallback to org-insert-link

If my DWIM rules don't apply, fall back to using good ol' org-insert-link.

My most common use case here is when editing an existing link where I don't want neither its title nor URL automatically handled.


The code

This is your own DWIM command that does what you mean. Strive to write a clean implementation, but hey you can be forgiven for not handling all the cases that other folks may want or inlining more code than usual. The goal is to bend your editor a little, not write an Emacs package.

(defun ar/org-insert-link-dwim ()
  "Like `org-insert-link' but with personal dwim preferences."
  (let* ((point-in-link (org-in-regexp org-link-any-re 1))
         (clipboard-url (when (string-match-p "^http" (current-kill 0))
                          (current-kill 0)))
         (region-content (when (region-active-p)
                           (buffer-substring-no-properties (region-beginning)
    (cond ((and region-content clipboard-url (not point-in-link))
           (delete-region (region-beginning) (region-end))
           (insert (org-make-link-string clipboard-url region-content)))
          ((and clipboard-url (not point-in-link))
           (insert (org-make-link-string
                    (read-string "title: "
                                 (with-current-buffer (url-retrieve-synchronously clipboard-url)
                                   (dom-text (car
                                              (dom-by-tag (libxml-parse-html-region
           (call-interactively 'org-insert-link)))))

Org web tools package

I showed how to write your own DWIM command, so you can make Emacs do what ✨you✨ mean. ar/org-insert-link-dwim was built for my particular needs.

Having said all of this, alphapapa has built a great package with helpers for the org web/link space. It doesn't do what I mean (for now anyway), but it may work for you: org-web-tools: View, capture, and archive Web pages in Org-mode1.

23 May 2021 OCR bookmarks

19 May 2021 gpg: decryption failed: No secret key (macOS)

gpg: decryption failed: No secret key

OMG! Where's my secret key gone!?

But but but, gpg –list-secret-keys says they're there. Puzzled…

Ray Oei's Stack Overflow answer solved the mystery for me: pinentry never got invoked, so likely something's up with the agent… Killing (and thus restaring) the gpg-agent did the trick:

gpgconf --kill gpg-agent

Thank you internet stranger. Balance restored.

17 May 2021 Emacs plus –with-native-comp


I'm a big fan of Boris Buliga's Emacs Plus homebrew recipe for customizing and installing Emacs builds on macOS.

For a little while, I took a detour and built Emacs myself, so I could enable Andrea Corallo's fantastic native compilation. I documented the steps here. Though it was fairly straightforward, I did miss Emacs Plus's convenience.

I had been meaning to check back on Emacs Plus for native compilation support. Turns out, it was merged back in Dec 2020, and it works great!

Enabling native compilation is simple (just use –with-native-comp). As a bonus, you get all the Emacs Plus goodies. I'm loving –with-elrumo2-icon, enabling a spiffy icon to go with macOS Big Sur. –with-no-frame-refocus is also handy to avoid refocusing other frames when another one is closed.

In any case, here's the minimum needed to install Emacs Plus with native compilation support enabled:

brew tap d12frosted/emacs-plus
brew install emacs-plus@28 --with-native-comp

Sit tight. Homebrew will build and install some chunky dependencies (including gcc and libgccjit).

Note: Your init.el needs tweaking to take advantage of native compilation. See my previous post for how I set mine, or go straight to my config.

02 May 2021 Cycling window layouts with hammerspoon

Back in January, Patrik Collison tweeted about Rectangle's Todo mode. Rectangle looks great. Although I've not yet adopted it, Todo mode really resonates with me. I've been achieving similar functionality with hammerspoon.


Here's a quick and dirty function to cycle through my window layouts:

function reframeFocusedWindow()
   local win = hs.window.focusedWindow()
   local maximizedFrame = win:screen():frame()
   maximizedFrame.x = maximizedFrame.x + 15
   maximizedFrame.y = maximizedFrame.y + 15
   maximizedFrame.w = maximizedFrame.w - 30
   maximizedFrame.h = maximizedFrame.h - 30

   local leftFrame = win:screen():frame()
   leftFrame.x = leftFrame.x + 15
   leftFrame.y = leftFrame.y + 15
   leftFrame.w = leftFrame.w - 250
   leftFrame.h = leftFrame.h - 30

   local rightFrame = win:screen():frame()
   rightFrame.x = rightFrame.w - 250 + 15
   rightFrame.y = rightFrame.y + 15
   rightFrame.w = 250 - 15 - 15
   rightFrame.h = rightFrame.h - 30

   -- Make space on right
   if win:frame() == maximizedFrame then

   -- Make space on left
   if win:frame() == leftFrame then


A here's my ⌥-F binding to reframeFocusedWindow:

hs.hotkey.bind({"alt"}, "F", reframeFocusedWindow)

10 April 2021 Flat Habits meets org agenda

UPDATE: Flat Habits now has its own page at

Flat Habits v1.0.2 is out today, with habit-toggling now supported from the streak view.

Flat Habits runs on org, making it a great complement to Emacs and org agenda \o/



23 March 2021 Flat Habits v1.0.1 (org import menu)

UPDATE: Flat Habits now has its own page at

Flat Habits v1.0.1 is now released and available in the App Store.

org import (import vs in-place)

We can now import org files from the menu. Importing gives ya the option to either import (copy into the app) or open in-place. The latter enables users to sync org files with other iOS apps or just open/edit from Emacs for the full org-mode/agenda experience.

today_no_filter.png today_no_filter.png

Syncing with your desktop can be achieved by either iCloud or by enabling other providers in the Files app (after installing the likes of Google Drive, Dropbox, etc).

Please note that importing (copying into the app) is currently the recommended flow. Opening in-place and syncing is still fairly experimental, so please back up your org files regularly. If you do run into syncing issues, please get in touch.

Good luck with your habits!

17 March 2021 Flat Habits for iOS (powered by org)

UPDATE: Flat Habits now has its own page at

No friction. No social. No analytics. No account. No cloud. No lock-in.

So what is it?

An iOS app to help you form and track lasting habits.

today_no_filter.png today_no_filter.png today_no_filter.png

Why an app?

Tracking and accountability may help you develop positive habits. A simple habit-tracking app should make this easy. I'm not a habits expert, but got inspired by James Clear's Atomic Habits. Read that book if you're interested in the topic.

I wanted a frictionless habit tracker that gets out of the way, so I built one to my taste.

Sounds like a lot of work?

You mean habit tracking? It's not. I tried to make the app simple and focused. Mark a habit done whenever you do it. It's really encouraging to see your daily streaks grow. I really don't want to break them.

What kind of habits?

Any recurring habit you'd like to form like exercise, water the plants, read, make your bed, recycle, call grandma, yoga, cleaning, drink water, meditate, take a nap, make your lunch, journal, laundry, push-ups, sort out the dryer filter, floz, take your vitamins, take your meds, eat salad, eat fruit, practice a language, practice an instrument, go to bed early…

So it's like a task/todo app?

Nope. This app focuses solely on habits. Unlike todos/tasks, habits must happen regularly. If you don't water the plants, they will die. If you don't exercise regularly, you won't get the health benefits. Keep your habits separate from that long list of todos. You know, that panic-inducing list you're too afraid to look at.

Where is my data stored?

On your iPhone as a plain text file (in org mode format). You can view, edit, or migrate your data at any time (use export from the menu). You may also save it to a shared location, so you can access it from multiple devices/apps. Some of us like to use our beloved text editors (Emacs, Vim, VSCode, etc.) to poke at habits.

Got more questions?

I may not have the answer, but I can try. Ping me at flathabits*at*

Privacy policy

No personal data is sent to any server, as there is no server component to this app. There are neither third party integrations, accounts, analytics, nor trackers in this app. All your data is kept on your iPhone, unless you choose a cloud provider to sync or store your data. See your cloud provider's privacy policy for details on how they may handle it.

If you choose to send feedback by email, you have the option to review and attach logs to help diagnose issues. If you'd like an email thread to be deleted, just ask.

To join TestFlight as a beta tester, you likely gave your email address. If you'd like your email removed, just ask. Note that TestFlight has its own Terms Of Service.

21 February 2021 Frictionless org habits on iOS

UPDATE: Flat Habits now has its own page at


I've been wanting org to keep track of my daily habits for a little while. The catalyst: reading James Clear's wonderful Atomic Habits (along with plenty of lock-down inspiration).

As much as I live in Emacs and org mode, it just wasn't practical enough to rely on my laptop for tracking habits. I wanted less friction, so I've been experimenting with building a toy app for my needs. Naturally, org support was a strict requirement, so I could always poke at it from my beloved editor.

I've been using the app every day with success. The habits seem to be sticking, but equally important, it's been really fun to join the fabulous world of Emacs/Org with iOS/SwiftUI.

This is all very experimental1 and as mentioned on reddit (follow-up here) and twitter, the app isn't available on the App Store. I may consider publishing if there's enough interest, but in the mean time, you can reach out and install via TestFlight.

Send me an email address to flathabits*at* for a TestFlight invite.

2021-03-12 Update: Now with iOS Files app/sync integration

If you can sync your org file with your iPhone (ie. Drive/Dropbox/iCloud), and list it in the Files app, you should be able to open/edit1 with Flat Habits (that's the name now). With iOS Files integration, you should be able to sync your habits between your iPhone and your funky editor powering org mode2.


20 February 2021 Symbolicating iOS crashes

export DEVELOPER_DIR=$(xcode-select --print-path)
/Applications/ crashlog.crash

23 January 2021 Emacs: mu4e icons

Recently spotted mu4e-marker-icons, which adds mu4e icons using all-the-icons.

Although I'm not currently using all-the-icons, it did remind me to take a look at mu4e's built-in variables to spiff up my email. It's pretty simple. Find the icons you like and set them as follows:


(setq mu4e-headers-unread-mark    '("u" . "📩 "))
(setq mu4e-headers-draft-mark     '("D" . "🚧 "))
(setq mu4e-headers-flagged-mark   '("F" . "🚩 "))
(setq mu4e-headers-new-mark       '("N" . "✨ "))
(setq mu4e-headers-passed-mark    '("P" . "↪ "))
(setq mu4e-headers-replied-mark   '("R" . "↩ "))
(setq mu4e-headers-seen-mark      '("S" . " "))
(setq mu4e-headers-trashed-mark   '("T" . "🗑️"))
(setq mu4e-headers-attach-mark    '("a" . "📎 "))
(setq mu4e-headers-encrypted-mark '("x" . "🔑 "))
(setq mu4e-headers-signed-mark    '("s" . "🖊 "))

02 January 2021 Luxembourg travel bookmarks

02 January 2021 South Africa travel bookmarks

29 December 2020 Swift package code coverage (plus Emacs overlay)

While playing around with Swift package manager, I had a quick look into code coverage options. Luckily, coverage reporting and exporting are supported out of the box (via llvm-cov).

Ensure tests are invoked as follows:

swift test --enable-code-coverage

A high level report can be generated with:

xcrun llvm-cov report .build/x86_64-apple-macosx/debug/FooPackageTests.xctest/Contents/MacOS/FooPackageTests \ -ignore-filename-regex=".build|Tests"
Filename                                   Regions    Missed Regions     Cover   Functions  Missed Functions  Executed       Lines      Missed Lines     Cover
/tmp/Foo/Sources/Foo/Foo.swift                   2                 1    50.00%           2                 1    50.00%           6                 3    50.00%
TOTAL                                            2                 1    50.00%           2                 1    50.00%           6                 3    50.00%

llvm-cov can export as lcov format:

xcrun llvm-cov export -format="lcov" .build/x86_64-apple-macosx/debug/FooPackageTests.xctest/Contents/MacOS/FooPackageTests -ignore-filename-regex=".build|Tests" > coverage.lcov

With the report in lcov format, we can look for an Emacs package to visualize coverage in source files. Found coverlay.el to require minimal setup. I was interested in highlighting only untested areas, so I set tested-line-background-color to nil:

(use-package coverlay
  :ensure t
  (setq coverlay:tested-line-background-color nil))

After installing coverlay, I enabled the minor mode via M-x coverlay-minor-mode, invoked M-x coverlay-watch-file to watch coverage.lcov for changes, and voilà!


29 December 2020 Hiking bookmarks

28 December 2020 Patience

Via Orange Book, a reminder to myself:

  • In investing, patience is rewarded.
  • In growing a talent, patience is rewarded.
  • In building a business, patience is rewarded.
  • In love and friendships, patience is rewarded.
  • Patience = success

I feel like there's an Emacs lesson somewhere in there…

26 December 2020 Chess bookmarks

20 December 2020 40 Coolest neighbourhoods in the world

Via TimeOut's 40 Coolest Neighbourhoods in the World Right Now:

  1. Esquerra de l’Eixample, Barcelona
  2. Downtown, Los Angeles
  3. Sham Shui Po, Hong Kong
  4. Bedford-Stuyvesant, New York
  5. Yarraville, Melbourne
  6. Wedding, Berlin
  7. Shaanxi Bei Lu/Kangding Lu, Shanghai
  8. Dennistoun, Glasgow
  9. Haut-Marais, Paris
  10. Marrickville, Sydney
  11. Verdun, Montreal
  12. Kalamaja, Tallinn
  13. Hannam-dong, Seoul
  14. Bonfim, Porto
  15. Ghosttown, Oakland
  16. Chula-Samyan, Bangkok
  17. Alvalade, Lisbon
  18. Noord, Amsterdam
  19. Centro, São Paulo
  20. Holešovice, Prague
  21. Lavapiés, Madrid
  22. Opebi, Lagos
  23. Narvarte, Mexico City
  24. Uptown, Chicago
  25. Little Five Points, Atlanta
  26. Wynwood, Miami
  27. Phibsboro, Dublin
  28. Nørrebro, Copenhagen
  29. Bugis, Singapore
  30. Gongguan, Taipei
  31. Soho, London
  32. Binh Thanh, Ho Chi Minh City
  33. Melville, Johannesburg
  34. Kabutocho, Tokyo
  35. Porta Venezia, Milan
  36. Taman Paramount, Kuala Lumpur
  37. Allston, Boston
  38. Bandra West, Mumbai
  39. Arnavutköy, Istanbul
  40. Banjar Nagi, Ubud

05 December 2020 Emacs: Rotate my macOS display

Every so often, I rotate my monitor (vertical vs horizontal) for either work or to watch a movie. macOS enables changing the display rotation via a dropdown menu (under Preferences > Displays > Rotation) where you can pick between Standard, 90°, 180°, and 270°. That's all fine, but what I'd really like is a quick way to toggle between my preferred two choices: Standard and 270°.

Unsurprisingly, I'd also like to invoke it as an interactive command via Emacs's M-x (see Emacs: connect my Bluetooth speaker). With narrowing frameworks like ivy, helm, and ido, invoking these commands is just a breeze.

Turns out, this was pretty simple to accomplish, thanks to Eric Nitardy's fb-rotate command line utility. All that's left to do is wrap it in a tiny elisp function hack, add the toggling logic, and voilà!


The screen capture goes a little funky when rotating the display, but you get the idea. It works better in person :)

…and here's the snippet:

(defun ar/display-toggle-rotation ()
  (require 'cl-lib)
  (cl-assert (executable-find "fb-rotate") nil
             "Install fb-rotate from")
  ;; #  Display_ID    Resolution  ____Display_Bounds____  Rotation
  ;; 2  0x2b347692    1440x2560      0     0  1440  2560    270    [main]
  ;; From fb-rotate output, get the `current-rotation' from Column 7, row 1 zero-based.
  (let ((current-rotation (nth 7 (split-string (nth 1 (process-lines "fb-rotate" "-i"))))))
    (call-process-shell-command (format "fb-rotate -d 1 -r %s"
                                        (if (equal current-rotation "270")

29 November 2020 Emacs: Clone git repo from clipboard

Cloning git repositories is a pretty common task. For me, it typically goes something like:

  • Copy git repo URL from browser.
  • Drop to Emacs eshell.
  • Change current directory.
  • Type "git clone ".
  • Paste git repo URL.
  • Run git command.
  • Change directory to cloned repo.
  • Open dired.

No biggie, but why go through the same steps every time? We can do better. We have a hyper malleable editor, so let's get it to grab the URL from clipboard and do its thing.

shell-command or async-shell-command can help in this space, but require additional work: change location, re-type command, what if directory already exists… This is Emacs, so we can craft the exact experience we want. I did take inspiration from shell-command to display the process buffer correctly (git progress, control codes, etc.) and landed on the following experience:


;; -*- lexical-binding: t -*-

(defun ar/git-clone-clipboard-url ()
  "Clone git URL in clipboard asynchronously and open in dired when finished."
  (cl-assert (string-match-p "^\\(http\\|https\\|ssh\\)://" (current-kill 0)) nil "No URL in clipboard")
  (let* ((url (current-kill 0))
         (download-dir (expand-file-name "~/Downloads/"))
         (project-dir (concat (file-name-as-directory download-dir)
                              (file-name-base url)))
         (default-directory download-dir)
         (command (format "git clone %s" url))
         (buffer (generate-new-buffer (format "*%s*" command)))
    (when (file-exists-p project-dir)
      (if (y-or-n-p (format "%s exists. delete?" (file-name-base url)))
          (delete-directory project-dir t)
        (user-error "Bailed")))
    (switch-to-buffer buffer)
    (setq proc (start-process-shell-command (nth 0 (split-string command)) buffer command))
    (with-current-buffer buffer
      (setq default-directory download-dir)
      (require 'shell)
      (view-mode +1))
    (set-process-sentinel proc (lambda (process state)
                                 (let ((output (with-current-buffer (process-buffer process)
                                   (kill-buffer (process-buffer process))
                                   (if (= (process-exit-status process) 0)
                                         (message "finished: %s" command)
                                         (dired project-dir))
                                     (user-error (format "%s\n%s" command output))))))
    (set-process-filter proc #'comint-output-filter)))

Comment on reddit or twitter.


  • Added lexical binding.
  • Checks clipboard for ssh urls also.

23 November 2020 Pulled pork recipe

Made pulled pork a couple of times. Freestyled a bit. No expert here, but result was yummie.

Grind/blend spices

  • 2 teaspoons smoked paprika
  • 2 teaspoons cumin seeds
  • 2 teaspoons whole pepper corn mix
  • 2 teaspoons chilly flakes

If spices are whole, grind or blend them. Set aside.

Optionally: Substitute 1 teaspoon of paprika with chipotle pepper.



Mix into a paste

  • 2 tablespoons honey
  • 1 teaspoon of dijon mustard

Mix the honey, mustard, and previous spices into a paste.

Rub the mix in

Rub mix thoroughly into the pork shoulder.

Bake (1 hour)

Place in a pot (lid off) and bake in the oven for 1 hour at 200 °C.

Add liquids

  • 1/2 cup of water.
  • 4 tablespoons of apple cider vinegar.

Add liquids to pot.


Bake (3-5 hours)

Bake between 3 to 5 hours 150 °C. Check every hour or two. Does the meat fall easily when spread with two forks? If so, you're done.


Pull apart

Use two forks to pull the meat apart.


01 November 2020 Zettelkasten bookmarks

28 October 2020 Battlestation bookmarks

27 October 2020 Emacs: chaining org babel blocks

Recently wanted to chain org babel blocks. That is, aggregate separate source blocks and execute as one combined block.


I wanted the chaining primarily driven through header arguments as follows:

#+name: block-0
#+begin_src swift
  print("hello 0")

#+name: block-1
#+begin_src swift :include block-0
  print("hello 1")

#+RESULTS: block-1
: hello 0
: hello 1

I didn't find the above syntax and behaviour supported out of the box (or didn't search hard enough?). Fortunately, this is our beloved and malleable editor, so we can always bend it our way! Wasn't quite sure how to go about it, so I looked at other babel packages for inspiration. ob-async was great for that.

Turns out, advicing org-babel-execute-src-block did the job:

(defun adviced:org-babel-execute-src-block (&optional orig-fun arg info params)
  (let ((body (nth 1 info))
        (include (assoc :include (nth 2 info)))
        (named-blocks (org-element-map (org-element-parse-buffer)
                          'src-block (lambda (item)
                                       (when (org-element-property :name item)
                                         (cons (org-element-property :name item)
    (while include
      (unless (cdr include)
        (user-error ":include without value" (cdr include)))
      (unless (assoc (cdr include) named-blocks)
        (user-error "source block \"%s\" not found" (cdr include)))
      (setq body (concat (org-element-property :value (cdr (assoc (cdr include) named-blocks)))
      (setf (nth 1 info) body)
      (setq include (assoc :include
                            (org-element-property :parameters (cdr (assoc (cdr include) named-blocks)))))))
    (funcall orig-fun arg info params)))

(advice-add 'org-babel-execute-src-block :around 'adviced:org-babel-execute-src-block)

Before I built my own support, I did find that noweb got me most of what I needed, but required sprinkling blocks with placeholder references.


Combining :noweb and :prologue would have been a great match, if only prologue did expand the noweb reference. I'm sure there's an alternative I'm missing. Either way, it was fun to poke at babel blocks and build my own chaining support.

25 October 2020 Emacs: quote wrap all in region

As I find myself moving more shell commands into Emacs interactive commands to create a Swift package/project, enrich dired's featureset, or search/play Music (macOS), I often need to take a single space-separated string, make an elisp list of strings, and feed it to functions like process-lines. No biggie, but I thought it'd be a fun little function to write: take the region and wrap all items in quotes. As a bonus, made it toggable.


(defun ar/toggle-quote-wrap-all-in-region (beg end)
  "Toggle wrapping all items in region with double quotes."
  (interactive (list (mark) (point)))
  (unless (region-active-p)
    (user-error "no region to wrap"))
  (let ((deactivate-mark nil)
        (replacement (string-join
                      (mapcar (lambda (item)
                                (if (string-match-p "^\".*\"$" item)
                                    (string-trim item "\"" "\"")
                                  (format "\"%s\"" item)))
                              (split-string (buffer-substring beg end)))
                      " ")))
    (delete-region beg end)
    (insert replacement)))

18 October 2020 Emacs: org block complete and edit

I quickly got used to Emacs org block company completion. I did, however, almost always found myself running org-edit-special immediately after inserting completion. I use C-c ' for that. That's all fine, but it just felt redundant.

Why not automatically edit the source block in corresponding major mode after completion? I think I can also get used to that!


Or maybe the automatic approach is too eager? There's also a middle ground: ask immediately after.


Or maybe I don't want either in the end? Time will tell, but I now have all three options available:

(defcustom company-org-block-edit-mode 'auto
  "Customize whether edit mode, post completion was inserted."
  :type '(choice
          (const :tag "nil: no edit after insertion" nil)
          (const :tag "prompt: ask before edit" prompt)
          (const :tag "auto edit, no prompt" auto)))

The new option is now in the company-org-block snippet with my latest config.

11 October 2020 Emacs: create a Swift package/project

Been playing around with Swift Package Manager (SPM). Creating a new Swift package (ie. project) is pretty simple.

To create a library package, we can use the following:

swift package init --type library

Alternatively, to create a command-line utility use:

swift package init --type executable

Turns out, there are a few options: empty, library, executable, system-module, manifest.

With a little elisp, we can write a completing function to quickly generate a Swift package/project without the need to drop to the shell.

Bonus: I won't have to look up SPM options if I ever forget them.


(defun ar/swift-package-init ()
  "Execute `swift package init', with optional name and completing type."
  (let* ((name (read-string "name (default): "))
         (type (completing-read
                "project type: "
                ;; Splits "--type empty|library|executable|system-module|manifest"
                 (nth 1 (split-string
                           (lambda (line)
                             (string-match "--type" line))
                           (process-lines "swift" "package" "init" "--help")))
                         "   "))
         (command (format "swift package init --type %s" type)))
    (unless (string-empty-p name)
      (append command "--name " name))
    (shell-command command))
  (dired default-directory)

04 October 2020 Improved Ctrl-p/Ctrl-n macOS movement

macOS supports many Emacs bindings (out of the box). You can, for example, press C-p and C-n to move the cursor up and down (whether editing text in Emacs or any other macOS app). Jacob Rus's Customizing the Cocoa Text System offers a more in-depth picture and also shows how to customize global macOS keybindings (via DefaultKeyBinding.dict).

In addition to moving Emacs point (cursor) up/down using C-p/C-n, I've internalized the same bindings to select an option from a list. Good Emacs examples of these are company mode and ivy.

Vertical cursor movement using Emacs bindings works well in most macOS apps, including forms and text boxes in web pages. However, selecting from a completion list doesn't quite work as expected. Although the binding is technically handled, it moves the cursor within the text widget, ignoring the suggested choices.


Atif Afzal's Use emacs key bindings everywhere has a solution for the ignored case. He uses Karabiner Elements to remap c-p and c-n to arrow-up and arrow-down.

It's been roughly a week since I started using the Karabiner remapping, and I've yet to find a case where a web page (or any other macOS app) did not respond to c-p and c-n to move selection from a list.


My ~/.config/karabiner/karabiner.json configuration is as follows:

    "global": {
        "check_for_updates_on_startup": true,
        "show_in_menu_bar": true,
        "show_profile_name_in_menu_bar": false
    "profiles": [
            "complex_modifications": {
                "parameters": {
                    "basic.simultaneous_threshold_milliseconds": 50,
                    "basic.to_delayed_action_delay_milliseconds": 500,
                    "basic.to_if_alone_timeout_milliseconds": 1000,
                    "basic.to_if_held_down_threshold_milliseconds": 500,
                    "mouse_motion_to_scroll.speed": 100
                "rules": [
                        "description": "Ctrl+p/Ctrl+n to arrow up/down",
                        "manipulators": [
                                "from": {
                                    "key_code": "p",
                                    "modifiers": {
                                        "mandatory": [
                                "to": [
                                        "key_code": "up_arrow"
                                "conditions": [
                                        "type": "frontmost_application_unless",
                                        "bundle_identifiers": [
                                "type": "basic"
                                "from": {
                                    "key_code": "n",
                                    "modifiers": {
                                        "mandatory": [
                                "to": [
                                        "key_code": "down_arrow"
                                "conditions": [
                                        "type": "frontmost_application_unless",
                                        "bundle_identifiers": [
                                "type": "basic"
            "devices": [],
            "fn_function_keys": [],
            "name": "Default profile",
            "parameters": {
                "delay_milliseconds_before_open_device": 1000
            "selected": true,
            "simple_modifications": [],
            "virtual_hid_keyboard": {
                "country_code": 0,
                "mouse_key_xy_scale": 100

Bonus (C-g to exit)

Pressing Esc often dismisses or cancels macOS windows, menus, etc. This is also the case for web pages. As an Emacs user, I'm pretty used to pressing C-g to cancel, quit, or exit things. With that in mind, mapping C-g to Esc is surprisingly useful outside of Emacs. Here's the relevant Karabiner C-g binding for that:

    "description": "Ctrl+G to Escape",
    "manipulators": [
            "description": "emacs like escape",
            "from": {
                "key_code": "g",
                "modifiers": {
                    "mandatory": [
            "to": [
                    "key_code": "escape"
            "conditions": [
                    "type": "frontmost_application_unless",
                    "bundle_identifiers": [
            "conditions": [
                    "type": "frontmost_application_unless",
                    "bundle_identifiers": [
            "type": "basic"

UPDATE: Ensure bindings are only active when Emacs is not active.

04 October 2020 Basmati rice pudding recipe


Combine in a pot

  • 2/3 cup of basmati rice
  • 400 ml of coconut milk
  • 4 cups of milk [1]
  • 3 tablespoons of honey [2]
  • 1/4 teaspoon of crushed cardamom seeds [3]
  • 1/8 teaspoon of salt

Simple. Combine all ingredients in a pot.

[1] Been using powder milk since lockdown, end-result's been tasty. [2] Only tried raw honey so far. [3] Can likely use ground cardamom. I enjoy the scents while crushing.

Boil and simmer

Bring ingredients to a boil and simmer at low heat for 45 minutes. Stir occasionally.

Mix in butter

  • 1 tablespoon of butter.

Turn stove off, add a tablespoon of butter, and mix in.

Serve warm or cold

After mixing in the butter, the rice pudding is done. You can serve warm or cold.

Garnish (optional)

  • Pistachios
  • Cinnamon

Optionally garnish with either pistachios or cinnamon (or both).

27 September 2020 Adding images to pdfs (macOS)

The macOS Preview app does a great job inserting signatures to existing pdfs. I was hoping it could overlay images just as easily. Doesn't look like it's possible, without exporting/reimporting to image formats and losing pdf structure. Did I miss something?

In any case, I found formulatepro. Dormant at Google Code Archive, but also checked in to github. With a tiny patch, it builds and runs on Catalina. One can easily insert an image via "File > Place Image…".


27 September 2020 DIY bookmarks

24 September 2020 Skiing bookmarks

19 September 2020 Emacs: search/play Music (macOS)

While trying out macOS's Music app to manage offline media, I wondered if I could easily search and control playback from Emacs. Spoiler alert: yes it can be done and fuzzy searching music is rather gratifying.


Luckily, the hard work's already handled by pytunes, a command line interface to macOS's iTunes/Music app. We add ffprobe and some elisp glue to the mix, and we can generate an Emacs media index.

Indexing takes roughly a minute per 1000 files. Prolly suboptimal, but I don't intend to re-index frequently. For now, we can use a separate process to prevent Emacs from blocking, so we can get back to playing tetris from our beloved editor:

(defun musica-index ()
  "Indexes Music's tracks in two stages:
1. Generates \"Tracks.sqlite\" using pytunes (needs installed).
2. Caches an index at ~/.emacs.d/.musica.el."
  (message "Indexing music... started")
  (let* ((now (current-time))
         (name "Music indexing")
         (buffer (get-buffer-create (format "*%s*" name))))
    (with-current-buffer buffer
      (delete-region (point-min)
     (start-process name
                    (file-truename (expand-file-name invocation-name
                    "--quick" "--batch" "--eval"
                        (require 'cl-lib)
                        (require 'seq)
                        (require 'map)

                        (message "Generating Tracks.sqlite...")
                        (process-lines "pytunes" "update-index") ;; Generates Tracks.sqlite
                        (message "Generating Tracks.sqlite... done")

                        (defun parse-tags (path)
                            (if (eq 0 (call-process "ffprobe" nil t nil "-v" "quiet"
                                                    "-print_format" "json" "-show_format" path))
                                (map-elt (json-parse-string (buffer-string)
                                                            :object-type 'alist)
                              (message "Warning: Couldn't read track metadata for %s" path)
                              (message "%s" (buffer-string))
                              (list (cons 'filename path)))))

                        (let* ((paths (process-lines "sqlite3"
                                                     (concat (expand-file-name "~/")
                                                             "Music/Music/Music Library.musiclibrary/Tracks.sqlite")
                                                     "select path from tracks"))
                               (total (length paths))
                               (n 0)
                               (records (seq-map (lambda (path)
                                                   (let ((tags (parse-tags path)))
                                                     (message "%d/%d %s" (setq n (1+ n))
                                                              total (or (map-elt (map-elt tags 'tags) 'title) "No title"))
                            (prin1 records (current-buffer))
                            (write-file "~/.emacs.d/.musica.el" nil))))))
     (lambda (process state)
       (if (= (process-exit-status process) 0)
           (message "Indexing music... finished (%.3fs)"
                    (float-time (time-subtract (current-time) now)))
         (message "Indexing music... failed, see %s" buffer))))))

Once media is indexed, we can feed it to ivy for that narrowing-down fuzzy-searching goodness! It's worth mentioning the truncate-string-to-width function. Super handy for truncating strings to a fixed width and visually organizing search results in columns.

(defun musica-search ()
  (cl-assert (executable-find "pytunes") nil "pytunes not installed")
  (let* ((c1-width (round (* (- (window-width) 9) 0.4)))
         (c2-width (round (* (- (window-width) 9) 0.3)))
         (c3-width (- (window-width) 9 c1-width c2-width)))
    (ivy-read "Play: " (mapcar
                        (lambda (track)
                          (let-alist track
                            (cons (format "%s   %s   %s"
                                           (or .tags.title
                                               (file-name-base .filename)
                                               "No title") c1-width nil ?\s "…")
                                          (truncate-string-to-width (propertize (or .tags.artist "")
                                                                                'face '(:foreground "yellow")) c2-width nil ?\s "…")
                                           (propertize (or .tags.album "")
                                                       'face '(:foreground "cyan1")) c3-width nil ?\s "…"))
              :action (lambda (selection)
                        (let-alist (cdr selection)
                          (process-lines "pytunes" "play" .filename)
                          (message "Playing: %s [%s] %s"
                                   (or .tags.title
                                       (file-name-base .filename)
                                       "No title")
                                   (or .tags.artist
                                       "No artist")
                                   (or .tags.album
                                       "No album")))))))

(defun musica--index ()
    (insert-file-contents "~/.emacs.d/.musica.el")
    (read (current-buffer))))

The remaining bits are straigtforward. We add a few interactive functions to control playback:

(defun musica-info ()
  (let ((raw (process-lines "pytunes" "info")))
    (message "%s [%s] %s"
             (string-trim (string-remove-prefix "Title" (nth 3 raw)))
             (string-trim (string-remove-prefix "Artist" (nth 1 raw)))
             (string-trim (string-remove-prefix "Album" (nth 2 raw))))))

(defun musica-play-pause ()
  (cl-assert (executable-find "pytunes") nil "pytunes not installed")
  (process-lines "pytunes" "play")

(defun musica-play-next ()
  (cl-assert (executable-find "pytunes") nil "pytunes not installed")
  (process-lines "pytunes" "next"))

(defun musica-play-next-random ()
  (cl-assert (executable-find "pytunes") nil "pytunes not installed")
  (process-lines "pytunes" "shuffle" "enable")
  (let-alist (seq-random-elt (musica--index))
    (process-lines "pytunes" "play" .filename))

(defun musica-play-previous ()
  (cl-assert (executable-find "pytunes") nil "pytunes not installed")
  (process-lines "pytunes" "previous"))

Finally, if we want some convenient keybindings, we can add something like:

(global-set-key (kbd "C-c m SPC") #'musica-play-pause)
(global-set-key (kbd "C-c m i") #'musica-info)
(global-set-key (kbd "C-c m n") #'musica-play-next)
(global-set-key (kbd "C-c m p") #'musica-play-previous)
(global-set-key (kbd "C-c m r") #'musica-play-next-random)
(global-set-key (kbd "C-c m s") #'musica-search)

Hooray! Controlling music is now an Emacs keybinding away: \o/

comments on twitter.

UPDATE1: Installing pytunes with pip3 install pytunes didn't just work for me. Instead, I cloned and installed as:

git clone
pip3 install file:///path/to/pytunes
pip3 install pytz
brew install libmagic

UPDATE2: Checked in to dot files.

12 September 2020 Cheese cake recipe (no crust)



Preheat oven

Preheat oven at 175°C.

Ingredients at room temperature

Ensure the cream cheese, sour cream, and eggs are at room temperature before starting.

Mix cream cheese

  • 900g of cream cheese

Mix the cream cheese thoroughly.

Mix sugar

  • 240g of sugar

Add half the sugar. Mix in thoroughly. Add second half and mix.

Mix sour cream, corn flour, and vanilla.

  • 100g sour cream
  • 40g corn flour
  • 1tbsp vanilla bean paste

Add the three ingredients and mix well.

Mix eggs

  • 3 eggs
  • 1 egg yolk

Add the eggs and mix for 30 seconds.

Mix by hand

Finish mixing thoroughly by hand, using a wooden spoon.

Prepare pan

  • Springform pan
  • Parchment paper

A springform pan works best here. Wrap its plate with parchment paper and lock it in place.

Pour mix

  • Strainer

Pour the mix through a strainer and into the prepared pan.

Rest mix

Let the mix rest in the pan for 10 minutes to let air bubbles out.


Bake for an 1 hour 10 minutes. Maybe add another 10 minutes (or more) if surface is still pale. Turn the oven off, leave door half open, and let it sit for 20 minutes.

Cool off

Take out and let it cool off to room temperature.


Refrigerate for 4 hours (or overnight) before removing the sides of the pan.


Nom nom. Yum yum.

Bonus (topping)

I winged this one and it worked out well. Heated up frozen berries with some honey and used it as topping. The whole combo was pretty tasty.

28 August 2020 Faster macOS dock auto-hide


Via Marcin Swieczkowski's Upgrading The OSX Dock, change default to make macOS's dock auto-hide faster:

defaults write autohide-time-modifier -float 0.2; killall Dock

25 August 2020 Smarter Swift snippets

Jari Safi published a wonderful Emacs video demoing python yasnippets in action. The constructor snippet, automatically setting ivars, is just magical. I wanted it for Swift!

I took a look at the __init__ snippet from Jorgen Schäfer's elpy. It uses elpy-snippet-init-assignments to generate the assignments.

With small tweaks, we can get the same action going on for Swift \o/



# -*- mode: snippet -*-
# name: init with assignments
# key: init
# --
init(${1:, args}) {
  ${1:$(swift-snippet-init-assignments yas-text)}


(defun swift-snippet-init-assignments (arg-string)
  (let ((indentation (make-string (save-excursion
                                    (goto-char start-point)
    (string-trim (mapconcat (lambda (arg)
                              (if (string-match "^\\*" arg)
                                (format "self.%s = %s\n%s"
                                        arg arg indentation)))
                            (swift-snippet-split-args arg-string)

(defun swift-snippet-split-args (arg-string)
  (mapcar (lambda (x)
            (if (and x (string-match "\\([[:alnum:]]*\\):" x))
                (match-string-no-properties 1 x)
          (split-string arg-string "[[:blank:]]*,[[:blank:]]*" t)))

23 August 2020 Swift package manager build for iOS

While playing around with Swift package manager, it wasn't immediately obvious how to build for iOS from the command line. The default behaviour of invoking swift build is to build for the host. In my case, macOS. In any case, this was it:

swift build -Xswiftc "-sdk" -Xswiftc "/Applications/" -Xswiftc "-target" -Xswiftc "x86_64-apple-ios13.0-simulator"

ps. Can get the SDK path with:

xcrun --sdk iphonesimulator --show-sdk-path

23 August 2020 QR code bookmarks

16 August 2020 Trying out gccemacs on macOS

UPDATE: I'm no longer using these steps. See Emacs plus –with-native-comp for an easier alternative.

Below are the instructions I use to build Andrea Corallo's gccemacs on macOS. It is based on Allen Dang's handy instructions plus some changes of my own.

Install gcc and libgccjit via homebrew

brew install gcc libgccjit

Save configure script



set -o nounset
set -o errexit

# Configures Emacs for building native comp support

readonly GCC_DIR="$(realpath $(brew --prefix libgccjit))"
[[ -d $GCC_DIR ]] ||  { echo "${GCC_DIR} not found"; exit 1; }

readonly SED_DIR="$(realpath $(brew --prefix gnu-sed))"
[[ -d $SED_DIR ]] ||  { echo "${SED_DIR} not found"; exit 1; }

readonly GCC_INCLUDE_DIR=${GCC_DIR}/include
[[ -d $GCC_INCLUDE_DIR ]] ||  { echo "${GCC_INCLUDE_DIR} not found"; exit 1; }

readonly GCC_LIB_DIR=${GCC_DIR}/lib/gcc/10
[[ -d $GCC_LIB_DIR ]] ||  { echo "${GCC_LIB_DIR} not found"; exit 1; }

export PATH="${SED_DIR}/libexec/gnubin:${PATH}"

echo "Environment"
echo "-----------"
echo PATH: $PATH
echo "-----------"


./configure \
     --prefix="$PWD/nextstep/" \
     --enable-locallisppath="${PWD}/nextstep/" \
     --with-mailutils \
     --with-ns \
     --with-imagemagick \
     --with-cairo \
     --with-modules \
     --with-xml2 \
     --with-gnutls \
     --with-json \
     --with-rsvg \
     --with-native-compilation \
     --disable-silent-rules \
     --disable-ns-self-contained \

Make it executable

chmod +x

Clone Emacs source

git clone --branch master gccemacs

Configure build

cd gccemacs

Native lisp compiler found?

Verify native lisp compiler is found:

Does Emacs have native lisp compiler?                   yes


Put those cores to use. Find out how many you got with:

sysctl hw.logicalcpu
hw.logicalcpu: 4

Ok so build with:

cp -r lisp nextstep/
cp -r native-lisp nextstep/
make install

Note: Using NATIVE_FAST_BOOT=1 significantly improves build time (totalling between 20-30 mins, depending on your specs). Without it, the build can take hours.

The macOS app build (under nextstep/ is ready, but read on before launching.

Remove ~/emacs.d

You likely want to start with a clean install, byte-compiling all packages with the latest Emacs version. In any case, rename ~/emacs.d (for backup?) or remove ~/emacs.d.

init.el config

Ensure exec-path includes the script's "–prefix=" value, LIBRARY_PATH points to gcc's lib dir, and finally set comp-deferred-compilation. I wrapped the snippet in my exec-path-from-shell config, but setting early in init.el should be enough.

(use-package exec-path-from-shell
  :ensure t
  (if (and (fboundp 'native-comp-available-p)
        (message "Native comp is available")
        ;; Using since it was compiled with
        ;; ./configure --prefix="$PWD/nextstep/"
        (add-to-list 'exec-path (concat invocation-directory "bin") t)
        (setenv "LIBRARY_PATH" (concat (getenv "LIBRARY_PATH")
                                       (when (getenv "LIBRARY_PATH")
                                       ;; This is where Homebrew puts gcc libraries.
                                       (car (file-expand-wildcards
                                             (expand-file-name "~/homebrew/opt/gcc/lib/gcc/*")))))
        ;; Only set after LIBRARY_PATH can find gcc libraries.
        (setq comp-deferred-compilation t))
    (message "Native comp is *not* available")))


You're good to go. Open via finder or shell:

open nextstep/

Deferred compilation logs

After setting comp-deferred-compilation (in init.el config section), .elc files should be asyncronously compiled. Function definition should be updated to native compiled equivalent.

Look out for an Async-native-compile-log buffer. Should have content like:

Compiling .emacs.d/elpa/moody-20200514.1946/moody.el...
Compiling .emacs.d/elpa/minions-20200522.1052/minions.el...
Compiling .emacs.d/elpa/persistent-scratch-20190922.1046/persistent-scratch.el...
Compiling .emacs.d/elpa/which-key-20200721.1927/which-key.el...

Can also check for .eln files:

find ~/.emacs.d -iname *.eln | wc -l

UPDATE1: Added Symlink section for update 11.

UPDATE2: Noted using NATIVE_FAST_BOOT makes the build much faster.

UPDATE3: Removed symlinks and copied content instead. This simplifies things. Inspired by Ian Wahbe's

UPDATE4: Removed homebrew recipe patching. Thanks to Dmitry Shishkin's instructions.

UPDATE5: Use new flag –with-native-compilation and master branch.

02 August 2020 SwiftUI macOS desk clock


For time display, I've gone back and forth between an always-displayed macOS's menu bar to an auto-hide menu bar, and letting Emacs display the time. Neither felt great nor settled.

With some tweaks, Paul Hudson's How to use a timer with SwiftUI, led me to build a simple desk clock. Ok, let's not get fancy. It's really just an always-on-top floating window, showing a swiftUI label, but hey I like the minimalist feel ;)

Let's see if it sticks around or it gets in the way… Either way, here's standalone snippet. Run with swift deskclock.swift.

import Cocoa
import SwiftUI

let application = NSApplication.shared
let appDelegate = AppDelegate()
application.delegate = appDelegate
application.mainMenu = NSMenu.makeMenu()

struct ClockView: View {
  @State var time = "--:--"

  let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

  var body: some View {
    GeometryReader { geometry in

      VStack {
          .onReceive(timer) { input in
            let formatter = DateFormatter()
            formatter.dateFormat = "HH:mm"
            time = formatter.string(from: input)
          .font(.system(size: 40))
      }.frame(width: geometry.size.width, height: geometry.size.height)
        .frame(maxWidth: .infinity, maxHeight: .infinity)

extension NSWindow {
  static func makeWindow() -> NSWindow {
    let window = NSWindow(
      contentRect: NSRect.makeDefault(),
      styleMask: [.closable, .miniaturizable, .resizable, .fullSizeContentView],
      backing: .buffered, defer: false)
    window.level = .floating
    window.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenPrimary]
    window.isMovableByWindowBackground = true
    window.titleVisibility = .hidden
    window.backgroundColor = .clear
    return window

class AppDelegate: NSObject, NSApplicationDelegate {
  var window = NSWindow.makeWindow()
  var hostingView: NSView?

  func applicationDidFinishLaunching(_ notification: Notification) {
    hostingView = NSHostingView(rootView: ClockView())
    window.contentView = hostingView
    NSApp.activate(ignoringOtherApps: true)

extension NSRect {
  static func makeDefault() -> NSRect {
    let initialMargin = CGFloat(60)
    let fallback = NSRect(x: 0, y: 0, width: 100, height: 150)

    guard let screenFrame = NSScreen.main?.frame else {
      return fallback

    return NSRect(
      x: screenFrame.maxX - fallback.width - initialMargin,
      y: screenFrame.maxY - fallback.height - initialMargin,
      width: fallback.width, height: fallback.height)

extension NSMenu {
  static func makeMenu() -> NSMenu {
    let appMenu = NSMenuItem()
    appMenu.submenu = NSMenu()

        title: "Quit \(ProcessInfo.processInfo.processName)",
        action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"

    let mainMenu = NSMenu(title: "Main Menu")
    return mainMenu

30 July 2020 Mending bookmarks

17 June 2020 ffmpeg bookmarks

14 June 2020 Black lives matter (BLM) bookmarks

14 June 2020 Dogs bookmarks

06 June 2020 Emacs, search


Paul Hudson authors excellent Swift material at 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"
  (ivy-read "hacking with swift: "
            (lambda (input)
               (let ((request-curl-options (list "-H" (string-trim (url-http-user-agent-string)))))
                   :type "GET"
                   :params (list
                            (cons "search" input))
                   :parser 'json-read
                   :success (cl-function
                             (lambda (&key data &allow-other-keys)
                                (mapcar (lambda (item)
                                          (let-alist item
                                            (propertize .title 'url .url)))
            :action (lambda (selection)
                      (browse-url (concat ""
                                          (get-text-property 0 'url selection))))
            :dynamic-collection t
            :caller 'ar/counsel-hacking-with-swift-search))

23 May 2020 Preview SwiftUI layouts using Emacs org blocks


UPDATE: The snippets in this post are outdated. See ob-swiftui for better SwiftUI babel support. ✨

Chris Eidhof twitted a handy snippet that enables quickly bootstrapping throwaway SwiftUI code. It can be easily integrated into other tools for rapid experimentation.

Being a SwiftUI noob, I could use some SwiftUI integration with my editor of choice. With some elisp glue and a small patch, Chris's snippet can be used to generate SwiftUI inline previews using Emacs org babel. This is particularly handy for playing around with SwiftUI layouts.

We can piggyback ride off zweifisch's ob-swift by advicing org-babel-execute:swift to inject the org source block into the bootstrapping snippet. We also add a hook to org-babel-after-execute-hook to automatically refresh the inline preview.

If you're a use-package user, the following snippet should make things fairly self-contained (if you have melpa set up already).

(use-package org
  :hook ((org-mode . org-display-inline-images))

  (use-package ob

    (use-package ob-swift
      :ensure t
      (org-babel-do-load-languages 'org-babel-load-languages
                                   (append org-babel-load-languages
                                           '((swift     . t))))

      (defun ar/org-refresh-inline-images ()
        (when org-inline-image-overlays

      ;; Automatically refresh inline images.
      (add-hook 'org-babel-after-execute-hook 'ar/org-refresh-inline-images)

      (defun adviced:org-babel-execute:swift (f &rest args)
        "Advice `adviced:org-babel-execute:swift' enabling swiftui header param."
        (let* ((body (nth 0 args))
               (params (nth 1 args))
               (swiftui (cdr (assoc :swiftui params)))
          (when swiftui
            (assert (or (string-equal swiftui "preview")
                        (string-equal swiftui "interactive"))
                    nil ":swiftui must be either preview or interactive")
            (setq body (format
import Cocoa
import SwiftUI
import Foundation

let screenshotURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString + \".png\")
let preview = %s {

extension NSApplication {
  public func run<V: View>(@ViewBuilder view: () -> V) {
    let appDelegate = AppDelegate(view())
    mainMenu = customMenu
    delegate = appDelegate

extension NSApplication {
  var customMenu: NSMenu {
    let appMenu = NSMenuItem()
    appMenu.submenu = NSMenu()

    let quitItem = NSMenuItem(
      title: \"Quit \(ProcessInfo.processInfo.processName)\",
      action: #selector(NSApplication.terminate(_:)), keyEquivalent: \"q\")
    quitItem.keyEquivalentModifierMask = []

    let mainMenu = NSMenu(title: \"Main Menu\")
    return mainMenu

class AppDelegate<V: View>: NSObject, NSApplicationDelegate, NSWindowDelegate {
  var window = NSWindow(
    contentRect: NSRect(x: 0, y: 0, width: 414 * 0.2, height: 896 * 0.2),
    styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
    backing: .buffered, defer: false)

  var contentView: V

  init(_ contentView: V) {
    self.contentView = contentView

  func applicationDidFinishLaunching(_ notification: Notification) {
    window.delegate = self
    window.contentView = NSHostingView(rootView: contentView)

    if preview {
      screenshot(view: window.contentView!, saveTo: screenshotURL)
      // Write path (without newline) so org babel can parse it.
      print(screenshotURL.path, terminator: \"\")

    window.setFrameAutosaveName(\"Main Window\")
    NSApp.activate(ignoringOtherApps: true)

func screenshot(view: NSView, saveTo fileURL: URL) {
  let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
  view.cacheDisplay(in: view.bounds, to: rep)
  let pngData = rep.representation(using: .png, properties: [:])
  try! pngData?.write(to: fileURL)
                        (if (string-equal swiftui "preview")
            (setq args (list body params)))
          (setq output (apply f args))
          (when org-inline-image-overlays

      (advice-add #'org-babel-execute:swift

Snippet also at github gist and included in my emacs config.

UPDATE: See ob-swiftui for a better version of babel SwiftUI support.

Once the snippet is evaluated, we're ready to use in an org babel block. We introduced the :swiftui header param to switch between inline static preview and interactive mode.

To try out an inline preview, create a new org file (eg. and a source block like:

#+begin_src swift :results file :swiftui preview
  VStack(spacing: 10) {
      HStack(spacing: 10) {
      HStack(spacing: 10) {
    .frame(maxWidth: .infinity, maxHeight: .infinity)


Place the cursor anywhere inside the source block (#+begin_src/#+end_src) and press C-c C-c (or M-x org-ctrl-c-ctrl-c).

To run interactively, change the :swiftui param to interactive and press C-c C-c (or M-x org-ctrl-c-ctrl-c). When running interactively, press "q" (without ⌘) to quit the Swift app.

comments on twitter.


  • Tweaked the snippet to make it more self-contained and made the steps more reproducible. Need to work out how to package things to make them more accessible. May be best to contribute as a patch to ob-swift and we can avoid the icky advice-add.
  • Thanks to Chris Eidhof for PNG support (instead of TIFF). Also TIL Swift's print has got a terminator param.

11 May 2020 Enrich Emacs dired's batching toolbox

Shell one-liners are super handy for batch-processing files. Say you'd like to convert a bunch of images from HEIC to jpg, you could use something like:

for f in *.HEIC ; do convert "$f" "${f%.*}.jpg"; done

Save the one-liner (or memorize it) and pull it from your toolbox next time you need it. This is handy as it is, but Emacs dired is just a file-management powerhouse. Its dired-map-over-marks function is just a few elisp lines away from enabling all sorts of batch processing within your dired buffers.

Dired already enables selecting and deselecting files using all sorts of built-in mechanisms (dired-mark-files-regexp, find-name-dired, etc) or wonderful third-party packages like Matus Goljer's dired-filters.

Regardless of how you selected your files, here's a snippet to run ImageMagick's convert on a bunch of selected files:

;;; -*- lexical-binding: t; -*-

(defun ar/dired-convert-image (&optional arg)
  "Convert image files to other formats."
  (interactive "P")
  (assert (or (executable-find "convert") (executable-find "magick.exe")) nil "Install imagemagick")
  (let* ((dst-fpath)
     (lambda (fpath)
       (setq src-fpath fpath)
       (setq src-ext (downcase (file-name-extension src-fpath)))
       (when (or (null dst-ext)
                 (not (string-equal dst-ext last-ext)))
         (setq dst-ext (completing-read "to format: "
                                        (seq-remove (lambda (format)
                                                      (string-equal format src-ext))
                                                    '("jpg" "png")))))
       (setq last-ext dst-ext)
       (setq dst-fpath (format "%s.%s" (file-name-sans-extension src-fpath) dst-ext))
       (message "convert %s to %s ..." (file-name-nondirectory dst-fpath) dst-ext)
        (if (string-equal system-type "windows-nt")
            (start-process "convert"
                           (generate-new-buffer (format "*convert %s*" (file-name-nondirectory src-fpath)))
                           "magick.exe" "convert" src-fpath dst-fpath)
          (start-process "convert"
                         (generate-new-buffer (format "*convert %s*" (file-name-nondirectory src-fpath)))
                         "convert" src-fpath dst-fpath))
        (lambda (process state)
          (if (= (process-exit-status process) 0)
              (message "convert %s ✔" (file-name-nondirectory dst-fpath))
            (message "convert %s ❌" (file-name-nondirectory dst-fpath))
            (message (with-current-buffer (process-buffer process)
          (kill-buffer (process-buffer process)))))
     (dired-map-over-marks (dired-get-filename) arg))))

The snippet can be shorter, but wouldn't be as friendly. We ask users to provide desired image format, spawn separate processes (avoids blocking Emacs), and generate a basic report. Also adds support for Windows.



The snippet isn't currently capping the number of processes, but hey we can revise in the future…


Thanks to Philippe Beliveau for pointing out a bug in snippet (now updated) and changes to make it Windows compatible.

09 May 2020 Banana oats pancakes recipe



  • Ripe banana.
  • 2 Eggs.
  • 1/3 cup instant oats.
  • 1/2 teaspoon baking powder.

Really is this easy. Add all ingredients and blend.


Medium to low heat. Cook for 3 minutes. Flip. Cook for 1 minute. You're done.

06 May 2020 Emacs: connect my Bluetooth speaker

Connecting and disconnecting bluetooth devices on macOS is fairly simple: use the menu bar utility.


But could we make it quicker from our beloved editor?

Turns out with a little elisp glue, we can fuzzy search our Bluetooth devices and toggle connections. We can use Oleh Krehel's ivy-read for fuzzy searching and Felix Lapalme's nifty BluetoothConnector to list devices and toggle Bluetooth connections.

As a bonus, we can make it remember the last selected device, so you can quickly toggle it again.

(defun ar/ivy-bluetooth-connect ()
  "Connect to paired bluetooth device."
  (assert (string-equal system-type "darwin")
          nil "macOS only. Sorry :/")
  (assert (executable-find "BluetoothConnector")
          nil "Install BluetoothConnector from")
  (ivy-read "(Dis)connect: "
             (lambda (item)
               (let* ((device (split-string item " - "))
                      (mac (nth 0 device))
                      (name (nth 1 device)))
                 (propertize name
                             'mac mac)))
              (lambda (line)
                ;; Keep lines like: af-8c-3b-b1-99-af - Device name
                (string-match-p "^[0-9a-f]\\{2\\}" line))
              (with-current-buffer (get-buffer-create "*BluetoothConnector*")
                ;; BluetoothConnector exits with 64 if no param is given.
                ;; Invoke with no params to get a list of devices.
                (unless (eq 64 (call-process "BluetoothConnector" nil (current-buffer)))
                  (error (buffer-string)))
                (split-string (buffer-string) "\n"))))
            :require-match t
            :preselect (when (boundp 'ar/misc-bluetooth-connect--history)
                         (nth 0 ar/misc-bluetooth-connect--history))
            :history 'ar/misc-bluetooth-connect--history
            :caller 'ar/toggle-bluetooth-connection
            :action (lambda (device)
                      (start-process "BluetoothConnector"
                                     (get-buffer-create "*BluetoothConnector*")
                                     "BluetoothConnector" (get-text-property 0 'mac device) "--notify"))))


comments on twitter.

02 May 2020 Duti: changing default macOS apps

Future self example, setting to open all aiff files on macOS:

duti -s io.mpv aiff

26 April 2020 Neapolitan pizza recipe

Full disclosure: I'm a complete noob at making pizza. It's my second pizza, but hey, it was tasty and fun to make! Making pizza at home is not as far-fetched as I initially thought.


I've made this recipe a couple of times. Made two improvements worth mentioning.

Flan tin / quiche pan


My first pizzas were rectangular, matching the baking tray shape, but I really wanted round pies. I found a quiche pan at home and gave that a try. Worked pretty well. The dish bottom comes up, which is pretty handy.

Double baking

Bake in two stages:

  1. Bake the pizza for 6 minutes (without the mozarella) at bottom of oven.
  2. Add mozzarella and make for 4 minutes at top of the oven.


Ok, on to the recipe now…

Dissolve the yeast

  • 7g of yeast.
  • 325ml of lukewarm water.

Dissolve the yeast in the lukewarm water.

Mixing the dough



  • 500g of flour.
  • 1 teaspoon of salt.

Gradually add flour to the yeast and water mix, using the bottom of a spoon to work it until smooth (no lumps). The dough will be very sticky at first. Stay faithful to the spoon. It'll work. BBC's How to make pizza like a Neapolitan master has a great demo. I followed the dough technique.

Kneading the dough



Sprinkle some flour on the table and knead the dough (punch, stretch, and fold many times) from previous step. Eventually, the dough will hold its shape.

Make 4 balls



Roll the dough into a cylinder and cut into 4 pieces. Make 4 balls.

Make the tomato sauce



  • 500g of passata.
  • 3 cloves of garlic.

I love garlic. Who doesn't? Slice the garlic finely and combine with the passata in a class jar. Shake it a little. Garlic and passata. That's your sauce.

Cover for 2 hours



Place the 4 dough balls into a container and cover with a damp cloth for 2 hours. You can make 4 pizzas.

*Rookie mistake: I should have used a bigger container. The balls grew and merged.

Preheat oven

Preheat the oven at 250°C.

Stretch base


Sprinkle more flour on table prior to shaping the dough. Place ball on table, flatten. Flip over, flatten again. Gradually stretch until you have the shape and thickness desired.

Place base on baking tray

  • Semolina
  • Aluminium foil

Line up the tray with some aluminium foil. Before transferring the base on to the baking tray, sprinkle semolina (or breadcrumbs) on the foil (it helps prevent the dough from sticking).





  • Tomato sauce.
  • Salt.
  • Olive oil.
  • Parmesan cheese.
  • 125g of Mozzarella cheese.
  • Fresh basil.

Spread some of the tomato sauce with a spoon. Sprinkle salt, olive oil, and parmesan cheese. Break the mozzarella into pieces and spread throughout. Add some basil leaves. Your basic margherita pizza is now ready for the oven.

Bake pizza

Place the tray in the oven for 10 minutes. This worked for my oven, which goes up to 250°C. Either way, keep an eye on it.

Post baking toppings


  • Anchovies.

Controversial, but I really like anchovies. Add them post-baking and you're good to go. Enjoy your pizza.

21 April 2020 TIL (today I learned) bookmarks

19 April 2020 mu/mu4e 1.4 released


mu/mu4e 1.4 is out. About a week ago, I built and installed its pre-release version (1.3.10) and noted build steps on macOS. It's been working great for me. Today, I updated to 1.4.

I was keen to try the new release out. I had been experiencing a short delay immediately after syncing/indexing mail. An initial investigation pointed to contact syncing, but I didn't dig further. The 1.4 release notes had a promising entry:

In many cases, `mu4e' used to receive all contacts after each indexing operation; this was slow for some users, so we have updated this to only get the contacts that have changed since the last round.

After upgrading. The delay is gone for me \o/

Note: there are a few config tweaks needed for the 1.4 upgrade, but these are well-documented in the release notes. For me, it primarily consisted of:

  • Swapping elisp mu4e-maildir var for mu init –maildir path/to/local/IMAP.
  • Swapping elisp mu4e-user-mail-address-list for mu init –my-address –my-address
  • Disabling mu4e-maildirs-extension (not yet compatible with mu 1.4). No issues here, since I hardly ever look at the mu4e-main buffer. I have global binding to my unread messages that looks a little something like this:
(defun ar/mu4e-view-unread-messages ()
  (mu4e-headers-search-bookmark (concat "flag:unread AND "
                                        "flag:unread AND "
                                        "NOT flag:trashed AND "
                                        "(maildir:/box1/INBOX OR "

comments on twitter.

14 April 2020 Libya travel bookmarks

07 April 2020 Trimming videos with ffmpeg

Via Bernd Verst's Trim Videos Instantly:

Start time + duration

ffmpeg -ss hh:mm:ss.msec -i in.mpeg -c copy -map 0 -t hh:mm:ss.msec out.mpeg

Start time + end time

ffmpeg -ss hh:mm:ss.msec -i in.mpeg -c copy -map 0 -to hh:mm:ss.msec out.mpeg

06 April 2020 Emacs's counsel-M-x meets multiple cursors

I'm a fan of Magnar Sveen's multiple cursors Emacs implementation. It's just so fun to use and works very well with commands bound to my favorite keys.

Every now and then I'd like to execute extended commands on all cursors, but they have no keys bound to them. If you're an ivy/counsel fan like me (and all packages by Abo Abo), you use counsel-M-x to invoke commands. However, counsel-M-x doesn't support multiple cursors out of the box. Luckily, this is Emacs and we can fix that…

Back in December 2019, I made a note to revisit u/snippins1987's weekly tip to pair helm-M-x with multiple cursors. Finally got back to it. With a few changes, we can also make the snippet work with counsel-M-x \o/.

(defun adviced:counsel-M-x-action (orig-fun &rest r)
  "Additional support for multiple cursors."
  (apply orig-fun r)
  (let ((cmd (intern (counsel--string-trim-left (nth 0 r) "\\^"))))
    (when (and (boundp 'multiple-cursors-mode)
               (not (memq cmd mc--default-cmds-to-run-once))
               (not (memq cmd mc/cmds-to-run-once))
               (or mc/always-run-for-all
                   (memq cmd mc--default-cmds-to-run-for-all)
                   (memq cmd mc/cmds-to-run-for-all)
                   (mc/prompt-for-inclusion-in-whitelist cmd)))
      (mc/execute-command-for-all-fake-cursors cmd))))

(advice-add #'counsel-M-x-action


05 April 2020 Portland travel bookmarks

29 March 2020 String inflection Emacs package

string-inflection (by Akira Ikeda) is a nifty package to cycle through string case styles: camel, snake, kebab… The package includes a handful of cycling functions for different languages (Ruby, Python and Java), but it's easy to mix and match to roll your own. For now, I'm binding C-M-j to string-inflection-cycle, which is an alias to string-inflection-ruby-style-cycle.

(use-package string-inflection
  :ensure t
  :bind (:map prog-mode-map
              ("C-M-j" . string-inflection-cycle)))


comments on twitter

28 March 2020 Turkey travel bookmarks

25 March 2020 Dal Makhani (black lentils) recipe


Soak beans (overnight)

  • 1 cup of rajmah (kidney beans).
  • 2 cups of sabut urad (black lentils).

Place the beans in a bowl with plenty of water. The beans will soak it up so ensure there's enough.

Cooking the beans

  • 3 liters of water.
  • 1 cinamon stick.
  • 1 tablespoon of turmeric.
  • 2 bay leaves.

Drain the beans and combine new ingredients into a pot. Bring to a boil and simer for 1.5 hours. Check beans aren't firm (give 'em a try'). If so extend another 15-30 mins.

Prepare paste

  • 1 4 cm piece of ginger.
  • 1 large onion.
  • 6 garlic cloves.
  • 2 tomatoes.

Put through blender (with choppin pulse) or food processor until you get a paste.

Golden paste

  • Paste.
  • 3 tablespoons of butter.
  • 1 tablespoon of cumin seeds.
  • 1 tablespoon of coriander powder.
  • 1 tablespoon of chilly powder (or less to make milder).
  • 1 fresh red hot pepper (find one with medium heat level) chopped.
  • 1 tablespoon of cumin powder.
  • 1/4 cup of water.
  • 3/4 tablespoon of salt.

Heat up the butter (medium heat) and brown the cumin seeds (maybe 30 seconds). Add the paste from previous step. Cook for about 4 minutes or until golden. Add the remaining ingredients in step (except water) and cook for another 30 seconds. Add the water and salt and mix to make more fluid and remove from heat.

Tying it all together

  • 1 tablespoon of panchpuram (cumin, fenugreek, mistard, and fennel seeds).
  • 300 ml of double cream.

Combine the cooked beans, golden paste, and seeds. Simmer for about 15 minutes. Add the cream and cook for about 2 minutes. You are effectively done.

Garnish (optional)

You can serve and optionally garnish with some chopped coriander. Recommended.

Serve with

Basmati rice, rotis, buttered buns, or even corn tortillas (unorthodox, but hey).

21 March 2020 Modern Emacs lisp libraries

Quickly finding related built-in elisp functions (without prefixes) can sometimes take a little poking around.

Some modern and predictable built-in exceptions I now reach out to are:

  • map.el for key/values, alists, hash-tables and arrays (built-in as of Emacs 25.1).
  • seq.el for sequence manipulation functions (built-in as of Emacs 25.1).
  • subr-x.el has a handful of string functions (built-in as of Emacs 24.4).
  • let-alist.el wonderful syntax for alists, great for json (built-in as of Emacs 25.1).

If you don't mind reaching out to third-party libs (you likely have some of these already installed), here are some modern, predictable, and well-documented ones that always get me out of trouble:

I'm happy with built-ins like map.el, seq.el, and let-alist.el. subr-x.el is also pretty nice, although not as full-featured as third-party s.el.

Am I missing out on other modern built-ins or third-party libraries?

UPDATE: Added a handful of newly discovered libraries plus suggestions by Daniel Martín (thanks!). Not tried any of these myself.

comments on twitter

20 March 2020 Emacs smartparens auto-indent

While I do most editing in Emacs, I use Xcode every now and then. I like Xcode's pair matching (of brackets) combined with its auto-indent.


While the wonderful smartparens gives Emacs pair-matching powers, it doesn't automatically indent between pairs (out of the box anyway).


Luckily, smartparens does provide sp-local-pair, which enables us to achieve a similar goal.

With a short snippet, we can autoindent between {}, [], and () when pressing return in-between.

(defun indent-between-pair (&rest _ignored)
  (forward-line -1)

(sp-local-pair 'prog-mode "{" nil :post-handlers '((indent-between-pair "RET")))
(sp-local-pair 'prog-mode "[" nil :post-handlers '((indent-between-pair "RET")))
(sp-local-pair 'prog-mode "(" nil :post-handlers '((indent-between-pair "RET")))


comments on twitter

20 March 2020 Solarpunk bookmarks

10 March 2020 sqlite bookmarks

26 February 2020 covid-19 bookmarks

15 February 2020 Security bookmarks

15 February 2020 Nix bookmarks

10 January 2020 Plants bookmarks

29 December 2019 Fixing Honeywell CM927's dead screen

My Honeywell CM927 thermostat's screen had been getting progressively worse over the last year. As of late, the screen was of little use.


A random search yielded the Honeywell CM927 LCD screen fail - common? thread, with a promising comment by Phil:

"Strip the unit and remove the circuit board (just a few plastic clips, no screws). Remove the LCD assembly from the circuit board (more plastic clips and an eight pin push connection). Removed the LCD unit from the clear plastic housing (more plastic clips). Finally heat up the plastic ribbon where it is stuck to the circuit board (hair dryer will do trick) and then firmly press it onto the circuit board… probably worth doing this several times; in effect you are remating the ribbon to the circuit board by softening the adhesive. Put it all back together and it should be working again."

Phil's instructions were great. There's also a super handy video by El Tucan, also linked by Stevie.

Success \o/

Heating up the plastic ribbon and pressing it onto the circuit board did the trick for me. Took a few tries for all segments to appear, but the screen is looking great again.

Thank you Internet strangers! :)


29 December 2019 SwiftUI bookmarks

updated: 23 November 2021

17 December 2019 Studying for Life in the UK test

Today, I passed the Life in the UK test. Wasn't quite sure how to study for it. During my commutes, I listened to the Life in the UK 2019 Test audio book.

A friend recommended Overall, I found their practice tests very useful. Taking a bunch tests helped me internalize the material.

Took some notes along the way (mostly data with years attached) and dumped it into an org table. This helped me form a mental timeline.

NOTE: These tables alone are not comprehensive enough to prepare for the exam. You'll need to know additional information without dates attached.


Year Event
2012 Diamond Jubilee
1999 Scottish Parliament formed
1973 UK joins the EU \o/
1972 Mary Peters wins Gold medal (pentathlon)
1957 Treaty of Rome signed (March 25)
1950 UK signs European Convention of Human Rights
1949 Ireland become a republic
1947 Granted independence India, Pakistan and Ceylon (Sri Lanka)
1945 Clement Attlee elected
1945 Alexander Fleming discovers penicillin
1945 WWII ends
1944 Butler Act (free secondary education England/Wales)
1940 Battle of Britain
1939 Germany invades Poland
1930s Turing Machine
1936 BBC first regular television service
1932 First television broadcast
1930 British Film Studios Fluorish
1928 Women/men with same voting age
1918 WWI ends (November 11, 11am)
1903 Emmeline Pankhurst Women’s Social and Political Union (suffragettes)
1902 Motor-car racing in UK
1896 First film shown publicly
1899-1902 The Boer War (South Africa)
1870-1914 120000 Russian and Polish Jews fled to Britain to escape prosecution
1853-1856 Crimean War
1851 Great Exhibition (showcased Crystal Palance)
1837 Queen Victoria becomes queen (at 18)
1833 Emancipation Act (abolished slavery throughout British Emprire)
1832 The Reform Act (increase number of people with voting rights)
1776 North American colonies want out (don't tax us without representation)
1745 Bonnie Prince Charlie gets support by clansmen from Scottish highlands
1714 Queen Ann dies, George I becomes King
1689 Bill of rights (limit rights of kings)
1688 William of Orange invades England (proclaims king)
1680-1720 Huguenots refugees came to England (from France)
1695 Free press (newspapers) established
1679 Habeas Corpus Act (right to trial)
1649-1660 Cromwell rules republic for 11 years (Charles I executed)
1642 English Civil war (Cavaliers vs Roundheads)
1606 Union flag created
1588 English beat Spanish Armada
1348 Black death (third population die)
1314 Battle of Bannockburn: Robert the Bruce (Scottish King) beats English invasion
1284 Statute of Rhuddlan (Wales joins Crown, by King Edward I)
1215 Magna Carta created
1066 Norman Conquest (Saxon King Harold killed by William I)
300-400 AD Christians appear in Britain
789 AD Vikings first visit Britain and raid coastal towns
6000 years ago Farmers come to Britain


Year Population
2010 > 62 million
2005 < 60 million
1998 57 million
1951 50 million
1901 40 million
1851 20 million
1700 5 million
1600 > 4 million

01 December 2019 Georgia travel bookmarks

24 November 2019 Wizard zines comics in Emacs eshell

Over at, Julia Evans authors wonderful zines on topics like git, networking, linux, command-line utilities, and others. Some zines are paid. Some are free. No affiliation here, just a fan.

A little while ago, Julia tweeted about a utility she's building to view her original comics on similar topics. I instantly thought it'd be a fun tool to implement for Emacs eshell.

Since then, I subscribed to and received a few comics (awk, tar, and bash tricks). I saved them locally (using topic name and dropping file extensions).

ls -1 ~/Downloads/wizardzines-comics/

By no means battle-tested, but here's an elisp snippet defining the ecomic command. It displays inlined comics in the handy eshell.

(require 'eshell)
(require 'iimage)

(defvar wizardzines-comics-path "~/Downloads/wizardzines-comics")

(defun eshell/ecomic (&rest args)
  "Display command comic in ARGS.
Note: ensure comic images live in `wizardzines-comics-path', named with
command name and no extension."
   "ecomic" args
   '((?h "help" nil nil "show this usage screen")
     :external "ecomic"
     :usage "COMMAND

Show COMMAND comic from Julia Evans'")
   (let* ((command (nth 0 (eshell-stringify-list (eshell-flatten-list args))))
          (image-fpath (concat (file-name-as-directory
                                (expand-file-name wizardzines-comics-path))
     (unless (file-exists-p image-fpath)
       (error "comic: \"%s\" not found :-(" command))
     (eshell-buffered-print "\n")
     (add-text-properties 0 (length image-fpath)
                          `(display ,(create-image image-fpath)
     (eshell-buffered-print image-fpath)


comments on twitter


  • Tweaked title.

21 November 2019 Emacs counsel default search switches

Following up from Enhanced Emacs searching with counsel switches, rather than remembering silver searcher and ripgrep switches, we can use counsel's ivy-initial-inputs-alist to set these up as default visible switches.

(push '(counsel-ag . "--file-search-regex '' -- ") ivy-initial-inputs-alist)
(push '(counsel-rg . "--glob '**' -- ") ivy-initial-inputs-alist)

The default switches stay out of the way in typical searches, but can be easily modified to include (or exclude) results matching specific file names.


comments on twitter

10 November 2019 Enhanced Emacs searching with counsel switches

The counsel family of Emacs search commands are great for searching the filesystem. More specifically, counsel-rg, counsel-ag, and counsel-pt, which use the popular ripgrep, silver searcher, and platinum searcher utilities.

counsel-rg is my default searcher. It returns results quickly, with live updates as I tweak the search query.

Up until recently, my queries typically matched text in files only. This works great, but every so often I wished I could amend the query to include (or exclude) results matching specific file names. Turns out, you can prepend the search query with additional switches using the "–" separator.

The switches are usually utility-specific, but if we wanted to keep results from file names matching a glob, we can prepend the ripgrep query with something like "–glob Make* –" or the shorter version "-g Make* –".

rg: -g Make* – install


10 November 2019 Emacs org block company completion

UPDATE: This is now available on melpa.

Back in 2015, I bound the "<" key to a hydra for quickly inserting org blocks. The idea came from Oleg's post on org-mode block templates in Hydra. The suggested binding settled in my muscle memory without much effort.

Fast forward to Febrary 2019. I replaced the hydra with org-insert-structure-template when org-try-structure-completion was removed from org mode. No biggie, as I kept the same binding to "<" and hardly noticed the change.

Since my primary use-case for easy templates is inserting source blocks, I was keen to expedite choosing the source language as well as inserting the source block itself.

Writing a small company mode completion backend fits my primary use-case pretty well.


The company backend looks as follow (Warning: Snippet needs Org v9.2).

Note: This code is not up to date. Install via melpa or see its repository.

(require 'map)
(require 'org)
(require 'seq)

(defvar company-org-block-bol-p t "If t, detect completion when at
begining of line, otherwise detect completion anywhere.")

(defvar company-org--regexp "<\\([^ ]*\\)")

(defun company-org-block (command &optional arg &rest ignored)
  "Complete org babel languages into source blocks."
  (interactive (list 'interactive))
  (cl-case command
    (interactive (company-begin-backend 'company-org-block))
    (prefix (when (derived-mode-p 'org-mode)
    (candidates (company-org-block--candidates arg))
     (company-org-block--expand arg))))

(defun company-org-block--candidates (prefix)
  "Return a list of org babel languages matching PREFIX."
  (seq-filter (lambda (language)
                (string-prefix-p prefix language))
              ;; Flatten `org-babel-load-languages' and
              ;; `org-structure-template-alist', join, and sort.
                (mapcar #'prin1-to-string
                        (map-keys org-babel-load-languages))
                (map-values org-structure-template-alist)))))

(defun company-org-block--template-p (template)
  (seq-contains (map-values org-structure-template-alist)

(defun company-org-block--expand (insertion)
  "Replace INSERTION with actual source block."
  (delete-region (point) (- (point) (1+ ;; Include "<" in length.
                                     (length insertion))))
  (if (company-org-block--template-p insertion)
      (company-org-block--wrap-point insertion
                                     ;; May be multiple words.
                                     ;; Take the first one.
                                     (nth 0 (split-string insertion)))
    (company-org-block--wrap-point (format "src %s" insertion)

(defun company-org-block--wrap-point (begin end)
  "Wrap point with block using BEGIN and END.  For example:
  (insert (format "#+begin_%s\n" begin))
  (insert (make-string org-edit-src-content-indentation ?\s))
  ;; Saving excursion restores point to location inside code block.
    (insert (format "\n#+end_%s" end))))

(defun company-org-block--grab-symbol-cons ()
  "Return cons with symbol and t whenever prefix of < is found.
For example: \"<e\" -> (\"e\" . t)"
  (when (looking-back (if company-org-block-bol-p
                          (concat "^" company-org--regexp)
    (cons (match-string-no-properties 1) t)))

To use, add the backend enable company-mode in org-mode:

(add-to-list 'company-backends 'company-org-block)
(company-mode +1)


08 November 2019 IRC bookmarks

03 November 2019 A more reusable Emacs shell-command history

Cameron Desautel has a great post on Working Faster in Emacs by Reading the "Future", highlighting M-n's usefulness for inserting minibuffer default values.

Invoking M-n in shell-command's prompt is handy for quickly getting the current buffer's file name. This works great for one-off shell commands like "chmod +x" or "tidy -xml -i -m data.xml". Unfortunately, these commands aren't easily reusable from shell-command's minibuffer history, since it'll keep hardcoded file names.

There's likely existing built-in functionality or a more elaborate package for this, but advising read-shell-command enables us to write more reusable commands like "chmod +x $f" or "tidy -xml -i -m $f". We merely replace $f with (buffer-file-name), and let everything else continue as usual.


(defun ar/adviced-read-shell-command (orig-fun &rest r)
  "Advice around `read-shell-command' to replace $f with buffer file name."
  (let ((command (apply orig-fun r)))
    (if (string-match-p "\\$f" command)
        (replace-regexp-in-string "\\$f"
                                  (or (buffer-file-name)
                                      (user-error "No file file visited to replace $f"))

(advice-add 'read-shell-command

It's worth mentioning that searching minibuffer history is pretty simple when leveraging counsel to fuzzy search (via counsel-minibuffer-history, bound to C-r by default).


On a final note, searching minibuffer history for cache hits is way more useful with richer history content. Be sure to save minibuffer history across Emacs sessions and increase shell-command-history using the built-in savehist-mode.

(use-package savehist
  (savehist-file "~/.emacs.d/savehist")
  (savehist-save-minibuffer-history t)
  (history-length 10000)
  (savehist-mode +1))

20 October 2019 Taiwan travel bookmarks

10 October 2019 Emacs swiper and multiple cursors

Emacs swiper is awesome. I bound swiper-isearch to C-s. Also a big fan of multiple cursors. I use it regularly (it's fun).

I had totally missed Ole's post back in 2015: A simple multiple-cursors extension to swiper. Turns out, swiper has multiple cursors support out of the box (bound to C-7 by default). Yay!

UPDATE: Thanks to irreal's post, please remember to add swiper-mc to mc/cmds-to-run-once list (or things won't work as expected). This typically happens interactively when you invoke C-7 the first time around. Make sure you answer "n" when you see a prompt like:


If you happen to choose "y" by mistake, take a look at ~/.emacs.d/.mc-lists.el to correct it. Remove swiper-mc from mc/cmds-to-run-for-all and add it to mc/cmds-to-run-once. Invoke m-x eval-buffer to reset the values and you're good to go.


08 October 2019 Speeding up gifs with gifsycle

Drop frames and speed gif up with gifsycle (via How to remove every second frame from an animated gif?):

gifsicle -U in.gif `seq -f "#%g" 0 3 398` -O2 -o out.gif

ps. 398 is the total number of frames, which you can get with:

identify in.gif

08 October 2019 Spam blacklisting with Emacs org babel

Some email provider accept regular expressions to blacklist additional spam. My blacklist is long and tedious to update, but hey… Emacs org babel can simplify things here.

It's way easier to maintain a blacklist (with no regex) using an org table.


#+name: spam-entries
| .spammy                |
| |
|    |
|            |

and subsequently use org babel (elisp snippet) to generate the regex.

Regex gen

#+begin_src emacs-lisp :var rows=spam-entries
  (require 'dash)
  (require 's)

  (concat "^"
          (s-join "|"
                  (mapcar (lambda (entry)
                            (setq entry (regexp-quote
                                         (s-trim entry)))
                            (assert (s-present? entry))
                             ;; Blacklist email address: joe@spammer.spammy
                             ((s-contains-p "@" entry)
                              (format "(%s)" entry))
                             ;; Blacklist top-level domain: .spammy
                             ((s-starts-with-p "\\." entry)
                              (format "([^.]*%s)" entry))
                             ;; Blacklist domain: @spammer.spammy
                              (format "(.*@%s)" entry))))
                           (-map (lambda (row)
                                   (nth 0 row))


: ^([^.]*\.spammy)|(dodgyfella@hotmail\.com)|(.*@henryzeespammer\.com)|(.*@yumspam\.com)$

UPDATE: Tweaked elisp and regex (but not animation) also found John Bokma's post: Blacklisting domains with Postfix.


06 October 2019 Rewriting dates with Emacs multiple cursors

Needed to rewrite the date format in a couple of csv columns. Emacs multiple cursors helps here, but needed a function to parse and reformat the dates themselves.

I can likely reformat dates using the built-in parse-time-string and format-time-string functions, but hey why not give the ts.el library a try…

(defun ar/region-to-timestamp ()
  "Convert date like \"29 Apr 2019\" to \"2019-04-29\"."
  (let ((date (ts-parse (buffer-substring
    (delete-region (region-beginning)
    (insert (ts-format "%Y-%m-%d" date))))

Bound the new function to a temporary keybinding, so I can invoke from multiple cursors:

(bind-key "M-q" #'ar/region-to-timestamp)

and voilà!


05 October 2019 Show/hide Emacs dired details in style

Emacs dired is a powerful directory browser/editor. By default, it shows lots of handy file and directory details.


I typically prefer hiding file and directory details until I need them. The built-in dired-hide-details-mode makes this easy with the "(" key toggle. Coupled with Steve Purcell's diredfl (for coloring), it strikes a great user experience.


With a short snippet, you can also show/hide dired details in style:

(use-package dired
  :hook (dired-mode . dired-hide-details-mode)
  ;; Colourful columns.
  (use-package diredfl
    :ensure t
    (diredfl-global-mode 1)))

UPDATE: Thanks to Daniel Martín, who pointed me to dired-git-info. This package adds git logs to dired file and directory details.


Binding dired-git-info-mode to ")" is a nice complement to dired-hide-details-mode's "(" binding.

(use-package dired-git-info
    :ensure t
    :bind (:map dired-mode-map
                (")" . dired-git-info-mode)))

29 September 2019 Bulk buying bookmarks

01 September 2019 Speeding up Emacs tramp via ControlMaster

Via Florian Margaine's Eshell config, I discovered ssh's ControlMaster. It enables sharing multiple sessions over a single network connection. This has the benefit of speeding up Emacs TRAMP.

In your ~/.ssh/config add:

Host *
    ControlPath ~/.ssh/master-%h:%p
    ControlMaster auto
    ControlPersist 10m

01 September 2019 csv bookmarks

10 August 2019 Slovakia travel bookmarks

14 July 2019 Thumbnailing pdf page

If you ever need to thumbnail a pdf page, imagemagick has got you covered. For example, to thumbnail page 3, you can use:

convert path/to/input.pdf[2] path/to/output.png
convert -resize 10000x10000 path/to/input.pdf[2] path/to/output.png
convert: FailedToExecuteCommand `'gs' -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 '-sDEVICE=pngalpha' -dTextAlphaBits=4 -dGraphicsAlphaBits=4 '-r72x72' -dFirstPage=3 -dLastPage=3 '-sOutputFile=/var/folders/2y/nj_s07ms7l5gfsffh89_79zm0000gn/T/magick-30950xzlPsgqGUwtA%d' '-f/var/folders/2y/nj_s07ms7l5gfsffh89_79zm0000gn/T/magick-30950jpGyui82uGOQ' '-f/var/folders/2y/nj_s07ms7l5gfsffh89_79zm0000gn/T/magick-30950cuDVTNjArshs'' (1) @ error/pdf.c/InvokePDFDelegate/292.

However, I had the error above (missing gs), resolved by installing ghostscript.

brew install ghostscript

12 July 2019 Outdoor bookmarks

07 July 2019 gnuplot bookmarks

04 June 2019 gnu global, ctags, and Emacs setup

Universal ctags (newer)

I'm now using universal ctags, as recommended by counsel-etags.

From universal ctag's Building on Mac OS:

brew tap universal-ctags/universal-ctags
brew install --HEAD universal-ctags




--regex-swift=/(var|let)[ \t]+([^:=]+).*$/\2/v/
--regex-swift=/func[ \t]+([^\(\)]+)\([^\(\)]*\)/\1/f/
--regex-swift=/struct[ \t]+([^:\{]+).*$/\1/s/
--regex-swift=/class[ \t]+([^:\{]+).*$/\1/c/
--regex-swift=/protocol[ \t]+([^:\{]+).*$/\1/p/
--regex-swift=/enum[ \t]+([^:\{]+).*$/\1/e/
--regex-swift=/(typealias)[ \t]+([^:=]+).*$/\2/v/

Exuberant ctags (older/buggy?)

Install gnu global (ensure homebrew uses –with-exuberant-ctags flag).

brew install global
brew install ctags
pip install pygments






exuberant-ctags|plugin-example|setting to use Exuberant Ctags plug-in parser:\


pygments-parser|Pygments plug-in parser:\

(use-package counsel-gtags
  :ensure t
  :commands counsel-gtags-mode
  :bind (:map
         ("M-." . counsel-gtags-dwim)
         ("M-," . counsel-gtags-go-backward))
  :hook ((swift-mode . counsel-gtags-mode)
         (swift-mode . ggtags-mode)))

;; Needs .ctags and .globalrc in $HOME.
(use-package ggtags
  :ensure t
  :commands ggtags-mode)

Helpful references

29 May 2019 mu4e as macOS mail composer

Via Using Emacs as Default Mailer on macOS, a tiny script to handle mailto: links.

From /Script Editor, save following script as Application ( From, Preferences -> Default email reader and chosse

on open location myurl
        tell application "Emacs" to activate
        set text item delimiters to {":"}
        do shell script "/path/to/emacsclient --eval '(browse-url-mail \"" & myurl & "\")'"
end open location

26 May 2019 New sudo user snippet

I don't add linux sudoers frequently enough. Always looking it up. Keeping snippet.

adduser -m -d /home/<username> <username>
passwd <username>
usermod -aG sudo <username>

24 May 2019 Plotting ledger reports in org

My ledger file

Save path to my.ledger in ledger-file block.

#+name: ledger-file
#+begin_src emacs-lisp

gnuplot terminal (png or qt)

Select gnuplot terminal. Using png to output images, but qt is handy too for interactive chart inspection.

Use png for inline or qt for interactive
#+name: gnuplot-term
#+begin_src emacs-lisp

Monthly Income and Expenses

Generate income report.

#+name: income-data
#+begin_src bash :results table :noweb yes
  ledger -f <<<ledger-file>>> -j reg ^Income -M --collapse --plot-amount-format="%(format_date(date, \"%Y-%m-%d\")) %(abs(quantity(scrub(display_amount))))\n"

Generate expenses report.

#+name: expenses-data
#+begin_src sh :results table :noweb yes
  ledger -f <<<ledger-file>>> -j reg ^Expenses -M --collapse

Plot income vs expenses.

set terminal myterm size 3500,1500
set style data histogram
set style histogram clustered gap 1
set style fill transparent solid 0.4 noborder
set xtics nomirror scale 0 center
set ytics add ('' 0) scale 0
set border 1
set grid ytics
set title "Monthly Income and Expenses"
set ylabel "Amount"
plot income using 2:xticlabels(strftime('%b', strptime('%Y-%m-%d', strcol(1)))) title "Income" linecolor rgb "light-salmon", '' using 0:2:2 with labels left font "Courier,8" rotate by 15 offset -4,0.5 textcolor linestyle 0 notitle, expenses using 2 title "Expenses" linecolor rgb "light-green", '' using 0:2:2 with labels left font "Courier,8" rotate by 15 offset 0,0.5 textcolor linestyle 0 notitle

21 May 2019 Changing MAC address in org

Via Minko Gechev's tweet. Saving in an org block, just because…

changeMAC() {
    local mac=$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')
    ifconfig en0 ether $mac
    ifconfig en0 down
    ifconfig en0 up
    echo "Your new physical address is $mac"

Your new physical address is aa:36:ee:d2:ee:66

ps. Also see Execute org blocks as root.

17 May 2019 Charting bookmarks

11 May 2019 Building swift-format

Trying out Google's swift-format. Build with:

git clone -b swift-5.2-branch
cd swift-format
swift build
.build/x86_64-apple-macosx/debug/swift-format --help
OVERVIEW: Format or lint Swift source code.

USAGE: swift-format [options] <filename or path> ...

  --configuration         The path to a JSON file containing the configuration of the linter/formatter.
  --in-place, -i          Overwrite the current file when formatting ('format' mode only).
  --mode, -m              The mode to run swift-format in. Either 'format', 'lint', or 'dump-configuration'.
  --recursive, -r         Recursively run on '.swift' files in any provided directories.
  --version, -v           Prints the version and exists
  --help                  Display available options

  filenames or paths      One or more input filenames

UPDATE: Now uses swift-5.2-branch (for Xcode 11.4), according to Matching swift-format to Your Swift Version.

06 May 2019 Ledger query snippets

Expenses paid in cash between two dates

ledger -f my.ledger reg "^Expenses" and expr 'any(account=~/Assets:Cash:Wallet/)' -b 02/19 -e 04/09

Bank account income between two dates

ledger -f my.ledger reg "^Assets:Bank:Acme" and expr "amount > 0" -b 02/19 -e 04/09

Formatting reg output

ledger -f my.ledger reg "^Assets:Bank:Acme" --format="%(payee) %(amount)\n"

04 May 2019 Batch file renaming with counsel, find-dired, and wdired

The first time I saw wdired in action, it blew my mind. wdired makes dired (directory editor) buffers writeable, so you can edit them like any other Emacs buffer. You can subsequently use all your favorite file-editing tricks to rename files (amongst other things). You can see it in action at the end of Emacs Rocks episode 16.

When combining find-dired with wdired, one can easily find matching files and quickly batch rename them using something like multiple cursors or keyboard macros. I've been a fan of the find-dired -> dired-toggle-read-only -> mc/mark-all-like-this workflow for quite some time, but I always wished I could adjust find-dired queries a little quicker by getting immediate feedback.

Completion frontends like ivy and helm are perfect for getting this kind of immediate feedback. Peeking into ivy's counsel source, I borrowed some ideas to glue counsel-style narrowing on a find command, which I can easily translate to a writeable dired buffer for all that joyful-mutiple-cursor-editing experience.


The code for ar/counsel-find is a little rough but can be found at here.

26 April 2019 VPS bookmarks

22 April 2019 Svelte bookmarks

16 April 2019 Mark region, indent, restore location

When I'm not using an automatic code formatter (ie. clang-format, gofmt, etc.), I often find myself using Emacs region marking commands like mark-defun, er/expand-region, and mark-whole-buffer prior to pressing <tab>, which is bound to indent-for-tab-command.

This is all working as expected: the selection gets indented and the point is left in the current location.

Say we have the following snippet we'd like to indent.


Mark region with C-M-h (mark-defun)


Indent with <tab> (indent-for-tab-command)


We're done. The selected function is now indented as expected.

But… I always wished the point returned to the location prior to initiating the region-marking command, in this case mark-defun.

In short, I wish the point had ended in the following location.


I'm not aware of an existing package that helps with this, so here's a tiny minor mode (divert-mode) to help with restoring point location after indenting a region. The diverted-events variable can be used to track specific region selecting commands and associate breadcrumb functions to replace the point location as needed.

;;; diverted.el --- Identify temporary diversions and automatically
;;; move point back to original location.

;;; Commentary:
;; Automatically come back to a original location prior to diversion.

;;; Code:

(require 'cl)
(require 'seq)

(defstruct diverted-event
  from ;; Initial function (eg. 'mark-defun)
  to ;; Follow-up function (eg. 'indent-for-tab-command)

(defvar diverted-events
   (make-diverted-event :from 'mark-defun
                        :to 'indent-for-tab-command
                        :breadcrumb (lambda ()
                                      (diverted--pop-to-mark-command 2)))
   (make-diverted-event :from 'er/expand-region
                        :to 'indent-for-tab-command
                        :breadcrumb (lambda ()
                                      (diverted--pop-to-mark-command 2)))
   (make-diverted-event :from 'mark-whole-buffer
                        :to 'indent-for-tab-command
                        :breadcrumb (lambda ()
                                      (diverted--pop-to-mark-command 2))))
  "Diversion events to look for.")

(defun diverted--resolve (symbol)
  "Resolve SYMBOL to event."
  (seq-find (lambda (event)
              (equal symbol
                     (diverted-event-from event)))

(defun diverted--pop-to-mark-command (n)
  "Invoke `pop-to-mark-command' N number of times."
  (dotimes (_ n)

(defun diverted--advice-fun (orig-fun &rest r)
  "Get back to location prior to diversion using advice around `diverted-events' (ORIG-FUN and R)."
  (let ((recognized-event (diverted--resolve last-command)))
    (when recognized-event
      (funcall (diverted-event-breadcrumb recognized-event))
      (message "Breadcrumbed prior to `%s'"
               (diverted-event-from recognized-event)))))

(defun diverted-mode-enable ()
  "Enable diverted-mode."
  (mapc (lambda (event)
          (advice-add (diverted-event-to event)
          (message "Looking for `%s' after `%s' diversions."
                   (diverted-event-to event)
                   (diverted-event-from event)))
  (message "diverted-mode enabled"))

(defun diverted-mode-disable ()
  "Disable diverted-mode."
  (mapc (lambda (event)
          (advice-remove (diverted-event-to event)
          (message "Ignoring `%s' after `%s' diversions."
                   (diverted-event-to event)
                   (diverted-event-from event)))
  (message "diverted-mode disabled"))

(define-minor-mode diverted-mode
  "Detect temporary diversions and restore point location."
  :init-value nil
  :lighter " diverted"
  :global t
  (if diverted-mode

(provide 'diverted)

;;; diverted.el ends here

UPDATE(2019-04-20): Source on github.

14 April 2019 Wider web bookmarks

14 April 2019 Compound interest calculations

Saving Tony Bedford's python snippets for calculating compound interest. Really just an excuse to fire up Emacs and play with org babel.

t = 20 # years
r = 0.07 # rate
pv = 200000.00 # present value
fv = pv * (1+r)**t # future value
print("Pension of %.2f at %d%% will be worth %.2f in %d years" % (pv, 100 * r, fv, t))
Pension of 200000.00 at 7% will be worth 773936.89 in 20 years
t = 20 # years
r = 0.07 # rate
pv = 200000.00 # present value
n = 1
fv = pv * (1 + r/n)**(n*t) # future value
print ("First formula calculates final value to: %.2f" % fv)

fv = pv * (1 + r/n)**(n*1) # year 1 only
print("Year %d: %.2f" % (1, fv))
for i in range (2, t+1):
    fv = fv * (1 + r/n)**(n*1) # Calculate one year at a time
    print("Year %d: %.2f" % (i, fv))
First formula calculates final value to: 773936.89
Year 1: 214000.00
Year 2: 228980.00
Year 3: 245008.60
Year 4: 262159.20
Year 5: 280510.35
Year 6: 300146.07
Year 7: 321156.30
Year 8: 343637.24
Year 9: 367691.84
Year 10: 393430.27
Year 11: 420970.39
Year 12: 450438.32
Year 13: 481969.00
Year 14: 515706.83
Year 15: 551806.31
Year 16: 590432.75
Year 17: 631763.04
Year 18: 675986.46
Year 19: 723305.51
Year 20: 773936.89

11 April 2019 Building mu/mu4e on macOS

I've now built Emacs's mu/mu4e releases a handful of times on macOS. These are the steps, so I don't forget.


Updated steps for building mu/mu4e 1.4:

brew install gmime
export CPPFLAGS="-I$(brew --prefix)/Cellar/gmime/3.2.3/include -I$(brew --prefix)/include"
export LDFLAGS=-L$(brew --prefix)/Cellar/gmime/3.2.3/lib
export PKG_CONFIG_PATH=$(brew --prefix)/Cellar/gmime/3.2.3/lib/pkgconfig:$(brew --prefix)/opt/libffi/lib/pkgconfig
export EMACS=/Applications/
./configure --prefix=$(~/local)
make install


Recently built Emacs's mu/mu4e 1.2.0 from source on macOS. Steps:

brew install gmime
export CPPFLAGS=-I$(brew --prefix)/Cellar/gmime/3.2.3/include
export LDFLAGS=-L$(brew --prefix)/Cellar/gmime/3.2.3/lib
export PKG_CONFIG_PATH=$(brew --prefix)/Cellar/gmime/3.2.3/lib/pkgconfig:$(brew --prefix)/opt/libffi/lib/pkgconfig
./configure --prefix=$(~/local) --disable-dependency-tracking
make install

UPDATE(2019-04-16): Another approach at Irreal's Mu/mu4e 1.2 Available.

30 March 2019 Reading spreadsheets with python/pandas

Via Daily python tip, a snippet to read xls files in python. This will come in handy. Saving for future.

Get set up with:

pip install pandas
pip install xlrd

Read with:

import pandas
xlf = pandas.ExcelFile("sheet.xlsx")
print xlf.sheet_names
[u'my sheet']

17 March 2019 Inserting numbers with Emacs multiple cursors

TIL that multiple cursor's mc/insert-numbers enables you to quickly enter increasing numbers for each cursor. I have mc/insert-numbers bound to # in region-bindings-mode-map. By default, sequence starts at 0, but invoking mc/insert-numbers with prefix enables you to quickly change that.

Came in handy when numbering an org table:


17 March 2019 Brazil travel bookmarks

17 March 2019 Bath travel bookmarks

17 March 2019 Half marathon training


Starting from week 4:

Week Monday Tuesday Wednesday Thursday Friday Saturday Sunday
4 Rest 40 mins easy 30 mins tempo Rest 40 mins cross Rest (03/24) 60 mins
    6.7 km 5.1 Km   -   -
    41:51 m 30:00 m        
    61.3 Kg 60.8 Kg        
5 Rest 40 mins easy 30 mins tempo Rest 40 mins interval Rest (03/31) 11 Km
    11.9 Km -   5.99 Km   11.0 Km
    80:00 m     40 m   60:08 m
6 Rest 40 mins easy 30 mins tempo Rest 40 mins interval/cross Rest (04/07) 13 Km
7 Rest 40 mins easy 30 mins tempo Rest 40 mins interval Rest (04/14) 60 mins
8 Rest 40 mins easy 30 mins tempo Rest 50 mins interval/cross Rest (04/21) 16 Km
9 Rest 40 mins easy 30 mins tempo Rest 50 mins interval Rest (04/28) 8 Km
10 Rest 40 mins easy 30 mins tempo Rest 40 mins interval/cross Rest (05/05) 19 Km
11 Rest 40 mins easy 30 mins tempo Rest 40 mins interval Rest (05/12) 10 Km
12 Rest 40 mins easy 30 mins tempo Rest 50 mins easy Rest (05/19) Race

16 March 2019 No Emacs frame refocus on macOS

This one's been bugging me for a while. On macOS, Emacs automatically focuses (raises) other frames when one is closed.


This has the unfortunate side-effect that I could be moved from one macOS desktop/space to another when closing an Emacs frame.

Finally managed do something about it. Since I install Emacs on macOS via homebrew, a small patch on emacs-plus recipe small patch on emacs-plus recipe did the job.


UPDATE: Pull request merged in d12frosted/emacs-plus.

The patch patch has been merged into d12frosted/homebrew-emacs-plus. To use:

brew tap d12frosted/emacs-plus
brew install emacs-plus --without-spacemacs-icon --with-no-frame-refocus

Balance restored.

16 March 2019 Checksums on linux/macOS


md5 file


shasum -a 1 file


shasum -a 256 file

12 March 2019 Language server protocol (LSP) bookmarks

24 February 2019 Copy from desktop to mobile via QR code

Marcin Borkowski has a nice tip to quickly copy text or URLs between desktop and mobile using QR codes.

Wrote a little elisp to do a similar thing using the clipboard via Emacs:

(defun ar/misc-clipboard-to-qr ()
  "Convert text in clipboard to qrcode and display within Emacs."
  (let ((temp-file (concat (temporary-file-directory) "qr-code")))
    (if (eq 0 (shell-command (format "qrencode -s10 -o %s %s"
                                     (shell-quote-argument (current-kill 0)))
        (switch-to-buffer (find-file-noselect temp-file t))
      (error "Error: Could not create qrcode, check *qrencode* buffer"))))


ps. Encoding your WiFi access point password into a QR code shows how to encode WiFi access point passwords:

qrencode -o wifi.png "WIFI:T:WPA;S:<SSID>;P:<PASSWORD>;;"

More comprehensively:

pwgen -s 63 > 00wifi.txt
qrencode -o 00wifi.png "WIFI:T:WPA;S:${SSID};P:$(cat 00wifi.txt);;"

19 February 2019 Parsing dates in Go

Ensure the reference time ("Mon Jan 2 15:04:05 -0700 MST 2006") is used in layout string.

For example:

package main

import (

func main() {
        goodLayout := "January 2 2006"
        if t, err := time.Parse(goodLayout, "March 10 2019"); err != nil {
                    fmt.Printf("%s\n", err)
        } else {
                    fmt.Printf("%v\n", t)

        badLayout := "January 2 2009"
        if t, err := time.Parse(badLayout, "March 10 2019"); err != nil {
                    fmt.Printf("%s\n", err)
        } else {
                    fmt.Printf("%v\n", t)
2019-03-10 00:00:00 +0000 UTC
parsing time "March 10 2019" as "January 2 2009": cannot parse "19" as "009"

13 February 2019 Life in the UK bookmarks

10 February 2019 C language bookmarks

10 February 2019 Video editing bookmarks

10 February 2019 Icons bookmarks

27 January 2019 Salt beef recipe

How to make salt beef (use 1.8kg brisket instead) and brining a brisket (celery and peppercorns) both from The Guardian were recommended by a friend.

27 January 2019 Geneva travel bookmarks

13 January 2019 Swapping Emacs ivy collections/sources

Ivy is great. I've been meaning to figure out a way to swap sources while running ivy. This would enable me to cycle through different sources using the existing search parameters.

At first look, 'ivy-set-sources seemed like the right choice, but it's used during setup to agregate sources. Subsequent 'ivy-set-sources calls are ignored during an 'ivy-read session.

There's an ivy feature request over at github with a similar goal in mind. Although the feature is not yet supported, there's a handy suggestion to use 'ivy-quit-and-run to quit the current command and run a different one.

With 'ivy-quit-and-run in mind, we can write our 'ar/ivy-read function to take a list of sources and add a little logic to cycle through them using a keybiding, in my case <left> and <right>.

;;; -*- lexical-binding: t; -*-

(require 'cl)


(cl-defun ar/ivy-read (sources &key index initial-input)
  (let ((kmap (make-sparse-keymap))
    (cl-assert (> (length sources) 0))
    (when (null index) (setq index 0))
    (setq source (nth index sources))
    (define-key kmap (kbd "<right>") (lambda ()
                                       (ivy-quit-and-run (ar/ivy-read sources
                                                                      :index (if (>= (1+ index)
                                                                                     (length sources))
                                                                               (1+ index))
                                                                      :initial-input ivy-text))))
    (define-key kmap (kbd "<left>") (lambda ()
                                      (ivy-quit-and-run (ar/ivy-read sources
                                                                     :index (if (< (1- index)
                                                                                (1- (length sources))
                                                                              (1- index))
                                                                     :initial-input ivy-text))))
    (ivy-read (ar/ivy-source-prompt source)
              (ar/ivy-source-collection source)
              :action (ar/ivy-source-action source)
              :initial-input initial-input
              :keymap kmap)))

(defun ar/ivy-food-menu ()
  (ar/ivy-read (list
                (make-ar/ivy-source :prompt "Pizza: "
                                    :action (lambda (selection)
                                              (message "Selected pizza: %s" selection))
                                    :collection (lambda (str pred v)
                                                  (list "Bianca Neve - Mozzarella, Ricotta, Sausage, Extra Virgin Olive Oil, Basil"
                                                        "Boscaiola - Mozzarella, Tomato Sauce, Sausage, Mushrooms, Extra Virgin Olive Oil, Basil"
                                                        "Calzone - Ricotta, Ham, Mushrooms, Artichokes. Topped with Tomato Sauce and Extra Virgin Olive Oil."
                                                        "Capricciosa - Mozzarella,Tomato Sauce, Prosciutto Cotto Ham, Mushrooms, Artichokes, Extra Virgin Olive Oil."
                                                        "Carciofi - Mozzarella, Tomato Sauce, Artichokes, Extra Virgin Olive Oil, Basil."
                                                        "Diavola - Mozzarella, Tomato Sauce, Spicy Salami, Extra Virgin Olive Oil, Basil."
                                                        "Funghi - Mozzarella, Tomato Sauce, Mushrooms, Extra Virgin Olive Oil, Basil.")))
                (make-ar/ivy-source :prompt "Tacos: "
                                    :action (lambda (selection)
                                              (message "Selected taco: %s" selection))
                                    :collection (lambda (str pred v)
                                                  (list "Pork pibil - Slow cooked in citrus & spices, with pink pickled onions."
                                                        "Grilled chicken & avocado - Ancho rub, guacamole & green tomatillo salsa."
                                                        "Plantain - Sweet & spicy chipotle & crumbled feta."
                                                        "Poblano pepper - Caramelised onions, corn & cashew nut mole."
                                                        "Buttermilk chicken - Served crispy fried with habanero & white onion relish & spiced mayo."
                                                        "Sustainable battered cod - mSC certified cod with shredded slaw, chipotle mayo & pickled cucumber."
                                                        "Chargrilled steak - Avocado & chipotle salsas.")))
                (make-ar/ivy-source :prompt "Burgers: "
                                    :action (lambda (selection)
                                              (message "Selected burger: %s" selection))
                                    :collection (lambda (str pred v)
                                                  (list "The cheese - Aged beef patty with american cheese, gherkins, ketchup & mustard."
                                                        "The yeah! - Aged beef patty with american cheese, gherkins, yeah! sauce & salad."
                                                        "The yfc or hot yfc - Crispy chicken with lime or chipotle crema, lettuce, pickled onion & slaw."
                                                        "The rancher - Grilled chicken with ranch dressing, bacon & salad."
                                                        "The bubbah - Aged beef patty with smokey aubergine, pickled red cabbage, lettuce, roast toms, onions & cheddar."
                                                        "The bulgogi - Sesame-spiced beef patty with miso mayo, pickled radish, onion, cucumber & spring onion."
                                                        "The summer - Aged beef patty with sriracha mayo, lettuce, onion, toms, avo, cheddar & bacon."))))))


ps. Menu data from Star of Kings, Wahaca, and Pizzarino.

12 January 2019 Podcast bookmarks

12 January 2019 Emacs on macOS Mojave

Had issues running Emacs on macOS Mojave (blank unresponsive screen). Bleeding edge emacs-plus did the job:

brew tap d12frosted/emacs-plus
brew install emacs-plus --without-spacemacs-icon --HEAD
brew info emacs-plus
d12frosted/emacs-plus/emacs-plus: stable 26.1, devel 26.1-rc1, HEAD
GNU Emacs text editor
/Users/some-user/homebrew/Cellar/emacs-plus/HEAD-8fe21b0 (3,985 files, 123.0MB) *
  Built from source on 2019-01-12 at 09:26:09 with: --without-spacemacs-icon
==> Dependencies
Build: pkg-config
Recommended: little-cms2, gnutls, librsvg, imagemagick@6
Optional: dbus, mailutils
==> Requirements
Optional: x11
==> Options
	Don't remove the ctags executable that Emacs provides
	Build with dbus support
	Using Emacs icon project EmacsIcon1
	Using Emacs icon project EmacsIcon2
	Using Emacs icon project EmacsIcon3
	Using Emacs icon project EmacsIcon4
	Using Emacs icon project EmacsIcon5
	Using Emacs icon project EmacsIcon6
	Using Emacs icon project EmacsIcon7
	Using Emacs icon project EmacsIcon8
	Using Emacs icon project EmacsIcon9
	Using Emacs icon project emacs-card-blue-deep
	Using Emacs icon project emacs-card-british-racing-green
	Using Emacs icon project emacs-card-carmine
	Using Emacs icon project emacs-card-green
	Build with mailutils support
	Using a modern style Emacs icon by @tpanum
	Experimental: build without titlebar
	Experimental: build from pdumper branch and with
         increasedremembered_data size (--HEAD only)
	Experimental: build with x11 support
	Experimental: build with xwidgets support (--HEAD only)
	Build a non-Cocoa version of Emacs
	Build without gnutls support
	Build without imagemagick@6 support
	Build without librsvg support
	Build without libxml2 support
	Build without little-cms2 support
	Build without dynamic modules support
	Build without a patch that enables multicolor font support
	Build without Spacemacs icon by Nasser Alshammari
	Install development version 26.1-rc1
	Install HEAD version
==> Caveats was installed to:

To link the application to default Homebrew App location:
  brew linkapps
  ln -s /Users/some-user/homebrew/Cellar/emacs-plus/26.1/ /Applications

--natural-title-bar option was removed from this formula, in order to
  duplicate its effect add following line to your init.el file
  (add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
  (add-to-list 'default-frame-alist '(ns-appearance . dark))
  (add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
  (add-to-list 'default-frame-alist '(ns-appearance . light))

If you are using macOS Mojave, please note that most of the experimental
options are forbidden on Mojave. This is temporary decision.

To have launchd start d12frosted/emacs-plus/emacs-plus now and restart at login:
  brew services start d12frosted/emacs-plus/emacs-plus
Or, if you don't want/need a background service you can just run:

06 January 2019 Trying out Emacs pdf tools

Late to the party, giving pdf-tools a try.

The macOS install instructions have a prerequisite:

brew install poppler automake

Installed with:

(use-package pdf-tools
  :ensure t
  :mode ("\\.pdf\\'" . pdf-view-mode)
  (setq-default pdf-view-display-size 'fit-page)
  (setq pdf-annot-activate-created-annotations t))


ps. (pdf-tools-install) may not find libffi on macOS. Try:

          (nth 0
                (shell-command-to-string "brew --prefix"))))
         "Cellar" "libffi" "3.2.1" "lib" "pkgconfig"))

27 December 2018 ASCII art generator bookmarks

26 December 2018 Osaka travel bookmarks

25 December 2018 Using OCR to create searchable pdfs from images

Used my phone to take a handful of photos of an article from a magazine. Wanted to convert the images to a searchable pdf on macOS.

This was straightforward, having already installed tesseract.

for i in IMG_3*.jpg; do echo $i; tesseract $i $(basename $i .tif) pdf; done

Should now have a handful of OCR'd pdfs:

ls *.jpg.pdf

Finally, join all pdfs into one. Turns out macOS has a handy python script already installed. We can use it as:

/usr/bin/python "/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/" -o joined.pdf IMG_*pdf

ps. pdfgrep is great for searching pdfs.

25 December 2018 Audiobook providers bookmarks

25 December 2018 Cookbook bookmarks

25 December 2018 Emailing pdfs to kindle from mu4e

Wanted to send a pdf to my kindle for some holiday reading. You can easily do this by emailing the pdf to your kindle-bound email address.

Now, I typically attach files when composing mu4e emails by using mml-attach-file, which attaches the file using <#part>…<#/part>. However, the Amazon service did not find the attached pdf, so no pdf was added to my Kindle.

Fortunately, I found a handy Reddit thread, leding me to a working solution. Wrapping the part using <#multipart type=mixed>…<#/multipart> did the job, using mml-insert-multipart, followed by mml-attach-file.

Resulting attachment should look something like:

<#multipart type=mixed>
<#part type="application/pdf" filename="/path/to/file.pdf" disposition=attachment>

I should add a convenience elisp function for this, but that's for another time…

21 December 2018 org tip: convert csv to table

Needed to import some csv data to an org table. Turns out org's got you covered out of the box with M-x org-table-create-or-convert-from-region bound to C-c |.


20 December 2018 Sponsoring platform bookmarks

20 December 2018 Artistic/creative bookmarks

20 December 2018 Marketing bookmarks

19 December 2018 Bluetooth low energy (BLE) bookmarks

18 December 2018 Fun project bookmarks

14 December 2018 Snowboarding bookmarks

11 December 2018 Scam bookmarks

11 December 2018 Passive income bookmarks

08 December 2018 DWIM ivy quit

"Do-what-I-mean" (DWIM) functions enable us to introduce new Emacs powers to existing workflows without incurring the typical cost of remembering multiple related functions or introducing yet another key binding. DWIM functions invoke other functions, based on current context.

I wanted a small tweak in Ivy's `minibuffer-keyboard-quit' invocation, commonly invoked via C-g key binding:

  1. If we have text selected in minibuffer, deselect it.
  2. If we have any text in minibuffer, clear it.
  3. If no text in minibuffer, quit.

Added `ar/ivy-keyboard-quit-dwim' for this purpose. Binding it to C-g in ivy-minibuffer-map:

(use-package ivy
  :ensure t
  :bind (:map ivy-minibuffer-map
              ("C-g" . ar/ivy-keyboard-quit-dwim))
  (defun ar/ivy-keyboard-quit-dwim ()
    "If region active, deactivate. If there's content, clear the minibuffer. Otherwise quit."
    (cond ((and delete-selection-mode (region-active-p))
           (setq deactivate-mark t))
          ((> (length ivy-text) 0)


05 December 2018 Diffing directories content size

Needed to diff two directories, but only interested in file size changes. diff, find, sort, and stat seem to do the job:

diff <(find dir1 -type f -exec stat -f '%N %z' '{}' \; | sort) <(find dir2 -type f -exec stat -f '%N %z' '{}' \; | sort)
< dir1/one.txt 14
< dir1/subdir/file.txt 5
< dir1/three.txt 7
> dir2/one.txt 19
> dir2/two.txt 0

Note: Using diff, find, sort, and stat on macOS.

Update 1

I've since learned about mtree (thanks Roman!). A nice utility to add to the toolbox.

mtree -p emacs-25.1 -c -k size -d
#	   user: me
#	machine: my-machine
#	   tree: /path/to/emacs-25.1
#	   date: Wed Dec  5 22:21:07 2018
# .
/set type=dir
.               size=1152
# ./admin
admin           size=960
# ./admin/charsets
charsets        size=544
# ./admin/charsets/glibc
glibc           size=3392
# ./admin/charsets/glibc
# ./admin/charsets/mapfiles
mapfiles        size=640
# ./admin/charsets/mapfiles

Update 2

I've added Emacs ediff to the mix:

(require 'f)

(defun ar/ediff-dir-content-size ()
    "Diff all subdirectories (sizes only) in two directories."
    (let* ((dir1-path (read-directory-name "Dir 1: "))
           (dir2-path (read-directory-name "Dir 2: "))
           (buf1 (get-buffer-create (format "*Dir 1 (%s)*" (f-base dir1-path))))
           (buf2 (get-buffer-create (format "*Dir 2 (%s)*" (f-base dir2-path)))))
      (with-current-buffer buf1
      (with-current-buffer buf2
      (shell-command (format "cd %s; find . -type d | sort | du -h" dir1-path) buf1)
      (shell-command (format "cd %s; find . -type d | sort | du -h" dir2-path) buf2)
      (ediff-buffers buf1 buf2)))


02 December 2018 Swift nil-coalescing operator

Paul Hudson, over at Hacking with Swift, has written The Complete Guide to Optionals in Swift. One of the many highlights is the nil-coalescing operator. If you're a fan of the C-like syntax in ternary operations, you'd enjoy chaining with Swift's nil-coalescing operator:

let players = [ "goose": "run!" ]
let move = players["duck1"] ?? players["duck2"] ?? players["duck3"] ?? players["goose"]
print("\(String(describing: move))")

ps. Swift snippet run on Emacs org babel's ob-swift. See Multiline Swift strings for details.

01 December 2018 Ocado vs Asda (org table)

Someone handed me an Ocado shopping voucher for 30% off. Sounded promising, even for a one-off.

With my Money or Your Life hat on, I took a closer look for potential savings. Results were disappointing, when compared to alternatives like Asda.

Here's a table comparing Ocado (30% off) and Asda (no discount):

  Ocado Asda
Coconut Merchant Organic Raw Extra Virgin Coconut Oil 500ml 6.74  
KTC 100% pure coconut oil   2.00
Waitrose Love Life Popcorn Maize 510g 1.50  
Cypressa Popping Corn 2x500g = 1000g   1.50
Whitworths Ground Almonds 2.00  
Whitworths Ground Almonds   1.60
Total   £ 5.10
-30% £ 7.17  

On the upside, Ocado has plenty of items I cannot find at Asda. May be a good opportunity to get these items at a discount.

Emacs org tables

Small tables are the perfect use-case for Emacs org-mode tables. Been a while since I used one, so great timing for a little refresh.

Here's the org source for the table above (prior to exporting to HTML):

|                                                             |  Ocado |   Asda |
| Coconut Merchant Organic Raw Extra Virgin Coconut Oil 500ml |   6.74 |        |
| KTC 100% pure coconut oil                                   |        |   2.00 |
| Waitrose Love Life Popcorn Maize 510g                       |   1.50 |        |
| Cypressa Popping Corn 2x500g = 1000g                        |        |   1.50 |
| Whitworths Ground Almonds                                   |   2.00 |        |
| Whitworths Ground Almonds                                   |        |   1.60 |
| Total                                                       |        | £ 5.10 |
| -30%                                                        | £ 7.17 |        |
#+TBLFM: @8$3=vsum(@2$3..@7$3);£ %.2f::@9$2=vsum(@2$2..@7$2) * 0.7;£ %.2f

24 November 2018 Execute org blocks as root

Been saving admin code snippets in my own org source blocks, some requiring root access. Handy for keeping tiny self-documented scripts to easily bootstrap other machines. TIL org source block's :dir argument can be used to run block as root by using tramp syntax: :dir /sudo::

As user:


: user

As root:

#+BEGIN_SRC sh :dir /sudo::

: root

23 November 2018 Inline Swift computed properties

Via and Max Howell's retweet, TIL about Swift's inline computed properties. Another one to try on Org Babel. ‏

func greetWorld() {
 var message = "hello"
 var betterMessage: String {
   return "\(message) world"

hello world

23 November 2018 Multiline Swift strings

Paul Hudson's tweet introduced me to Swift's multiline string indentation control using closing quotes. Neat!

Being an org-mode fan, I thought I'd give Swift multiline strings a try using Org Babel's ob-swift. I get to verify it and document at the same time. Win.

Swift org mode source blocks (ie. BEGIN_SRC/END_SRC) can be added as follows:

#+BEGIN_SRC swift :exports both
       Hello World

       Hello World

:      Hello World
: Hello World

By pressing C-c C-c anywhere in the code block, the snippet is executed and its output captured in the RESULT block. Super handy for quickly trying out snippets and keeping as future reference.

As a bonus, the above blocks can be exported to HTML (amongst other formats). With some styling, it looks as follows:

     Hello World

     Hello World
     Hello World
Hello World

17 November 2018 Quickly swapping elfeed filters

I seem to be more efficient in getting through rss feeds by individually browsing through related content. That is, I can get through all Emacs entries a lot faster if I look at Emacs content exclusively, instead of mixing with say BBC news. Elfeed filters are great for filtering related content.

I wanted a way to easily switch through my typical categories of related content by quickly changing elfeed filters using a completion framework.

Emacs's completing-read plays nicely with your favorite completing framework (mine is ivy). With a couple of functions, we can get Emacs to ask us for the filtering category using human-readable options and quickly presenting related content. Binding the new functionality to <tab> is working well for me.

(use-package elfeed :ensure t
  :commands elfeed
  :bind (:map elfeed-search-mode-map
              ("<tab>" . ar/elfeed-completing-filter))
  (defun ar/elfeed-filter-results-count (search-filter)
    "Count results for SEARCH-FILTER."
    (let* ((filter (elfeed-search-parse-filter search-filter))
           (head (list nil))
           (tail head)
           (count 0))
      (let ((lexical-binding t)
            (func (byte-compile (elfeed-search-compile-filter filter))))
        (with-elfeed-db-visit (entry feed)
          (when (funcall func entry feed count)
            (setf (cdr tail) (list entry)
                  tail (cdr tail)
                  count (1+ count)))))

  (defun ar/elfeed-completing-filter ()
    "Completing filter."
    (let ((categories (-filter
                       (lambda (item)
                         (> (ar/elfeed-filter-results-count (cdr item))
                       '(("All" . "@6-months-ago +unread")
                         ("BBC" . "@6-months-ago +unread +bbc")
                         ("Dev" . "@6-months-ago +unread +dev")
                         ("Emacs" . "@6-months-ago +unread +emacs")
                         ("Health" . "@6-months-ago +unread +health")
                         ("Hacker News" . "@6-months-ago +unread +hackernews")
                         ("iOS" . "@6-months-ago +unread +ios")
                         ("Money" . "@6-months-ago +unread +money")))))
      (if (> (length categories) 0)
            (ar/elfeed-view-filtered (cdr (assoc (completing-read "Categories: " categories)
            (goto-char (window-start)))
        (message "All caught up \\o/")))))


We don't actually need two functions, but ar/elfeed-filter-results-count enables us to list only those feeds that actually have new content. The list will shrink as we get through our content. When no content is left, we get a little celebratory message.


14 November 2018 Converting docx to pdf on macOS

Wanted to convert a docx document to pdf on macOS. Pandoc to the rescue, but first needed pdflatex installed:

pandoc -t latex some.docx -o some.pdf
pdflatex not found. Please select a different --pdf-engine or install pdflatex

Installed pdflatex on macOS with:

brew install mactex

Can also use HTML5. Install wkhtmltopdf with:

brew install Caskroom/cask/wkhtmltopdf

Convert with:

pandoc -t html5 some.docx -o some.pdf

13 November 2018 Faster elfeed browsing with paging

Following up from faster junk mail deletion with mu4e, elfeed is another candidate for enabling actions on pages. In this case, marking rss entries as read, page by Page.

If on use-package, the function can defined and bound to the "v" key using:

(use-package elfeed
  :ensure t
  :bind (:map elfeed-search-mode-map
              ("v" . ar/elfeed-mark-visible-as-read))
  (defun ar/elfeed-mark-visible-as-read ()
    (require 'window-end-visible)
    (set-mark (window-start))
    (goto-char (window-end-visible))
    (goto-char (window-start))))


10 November 2018 Faster junk mail deletion with mu4e

It's been roughly 5 months since my mu4e email migration. Happy with my choice. Mu4e is awesome.

I now have 4 email accounts managed by mu4e, and unfortunately receiving lots of junk mail.

I regularly peek at junk folders for false positives and delete junk email permanently. I've been wanting a quick way to glance at junk mail and easily delete page by page.

Deleting emails page by page is not supported in mu4e by default. Fortunately, this is Emacs and we can change that™.

There's a handy package by Roland Walker called window-end-visible. We can use it to select mu4e emails by page and subsequently glue it all together to enable deleting emails by page.

(require 'mu4e)
(require 'window-end-visible)

(defun ar/mu4e-delete-page ()
  (set-mark (window-start))
  (goto-char (window-end-visible))
  (mu4e-mark-execute-all t)
  (goto-char (window-start)))

I'm a use-package fan, so I use it to bind the "v" key to delete visible emails (by page).

(use-package mu4e
  :bind (:map mu4e-headers-mode-map
         ("v" . ar/mu4e-delete-page))


06 November 2018 Working with vultr's ipv6-only instances

Having recently read Your Money or Your Life, I've been cutting down on personal expenses wherever possible. Specially recurring expenses which include monthly charges from VPS hosting. Let's reduce those charges…

My VPS needs are fairly small (mostly hobby and tinkering). Vultr† has a plan for $2.50/month (not seen anything cheaper). The caveat for the price, you get ipv6 access only (ie. 0000:1111:2222:3333:4444:5555:6666:7777:8888).

So far so good, but my ISP doesn't yet support ipv6:

$ ping6 0000:1111:2222:3333:4444:5555:6666:7777:8888
$ ping6: UDP connect: No route to host

Fortunately, we can still work with ipv6 by using a tunnel (TIL about Hurricane Electric's tunnel broker). After signing up and creating a tunnel, they conveniently show you "Example Configurations" from the "Tunnel Details" menu. In my case, macOS:

ifconfig gif0 create
ifconfig gif0 tunnel <ipv4 client broker IP or DCHP internal IP> <ipv4 server IP>
ifconfig gif0 inet6 <ipv6 client broker IP> <ipv6 server IP> prefixlen 128
route -n add -inet6 default <ipv6 server IP>

Note: If behind router, use the DHCP internal IP.

After configuring with ifconfig, all is good. Yay!

$ ping6 0000:1111:2222:3333:4444:5555:6666:7777:8888
PING6(56=40+8+8 bytes) 2001:111:22:aaa::2 --> 0000:1111:2222:3333:4444:5555:6666:7777:8888
16 bytes from 0000:1111:2222:3333:4444:5555:6666:7777:8888, icmp_seq=0 hlim=52 time=270.019 ms
16 bytes from 0000:1111:2222:3333:4444:5555:6666:7777:8888, icmp_seq=1 hlim=52 time=290.834 ms
16 bytes from 0000:1111:2222:3333:4444:5555:6666:7777:8888, icmp_seq=2 hlim=52 time=311.960 ms
16 bytes from 0000:1111:2222:3333:4444:5555:6666:7777:8888, icmp_seq=3 hlim=52 time=330.902 ms

I'm an ipv6 noob. I mostly need ssh access. My typical usages need small tweaks.

For ssh:

ssh -6 username@0000:1111:2222:3333:4444:5555:6666:7777:8888

For scp:

scp -6 file.txt username@\[0000:1111:2222:3333:4444:5555:6666:7777:8888\]:/remote/dir/

† I get $10 credit if you use this affiliate link. Thank you.

04 November 2018 Shaving bookmarks

04 November 2018 Buy it for life bookmarks

29 October 2018 Rust bookmarks

28 October 2018 Fonts bookmarks

17 October 2018 imenu on Emacs eshell

imenu navigation is one of those Emacs gems I didn't discover until much later on. It does what you'd expect in all types of modes. In rare instances, I've found specific modes missing imenu support. Fortunately, this is Emacs and you can fix that.

Eshell has a handy feature to jump back and forth over previous prompts using M-x eshell-previous-prompt (C-c C-p) and M-x eshell-next-prompt (C-c C-n). Upon learning about these two functions, my immediate reaction was to try imenu. Surprisingly, it didn't "just work\n", but a tiny bit of elisp brought balance back to the Emacs universe.

In an eshell mode hook function, one can set the imenu-generic-expression to help it find your favorite prompt:

(setq-local imenu-generic-expression
                  '(("Prompt" " $ \\(.*\\)" 1)))

Ah it's the little things…


ps. If wondering why my imenu experience looks a little different, that's because I'm using Abo Abo's wonderful counsel and M-x counsel-semantic-or-imenu.

14 October 2018 Encrypted disk image on macOS



13 October 2018 Sheffield travel bookmarks

13 October 2018 Headsphones bookmarks

05 October 2018 macOS app bookmarks

30 September 2018 Gaming bookmarks

29 September 2018 Lua bookmarks

29 September 2018 Skin product bookmarks

29 September 2018 Sustainability bookmarks

29 September 2018 Investment platform bookmarks

28 September 2018 Minimalist bookmarks

23 September 2018 Recover from Time Machine's "backup already in use"

Started seeing "backup already in use" error from my daily Time Machine backups, against my Synology. Disabling and re-enabling AFP did the job (via Synology -> Control Panel -> Files Services -> Enable AFP service).


03 September 2018 CMake bookmarks

28 August 2018 GTD/Get things done bookmarks

28 August 2018 Pandoc bookmarks

27 August 2018 Mauritius travel bookmarks

27 August 2018 Scala bookmarks

22 August 2018 Actionable URLs in Emacs buffers

Should have enabled actionable URLs in my Emacs buffers long ago. Can now click or press return to follow links. It's great on eshell, compilation buffers, async shell commands, code, etc.

(use-package goto-addr
  :hook ((compilation-mode . goto-address-mode)
         (prog-mode . goto-address-prog-mode)
         (eshell-mode . goto-address-mode)
         (shell-mode . goto-address-mode))
  :bind (:map goto-address-highlight-keymap
              ("<RET>" . goto-address-at-point)
              ("M-<RET>" . newline))
  :commands (goto-address-prog-mode


22 August 2018 Bazel bookmarks

18 August 2018 Palestine travel bookmarks

18 August 2018 Enabling Control-Meta(⌘)-D on macOS

I use command (⌘) as my Emacs Meta key. Recently discovered C-M-d is not available to Emacs for binding keys on macOS. Stack Exchange had the workaround:

defaults write AppleSymbolicHotKeys -dict-add 70 '<dict><key>enabled</key><false/></dict>'

13 August 2018 Recycling bookmarks

updated: 13 August 2018

12 August 2018 Comoro islands travel bookmarks

12 August 2018 France travel bookmarks

12 August 2018 Corsica travel bookmarks

12 August 2018 Mozambique travel bookmarks

12 August 2018 M-r history search in git-commit-mode

I've grown accustomed to M-r bindings to search Emacs history. Been wanting similar functionality to search commit message history. Turns out log-edit-comment-ring has some of my local commit message history. Feeding it to completing-read gives me an easily searchable history when using a completing framework like ivy or helm:

(defun ar/git-commit-search-message-history ()
  "Search and insert commit message from history."
  (insert (completing-read "History: "
                           ;; Remove unnecessary newlines from beginning and end.
                           (mapcar (lambda (text)
                                     (string-trim text))
                                   (ring-elements log-edit-comment-ring)))))

Now we bind it to M-r and we're good to go:

(bind-key "M-r" #'ar/git-commit-search-message-history git-commit-mode-map)

May also want to persist log-edit-comment-ring across Emacs sessions by adding log-edit-comment-ring to savehist variables. Also ensure savehist-mode is enabled:

(add-to-list 'savehist-additional-variables log-edit-comment-ring)
(savehist-mode +1)


09 August 2018 Morning smoothie

Big fan of my morning power smoothie. Best deals I've found so far:

ps. I have no affiliation to either retailer. Prices may change.

08 August 2018 Installing ludget (ledger visualization

Needed python3:

brew install python3

Use pip3 to install ludget:

pip3 install ludget

08 August 2018 Ledger bookmarks

updated: 30 September 2021

07 August 2018 Tip: Convert .texi to .info

Convert with:

makeinfo doc.texi

View with:

Open in Emacs and render as info with:

(defun ar/format-info-mode ()
  (let ((file-name (buffer-file-name)))
    (kill-buffer (current-buffer))
    (info file-name)))

25 July 2018 Marking 20k emails as read

Mbsync and mu4e are great for syncing and handling IMAP email. I've now migrated 4 email addresses, including an old Yahoo account.

I wanted to mark all my Yahoo unread emails as read. Yahoo's webmail enables marking 500 emails at a time, making the process a little tedious.

Mu-discuss has a handy thread, highlighting that moving/renaming synced messages (in your local file system) would do the job. This worked well for me.

Let's do just that…

WARNING: Copy a small sample of your mails to a separate directory and run some trials until you feel comfortable.

Find your mail directory.

cd path/to/mail

Peek at the messages you'd like to mark unread:

ls -1 new/

1529958027.57518_11.mbp,U=8415:2, 1531346210.38822_3.mbp,U=8741:2, 1532464801.21057_1.mbp,U=9028:2, 1532464801.21057_2.mbp,U=9029:2,

Rename message files by appending "S" to their filename and moving from new/ to cur/ directory.

for FILE in new/*; do mv "${FILE}" cur/$(basename "${FILE}")S; done;

We can verify the move.

ls -1 cur/

1529958027.57518_11.mbp,U=8415:2,S 1531346210.38822_3.mbp,U=8741:2,S 1532464801.21057_1.mbp,U=9028:2,S 1532464801.21057_2.mbp,U=9029:2,S

Let's sync the local changes.

mbsync -Va

…and we're done ;)

24 July 2018 Show iOS simulator touches

TIL from this tweet, that you can enable showing touches on iOS simulator. This is handy for making nicer screencasts.

defaults write .iphonesimulator ShowSingleTouches 1

15 July 2018 Amsterdam travel bookmarks

14 July 2018 Hardware bookmarks

11 July 2018 fitbit API, org babel, and gnuplot

Retook running recently. Took the dust off my aria scale and used the opportunity to check out fitbit's API.

First register your app at and get a client_id=AABBCC.


You'll also need your USER_ID, from your Fitbitx user profile.


We'll also need a token. I used the implicit grant flow URL in my browser and extracted access_token=TOKEN.

Now let's wire up two org source blocks to fetch the data and subsequently plot using gnuplot.

It's pretty neat. You can take the output from one source block and use it as input to another.

We use curl to fetch data from fitbit's API and pipe through jq and sed to massage the output format into two columns.

Note: Before using gnuplot in org babel, you'll need to install the gnuplot package and add to babel languages.

(use-package gnuplot :ensure t)

(use-package ob
   '((gnuplot . t))))
curl -s -H "Authorization: Bearer TOKEN" | jq '.[][] | "\(.dateTime) \(.value)"' | sed 's/"//g'
2018-06-09 65.753
2018-06-10 65.762
2018-06-11 65.771
2018-06-12 65.78
2018-06-13 65.789
2018-06-14 65.798
2018-06-15 65.807
2018-06-16 65.816
2018-06-17 65.825
2018-06-18 65.85
2018-06-19 65.96
2018-06-20 64.1
2018-06-21 65.64
2018-06-22 65.47
2018-06-23 65.515
2018-06-24 65.56
2018-06-25 65.605
2018-06-26 65.65
2018-06-27 65.18
2018-06-28 64.49
2018-06-29 64.49
2018-06-30 64.41
2018-07-01 64.33
2018-07-02 64.25
2018-07-03 64.17
2018-07-04 64.55
2018-07-05 64.39
2018-07-06 64.33
2018-07-07 65.06
2018-07-08 63.28
2018-07-09 63.4
2018-07-10 64.22
2018-07-11 63.95

Now feed the two column data to gnuplot.

set title "My recent weight"
set xdata time
set timefmt '%Y-%m-%d'
set format x "%d/%m/%y"
set term png
set xrange ['2018-06-09':'2018-07-11']
plot data u 1:2 with linespoints title 'Weight in Kg'


Fetching data and plotting through org babel and gnuplot is pretty sweet. I've barely scratched the surface. There's more at Org-babel-gnuplot and Plotting tables in Org-Mode using org-plot. Either way, this is another Emacs super power to keep in the toolbox.

08 July 2018 PIPESTATUS for all return codes

From @saruspete's tweet, ${PIPESTATUS[@]} gives ya all piped commands' return codes:

echo foo | grep bar | tr z a | cat
echo ${PIPESTATUS[@]}
0 1 0 0

07 July 2018 Emacs utilities for your OS

Narrowing utilities are a wonderful way of increasing productivity. I have a few workflows using Emacs's Helm framework.

There are great productivity boosters like Alfred and Quicksilver for macOS, with batteries included.

If you're a tinkerer, you'd enjoy the powerful Hammerspoon. Like elisp gluing all things Emacs, Hammerspoon uses Lua to glue all things macOS. You can build your own narrowing utilities using chooser and a little Lua.

local chooser =['text'])

         ["text"] = "Alfred\n",
         ["subText"] = "macOS only\n",
         ["text"] = "Quicksilver\n",
         ["subText"] = "macOS only\n",
         ["text"] = "Hammerspoon\n",
         ["subText"] = "macOS only\n",
         ["text"] = "Emacs\n",
         ["subText"] = "is everywhere :)\n",


Howard Abrams's post on Capturing Content for Emacs inspired me to look at gluing Emacs and macOS to launch my own cross-platform narrowing utilities.

I've also taken this opportunity to look at Oleh Krehel's wonderful completion package: Ivy. We can use it to build a macOS narrowing utility.

Ivy is remarkably easy to use. Turns out, ivy-read is all you need. A simple Emacs completion can be accomplished with little elisp.

(ivy-read "Hello ivy: "
          '("One "
            "Two "
            "Three "
            "Four "))


Pretty nifty. Let's make this completion more accessible from the rest of the OS. To do so, we create a separate Emacs frame and make it pretty. We also want it to interact with the OS. We'll use ivy-read's :action to invoke a tiny bit of AppleScript.

Oh and we'll also use some funny quotes to tease ourselves about our beloved editor.

(with-current-buffer (get-buffer-create "*modal-ivy*")
  (let ((frame (make-frame '((auto-raise . t)
                             (background-color . "DeepSkyBlue3")
                             (cursor-color . "MediumPurple1")
                             (font . "Menlo 15")
                             (foreground-color . "#eeeeec")
                             (height . 20)
                             (internal-border-width . 20)
                             (left . 0.33)
                             (left-fringe . 0)
                             (line-spacing . 3)
                             (menu-bar-lines . 0)
                             (minibuffer . only)
                             (right-fringe . 0)
                             (tool-bar-lines . 0)
                             (top . 48)
                             (undecorated . t)
                             (unsplittable . t)
                             (vertical-scroll-bars . nil)
                             (width . 110)))))
    (set-face-attribute 'ivy-minibuffer-match-face-1 frame
                        :background nil
                        :foreground nil)
    (set-face-attribute 'ivy-minibuffer-match-face-2 frame
                        :background nil
                        :foreground "orange1")
    (set-face-attribute 'ivy-minibuffer-match-face-3 frame
                        :background nil
                        :foreground "orange1")
    (set-face-attribute 'ivy-minibuffer-match-face-4 frame
                        :background nil
                        :foreground "orange1")
    (set-face-attribute 'ivy-current-match frame
                        :background "#ffc911"
                        :foreground "red")
    (set-face-attribute 'minibuffer-prompt frame
                        :foreground "grey")
    (let ((ivy-height 20)
          (ivy-count-format ""))
      (ivy-read "Emacs acronyms: "
                '(" Emacs: Escape-Meta-Alt-Control-Shift "
                  " Emacs: Eight Megabytes And Constantly Swapping "
                  " Emacs: Even a Master of Arts Comes Simpler "
                  " Emacs: Each Manual's Audience is Completely Stupified "
                  " Emacs: Eventually Munches All Computer Storage "
                  " Emacs: Eradication of Memory Accomplished with Complete Simplicity "
                  " Emacs: Easily Maintained with the Assistance of Chemical Solutions "
                  " Emacs: Extended Macros Are Considered Superfluous "
                  " Emacs: Every Mode Accelerates Creation of Software "
                  " Emacs: Elsewhere Maybe All Commands are Simple "
                  " Emacs: Emacs Makes All Computing Simple "
                  " Emacs: Emacs Masquerades As Comfortable Shell "
                  " Emacs: Emacs My Alternative Computer Story "
                  " Emacs: Emacs Made Almost Completely Screwed "
                  " Emacs: Each Mail A Continued Surprise "
                  " Emacs: Eating Memory And Cycle-Sucking "
                  " Emacs: Elvis Masterminds All Computer Software "
                  " Emacs: Emacs Makes A Computer Slow" )
                :action (lambda (funny-quote)
                          (async-shell-command (format "osascript -e 'tell app \"System Events\" to display dialog \"%s\" buttons {\"OK\"}'" funny-quote)))
                :unwind (lambda ()
                          (shell-command "/Applications/ -c 'backFromEmacs()'")
                          (other-window 1))))))


So where's all this going? I wrote a utility to extract all links from this page's org file and make them easily searchable from anywhere on macOS by invoking ⌥-W.

The keys are bound using Lua, Hammerspoon, and emacsclient. This works well on macOS, but there are alternatives for other operating systems.

hs.execute("emacsclient -ne \""..elisp.."\" -s /tmp/emacs*/server")

Here's the resulting utility in action:


These integrations look promising. They enable me to bring cross-platform Emacs utilities into areas I hadn't considered.

01 July 2018 Web serving tools bookmarks

24 June 2018 URL shortener bookmarks

17 June 2018 Trying out mu4e with mbsync

The email fun in Emacs continues. After a few weeks since I started using mu4e and offlineimap, I'm sold. Both are awesome. Mbsync is an offlineimap alternative. Despite resyncing all my mail, the transition was fairly smooth. Here's how…

Install isync (for mbsync)

brew install isync

Configure mbsync

Mbsync uses ~/.mbsyncrc for configuration. Migrating ~/.offlineimaprc to ~/.mbsyncrc looks like:

IMAPAccount Personal
User your_user_name
PassCmd "gpg --quiet --batch -d ~/.offlineimap_accountname.gpg"
Port 993
AuthMechs Login
CertificateFile  ~/.offlineimapcerts.pem
# My IMAP provider doesn't handle concurrent IMAP commands.
PipelineDepth 1

IMAPStore Personal-remote
Account Personal

MaildirStore Personal-local
Path ~/IMAP/Personal/
Inbox ~/IMAP/Personal/INBOX

Channel Personal
Master :Personal-remote:
Slave :Personal-local:
Patterns *
Create Slave
Sync All
Expunge Both
SyncState *

No concurrent IMAP commands supported

My IMAP provider doesn't handle concurrent IMAP commands. mbsync and Office 365 had the answer:

PipelineDepth 1

Initial sync

Run initial from the command line sync:

mbsync -Va

While syncing my largest inbox, it sometimes received an unexpected EOF error:

IMAP error: unexpected EOF from (

First few times, I restarted the syncing manually, but then used a loop to automatically restart it.

Bash loops:

while true; do mbsync -V Personal; sleep 5; done
for i in {1..5}; do mbsync -V Personal; sleep 5; done

Eshell loop:

for i in (number-sequence 1 10) {mbsync -V Personal; sleep 5}

Create mu index

Reindex using mu, but first remove existing index for offlineimap messages:

rm -rf ~/.mu

Ok, do index now:

mu index --maildir=~/IMAP

Mu4e tweaks

The get mail command should now point to mbsync.

(csetq mu4e-get-mail-command "mbsync -Va")

I had issues with duplicate IDs after moving and deleting messages from mu4e. Migrating from offlineimap to mbsync for mu4e had the answer:

(csetq mu4e-change-filenames-when-moving t)

15 June 2018 Sticky function keys on touch bar

Visible (and sticky) function keys are not the touch bar default for Emacs. Let's change that:


13 June 2018 GNU find on macOS

At times, you may need GNU versions of command line utilities on macOS. For example, GNU find.

As usual, Homebrew saves the day. Install with:

brew install findutils

Unless you install with –with-default-names (I don't), GNU utilities will be prefixed with a "g".

gfind --version
find (GNU findutils) 4.6.0
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2)

If you need more, there are others:

brew install binutils
brew install diffutils
brew install ed
brew install findutils
brew install gawk
brew install gnu-indent
brew install gnu-sed
brew install gnu-tar
brew install gnu-which
brew install gnutls
brew install grep
brew install gzip
brew install screen
brew install watch
brew install wdiff --with-gettext
brew install wget

13 June 2018 PlantUML bookmarks

29 May 2018 Adding mu4e maildirs extension

Continuing the mu4e fun, added mu4e-maildirs-extension to display a mail dirs summary.


28 May 2018 Trying out mu4e and offlineimap


Managing Email from Emacs. Surely that's crazy-talk, but hey… let's give it a try.

Install offlineimap

Need to sync via imap. Use offlineimap. I'm on macOS, so homebrew is king for installing:

brew install offlineimap

Before can configure offlineimap, we'll need to handle a few things first.

Get a cert fingerprint

Use openssl for getting a certificate fingerprint. From offlineimap's FAQ:

SSL_CERT_DIR="" openssl s_client -connect < /dev/null 2>/dev/null | openssl x509 -fingerprint -noout -text -in /dev/stdin

Should give you something like:

SHA1 Fingerprint=AA:BB:CC:DD:EE:DD:FF:AA:00:AA:2A:AA:AA:AA:A8:20:80:AA:A2:AA

Encrypt password

Offlineimap can read passwords in plain text in its .offlineimaprc config file, but that's yuckie. Let's encrypt the password and use gnupg for that. Install it:

brew install gnupg

If you haven't already, generate a key

gpg --full-gen-key

Generate an offlineimap account password file.

echo "YourPassword" | gpg --encrypt --recipient "Your Name" -o ~/.offlineimap_accountname.gpg

Python password wrapper

Based on Fabian's Encrypt OfflineIMAP and msmtp password with GnuPG, I created ~/ with:

import os
import subprocess

def read_password(path):
  return subprocess.check_output(["gpg\n", "--quiet\n", "--batch\n", "-d\n", os.path.expanduser(path)]).strip()

ps. Alternatively, see The homely Mutt's section to store password in macOS's keychain.

Configure offlineimap

Offlineimap uses ~/.offlineimaprc for configuration. We now have all we need to put the configuration together:

accounts = Personal

# Load this python file.
pythonfile = ~/

[Account Personal]
localrepository = Personal-Local

remoterepository = Personal-Remote

# After syncing, let mu index it.
postsynchook = mu index --maildir ~/stuff/active/Mail

# Sync imap every 5 minutes.
autorefresh = 5

# Alternate between 10 quick syncs and full syncs.
quick = 10

[Repository Personal-Local]
type = Maildir
localfolders = ~/stuff/active/Mail/Personal

[Repository Personal-Remote]
type = IMAP
remotehost =
remoteuser = your_user_name

# Use function defined in to read the password.
remotepasseval = read_password("~/.offlineimap_personal_account_password.gpg")

# Use the SHA1 fingerprint retrieved with openssl.
cert_fingerprint = aabbccddeeddffaa00aa2aaaaaaaa82080aaa2aa

Cert file

You can use macOS's certificates from Keychain Access -> System Roots -> Certificates, select all, and ⌘-⇧-e (for export items). Save to ~/certs.pem and use offlineimap configutation:

sslcacertfile = /path/to/certs.pem

Another option is executing lib/ from curl's tarball to generate ca-bundle.crt, using certdata.txt from Mozilla's source tree.

Install mu4e

Manually modified mu4e recipe to pick up my Emacs binary. TIL about homebrew's edit command:

brew edit mu

Changed the one line:

  • ENV["EMACS"] = "no" if build.without? "emacs"
  • ENV["EMACS"] = "/Users/alvaro/homebrew/Cellar/emacs-plus/26.1-rc1_2/bin/emacs"

Finally installed mu4e:

brew install mu

Configure mu4e

Lastly, configure mu4e:

(add-to-list 'load-path
             (expand-file-name "~/homebrew/share/emacs/site-lisp/mu/mu4e"))
(use-package mu4e
  ;; Update mail using 'U' in main view:
  (setq mu4e-get-mail-command "offlineimap")
  (setq mu4e-view-show-addresses t)
  (setq mu4e-attachment-dir (expand-file-name "~/Downloads/"))
  (setq mu4e-maildir "path/to/Mail")
  (setq mu4e-html2text-command "w3m -T text/html") ;; alternatively "textutil -stdin -format html -convert txt -stdout"
  (setq mu4e-user-mail-address-list '(""
  (setq mu4e-context-policy 'pick-first)
  (setq mu4e-compose-context-policy 'always-ask)
  (setq mu4e-contexts
          :name "domain1"
          :enter-func (lambda () (mu4e-message "Entering context"))
          :leave-func (lambda () (mu4e-message "Leaving context"))
          :match-func (lambda (msg)
                        (when msg
                           msg '(:from :to :cc :bcc) "")))
          :vars '((user-mail-address . "")
                  (user-full-name . "My name")
                  (mu4e-sent-folder . "/Domain1/Sent")
                  (mu4e-drafts-folder . "/Domain1/Drafts")
                  (mu4e-trash-folder . "/Domain1/Trash")
                  (mu4e-compose-signature . nil)
                  (mu4e-compose-format-flowed . nil)
                  (smtpmail-smtp-user . "")
                  (smtpmail-smtp-server . "")
                  (smtpmail-smtp-service . 587)))
          :name "domain2"
          :enter-func (lambda () (mu4e-message "Entering context"))
          :leave-func (lambda () (mu4e-message "Leaving context"))
          :match-func (lambda (msg)
                        (when msg
                           msg '(:from :to :cc :bcc) "")))
          :vars '((user-mail-address . "")
                  (user-full-name . "My name")
                  (mu4e-sent-folder . "/Domain2/Sent")
                  (mu4e-drafts-folder . "/Domain2/Drafts")
                  (mu4e-trash-folder . "/Domain2/Trash")
                  (mu4e-compose-signature . nil)
                  (mu4e-compose-format-flowed . nil)
                  (smtpmail-smtp-user . "")
                  (smtpmail-smtp-server . "")
                  (smtpmail-smtp-service . 587))))))

(use-package smtpmail
  (setq smtpmail-stream-type 'starttls)
  (setq smtpmail-debug-info t)
  (setq smtpmail-warn-about-unknown-extensions t)
  (setq smtpmail-queue-mail t)
  (setq smtpmail-default-smtp-server nil)
  ;; Created with mu mkdir path/to/Mail/queue
  ;; Also avoid indexing.
  ;; touch path/to/Mail/queue/.noindex
  (setq smtpmail-queue-dir "path/to/Mail/queue/cur"))

(use-package message
  (setq message-send-mail-function 'smtpmail-send-it))


Create an ~/.authinfo file for sendmail authentication with:

machine login password somepassword1
machine login password somepassword2

Encrypt ~/.authinfo with M-x epa-encrypt-file. Keep ~/.authinfo.gpg and delete ~/.authinfo.

Mu4e helpful references

24 May 2018 Transparent Emacs titlebars on macOS

Happy with Emacs Plus builds on Mac. You get some eye-candy bonuses like transparent titlebars.

To install:

brew tap d12frosted/emacs-plus
brew install emacs-plus --without-spacemacs-icon


(when (memq window-system '(mac ns))
  (add-to-list 'default-frame-alist '(ns-appearance . dark)) ; nil for dark text
  (add-to-list 'default-frame-alist '(ns-transparent-titlebar . t)))


24 May 2018 Lunette: Like Spectacle but for Hammerspoon

Came across Lunette. Gives ya Spectacle Keybindings for Hammerspoon.

23 May 2018 Train Emacs to open files externally

TIL about the openwith package. It enables Emacs to defer to external programs for certain files. You choose which ones. Neat.

(use-package openwith :ensure t
  (csetq openwith-associations
         '(("\\.\\(mp4\\|mp3\\|webm\\|avi\\|flv\\|mov\\)$" "open" (file))))
  (openwith-mode 1))

22 May 2018 Show hidden files in Finder

defaults write AppleShowAllFiles TRUE
killall Finder

22 May 2018 Ejecting USB drives on Synology

For posterity:

Control panel > External devices > USB Disk 1 > Eject

21 May 2018 Remounting Synology encrypted share

Had been a while since I did this… for posterity:

Control panel > Shared Folder > Encryption > Mount

20 May 2018 Synology user had no home

Upon ssh'ing to a Synology box, the user had no home.

Could not chdir to home directory /var/services/homes/someone: No such file or directory

Fixed via:

Control Panel > User > Advanced > User Home > [x] Enable user home service

30 April 2018 Pre-commit hooks to save you from yourself

Wanted to try out some code, but needed to ensure never checked in. Git pre-commit hooks are handy in this space. Add the following script to search for either @COMMITFAIL or @NOCOMMIT in the staged files. If found, attempts to commit will fail.

Based on


set -o nounset
set -o errexit

echo "Arguments:"
echo "$@"
echo "---"

readonly FILES_PATTERN='(\..+)?$'

if ( git diff --cached --name-only | grep -E "$FILES_PATTERN" | xargs grep -E --with-filename -n "$FORBIDDEN" ); then
  echo "ERROR: @COMMITFAIL or @NOCOMMIT found. Exiting to save you from yourself."
  exit 1

Save to a file and create a symbolic link to your .git/hooks directory:

ln -s ../../git/ .git/hooks/pre-commit

19 April 2018 Azores travel bookmarks

19 April 2018 Debugging Emacs binary

From How do I debug an emacs crash? (Emacs Stack Exchange), disable optimizations when configuring and build:

CFLAGS="-O0 -g3" ./configure ...

And good 'ol gdb (lldb works too):

gdb ../nextstep/

19 April 2018 Paper less bookmarks

18 April 2018 Bologna travel bookmarks

  • Il Cannone restaurant.

17 April 2018 Grep through pdfs

Late to the party, but investing in going paperless. Got a scanner with OCR, which generates searchable pdfs. If I could only grep through them…

brew install pdfgrep

Balance restored.

14 April 2018 Hammerspoon bookmarks

14 April 2018 Options to reduce Go binary size

A Hacker News's thread Go gets preliminary WebAssembly support has a couple of tips to reduce binaries compiled with Go.

go build -ldflags=-s

UPX (Ultimate Packer for eXecutables) packs the binary further.

upx --ultra-brute

09 April 2018 Trying out tesseract

As part of going paperless, looking into OCR. Trying out tesseract.


$ brew install gs
$ brew install imagemagick
$ brew install tesseract
$ convert -density 300 -depth 8 receipt.pdf receipt.png
$ tesseract receipt.png receipt.png.txt

08 April 2018 Sapporo travel bookmarks

08 April 2018 Gif bookmarks

08 April 2018 Trying out ShellCheck

ShellCheck gives you automatic warnings/suggestions in bash/sh shell scripts.

$ brew install shellcheck

Bonus: If using Emacs's flycheck, you get ShellCheck support out of the box.

08 April 2018 Image editing bookmarks

05 April 2018 Buying matcha powder online

04 April 2018 Getting macOS app bundle ID

From stack overflow:

Option 1

osascript -e 'id of app "Emacs"'

Option 2

mdls -name kMDItemCFBundleIdentifier -r

31 March 2018 Trying out chunkwm


Installing Chunkwm

$ brew tap crisidev/homebrew-chunkwm
$ brew install --HEAD --with-tmp-logging chunkwm

Add a configuration file. Started off from this example.

~/.chunkwmrc chmod +x ~/.chunkwmrc

Note: Ensure core::plugin_dir matches homebrew's plugin directory. Typically something like: /path/to/homebrew/opt/chunkwm/share/chunkwm/plugins

Start chunkwmrc service.

$ brew services start crisidev/chunkwm/chunkwm

Installing skhd (a hotkey daemon)

$ brew install --HEAD --with-logging  koekeishiya/formulae/skhd

Start skhd service.

$ brew services start koekeishiya/formulae/skhd

Skhd logs location.


Add a configuration file. Started off from this example.

chmod +x ~/.skhdrc

Installing khd (easily invoke hotkeys from terminal)

$ brew install khd

Some additional Mission Control and keyboard shortcut preferences:



06 February 2018 Building bazel on macOS


brew tap bazelbuild/tap
brew install bazelbuild/tap/bazel


git clone
cd bazel
bazel build //src:bazel

Get your bazel binary

Self-contained binary in bazel-bin/src/bazel

Known revisions

07 January 2018 Extracting files from pkg

mkdir tmp
cd tmp
xar -xf ../Some.pkg
cat Payload | gunzip -dc |cpio -i

07 January 2018 Installing Inkscape with homebrew

brew tap caskroom/cask
brew install caskformula/caskformula/inkscape

16 December 2017 Magit amend commit author

Rarely use it, but handy. Use Magit to amend git commit author.

  • Rebase interactively (r, i).
  • Move point to commit to ammend.
  • Execute command (x).
git commit --amend --author="name <email>"
  • Commit (c, c).


13 December 2017 Homebrew install from cache

Came across a 404 while installing graphviz-2.40.1.tar.gz via homebrew. If you can find the package elsewhere, copy over to homebrew's cache directory.

brew --cache


16 November 2017 org-babel Objective-C support

Wanted to quickly execute an Objective-C snippet. org-babel didn't support it out of the box, but adding it was straightforward (looked at ob-C.el and ob-java.el):

(require 'ob)

(defcustom org-babel-objc-compile-command "clang -x objective-c -framework Foundation"
  "For example: \"clang -x objective-c -framework Foundation\"."
  :group 'org-babel
  :version "24.3"
  :type 'string)

(defun org-babel-execute:objc (body params)
  "Compile Objective-C BODY with org PARAMS and execute binary."
  (let* ((src-file (org-babel-temp-file "org-babel-objc-block-" ".m"))
         (cmpflag (or (cdr (assq :cmpflag params)) ""))
         (full-body (org-babel-expand-body:generic body params))
           (org-babel-temp-file "org-babel-objc-block" org-babel-exeext))))
    (with-temp-file src-file (insert full-body))
     (concat org-babel-objc-compile-command " " cmpflag " " src-file " " "-o" " " bin-file) "")

    ;; Using 2>&1 since org babel does not include stderr in output from NSLog.
    (let ((results (org-babel-eval (concat (org-babel-process-file-name bin-file) " 2>&1")  "")))
       (org-babel-result-cond (cdr (assq :result-params params))
         (org-babel-read results)
         (let ((tmp-file (org-babel-temp-file "c-")))
           (with-temp-file tmp-file (insert results))
           (org-babel-import-elisp-from-file tmp-file)))
        (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
        (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))

(provide 'ob-objc)

Add objc to org-babel-load-languages, and you can subsequently compile and run Objective-C blocks like:

#import <Foundation/Foundation.h>

int main() {
  NSLog(@"Hello World");
  return 0;
2017-11-16 01:47:28.923 org-babel-objc-block-Aai8ux[15319:346480] Hello World

12 November 2017 iOS dev command-line goodies

Install ipa on device

Get utility with:

npm install -g ipa-deploy
npm install -g ios-deploy

Install ipa on connected iPhone:

ipa-deploy path/to/your/App.ipa

Install app on booted simulator

Install ipa on connected iPhone:

xcrun simctl install booted path/to/your/

Install ipa on booted simulator


# Unzip ipa, install app, and run on booted simulator.

set -o nounset
set -o errexit

readonly IPA_PATH=$1
readonly TEMP_DIR_PATH=$(mktemp -d)
readonly BASENAME=$(basename ${IPA_PATH})
readonly NAME=${BASENAME%.*}
readonly APP_DIR_PATH="${TEMP_DIR_PATH}/Payload/${NAME}.app"
readonly PLIST_FILE_PATH="${APP_DIR_PATH}/Info.plist"

trap "rm -rf ${TEMP_DIR_PATH}" EXIT

unzip -o "${IPA_PATH=}" -d "${TEMP_DIR_PATH}"

readonly BUNDLE_ID=$(/usr/libexec/PlistBuddy -c "Print CFBundleIdentifier" ${PLIST_FILE_PATH})

xcrun simctl install booted "${APP_DIR_PATH}"
xcrun simctl launch booted "${BUNDLE_ID}"

01 November 2017 Eshell pcomplete company completion

Howard Abrams's Introduction to eshell video prompted me to poke at eshell some more. This time, I got eshell context aware completion by glueing the excellent company and pcomplete packages.


(require 'cl-lib)
(require 'company)
(require 'dash)
(require 'pcomplete)
(require 's)

(defun company-pcomplete--overlap-tail (a b)
  "When A is \"SomeDev\" and B is \"Developer\", return \"eloper\"."
  (let ((prefix a)
        (remaining nil))
    (while (and (not remaining) (> (length prefix) 0))
      (when (s-starts-with? prefix b)
        (setq remaining (substring b (length prefix))))
      (setq prefix (substring prefix 1)))

(defun company-pcomplete--candidates (prefix)
  "Get candidates for PREFIX company completion using `pcomplete'."
  ;; When prefix is: "~/Down" and completion is "Downloads", need
  ;; to find common string and join into "~/Downloads/".
  (-map (lambda (item)
          (if (s-starts-with? prefix item)
            (concat prefix (company-pcomplete--overlap-tail prefix item))))
        (all-completions prefix (pcomplete-completions))))

(defun company-pcomplete (command &optional arg &rest ignored)
  "Complete using pcomplete. See `company''s COMMAND ARG and IGNORED for details."
  (interactive (list 'interactive))
  (case command
    (interactive (company-begin-backend 'company-pcomplete))
    (prefix (company-grab-symbol))
     (company-pcomplete--candidates arg))))

Don't forget to add company-pcomplete to company-backends, and if you want an explicit binding, use something like:

(bind-key "<backtab>" #'company-complete eshell-mode-map)

10 September 2017 Basic imenu in helpful-mode

I'm finding Wilfred Hughes's helpful-mode, well… rather helpful. However, I'm missing imenu support. Here's a hacky way to get basic imenu.


(defun helpful--create-imenu-index ()
  "Create an `imenu' index for helpful."
  (let ((imenu-items '()))
    (while (progn
             ;; Not great, but determine if looking at heading:
             ;; 1. if it has bold face.
             ;; 2. if it is capitalized.
             (when (and (eq 'bold (face-at-point))
                         (buffer-substring (line-beginning-position)
               (add-to-list 'imenu-items
                            (cons (buffer-substring (line-beginning-position)
             (= 0 (forward-line 1))))

(defun helpful-mode-hook-function ()
  "A hook function for `helpful-mode'."
  (setq imenu-create-index-function #'helpful--create-imenu-index))

(add-hook 'helpful-mode-hook

19 August 2017 Projectile shell dir company completion

Projectile and company are just amazing Emacs packages. Projectile gives random access to files, while company completes well… anything. For shells, Emacs has a handful of options.

Standing on the shoulders of package giants (dash and f included) and some elisp, we can bring random access to project directories from the shell.


(require 'cl-lib)
(require 'company)
(require 'dash)
(require 'f)
(require 'projectile)

(defvar-local company-projectile-cd-prefix "cd ")

(defun company-projectile-cd (command &optional arg &rest ignored)
  "Company shell completion for any projectile path."
  (interactive (list 'interactive))
  (case command
    (interactive (company-begin-backend 'company-projectile-cd))
     (company-grab-symbol-cons company-projectile-cd-prefix
                               (length company-projectile-cd-prefix)))
      (company-grab-symbol-cons company-projectile-cd-prefix
                                (length company-projectile-cd-prefix))))
     (company-projectile-cd--expand-inserted-path arg))))

(defun company-projectile-cd--candidates (input)
  "Return candidates for given INPUT."
  (when (consp input)
    (let ((search-term (substring-no-properties
                        (car input) 0 (length (car input))))
          (prefix-found (cdr input)))
      (when prefix-found
        (if (projectile-project-p)
            (company-projectile-cd--projectile search-term)
          (company-projectile-cd--find-fallback search-term))))))

(defun company-projectile-cd--projectile (search-term)
  (-filter (lambda (path)
             (string-match-p (regexp-quote
            ;; Throw project root in there also.

(defun company-projectile-cd--find-fallback (search-term)
    (-map (lambda (path)
            (string-remove-prefix "./" path))
          (apply #'process-lines
                 (list "find" "." "-type" "d"  "-maxdepth" "2" "-iname"
                       (format "\*%s\*" search-term))))))

(defun company-projectile-cd--expand-inserted-path (path)
  "Replace relative PATH insertion with its absolute equivalent if needed."
  (unless (f-exists-p path)
    (delete-region (point) (- (point) (length path)))
    (insert (concat (projectile-project-root) path))))

(defun company-projectile-cd--reset-root ()
  "Reset project root. Useful when cd'ing in and out of projects."
  (when (projectile-project-p)

09 August 2017 Creating icns icons

Stack overflow yields Where can i find Icon Composer on Mac? when I did a quick search to convert a png to icns. For future reference:

#!/bin/bash -e

set -e
set -o pipefail

if [ "$#" -ne 1 ]; then
 echo "\nusage: path/to/image.png\n"
 exit 1

readonly IMAGE_FPATH=$1
readonly BASENAME=$(basename ${IMAGE_FPATH%.*})

mkdir ${BASENAME}.iconset

sips -z 16 16   $IMAGE_FPATH --out "${BASENAME}.iconset/icon_16x16.png"
sips -z 32 32   $IMAGE_FPATH --out "${BASENAME}.iconset/icon_16x16@2x.png"
sips -z 32 32   $IMAGE_FPATH --out "${BASENAME}.iconset/icon_32x32.png"
sips -z 64 64   $IMAGE_FPATH --out "${BASENAME}.iconset/icon_32x32@2x.png"
sips -z 128 128 $IMAGE_FPATH --out "${BASENAME}.iconset/icon_128x128.png"
sips -z 256 256 $IMAGE_FPATH --out "${BASENAME}.iconset/icon_128x128@2x.png"
sips -z 256 256 $IMAGE_FPATH --out "${BASENAME}.iconset/icon_256x256.png"
sips -z 512 512 $IMAGE_FPATH --out "${BASENAME}.iconset/icon_256x256@2x.png"
sips -z 512 512 $IMAGE_FPATH --out "${BASENAME}.iconset/icon_512x512.png"

cp $IMAGE_FPATH "${BASENAME}.iconset/icon_512x512@2x.png"

iconutil -c icns ${BASENAME}.iconset

rm -R ${BASENAME}.iconset

echo Wrote ${BASENAME}.icns

06 August 2017 Forcing aptX on MacOS bluetooth audio

Bought a pair of QuietComfort 35. Audio quality on MacOS was lagging compared to iOS. Googling led to different posts suggesting the use of Bluetooth Explorer to force aptX usage. Did the trick for me.

Bluetooth Explorer can be downloaded from Search for Hardware IO tools:


Open Hardware_IO_Tools_for_Xcode_7.3.dmg and launch Bluetooth Explorer:


Select Audio Options:


Check Force use of aptX:


Don't forget to disconnect and reconnect your Bluetooth device.

10 July 2017 Hungary travel bookmarks

08 July 2017 Faster cursor movement on macOS

Faster cursor movement on macOS by increasing your keyboard's initial key repeat subsequent key repeat.

defaults write -g KeyRepeat -int 1
defaults write -g InitialKeyRepeat -int 10

07 July 2017 Search/insert one-liners with Emacs helm-ag

Emacs helm is awesome. helm-ag is double awesome. Searching for one-liners in your codebase, narrowing down with helm, and easily inserting is triple awesome.


(defun ar/helm-ag (arg)
  "Helm-ag search remembering last location.  With ARG, forget the last location."
  (interactive "P")
  (defvar ar/helm-ag--default-locaction nil)
  (setq ar/helm-ag--default-locaction
                 (read-directory-name "search in: " (if arg
                                                      ar/helm-ag--default-locaction) nil t))
  (helm-do-ag ar/helm-ag--default-locaction))

(defun ar/helm-ag-insert (arg)
  ;; Helm-ag and insert match.
  (interactive "P")
  (let* ((actions (helm-make-actions
                   (lambda (candidate)
                     ;; Drop file:line:column. For example:
                     ;; arc_hostlink.c:13:2:#include <linux/fs.h>
                     ;; => #include <linux/fs.h>
                     (insert (replace-regexp-in-string "^[^ ]*:" "" candidate)))))
         (helm-source-do-ag (helm-build-async-source "The Silver Searcher"
                              :init 'helm-ag--do-ag-set-command
                              :candidates-process 'helm-ag--do-ag-candidate-process
                              :persistent-action  'helm-ag--persistent-action
                              :action actions
                              :nohighlight t
                              :requires-pattern 3
                              :candidate-number-limit 9999
                              :keymap helm-do-ag-map
                              :follow (and helm-follow-mode-persistent 1))))
    (call-interactively #'ar/helm-ag)))

29 May 2017 Sleep bookmarks

28 May 2017 Tea bookmarks

23 April 2017 Math bookmarks

23 April 2017 GnuPG and macOS

Had problems installing and using GnuPG on macOS, primarily for Emacs use:

gpg: problem with the agent: Inappropriate ioctl for device
gpg: error creating passphrase: Operation cancelled
gpg: symmetric encryption of '[stdin]' failed: Operation cancelled

Basic installation required:

brew install gnupg

But worked around the error above by using pinentry-mac (UI), instead of Emacs prompts.

brew install pinentry-mac

Edited ~/.gnupg/gpg-agent.conf with:

pinentry-program path/to/homebrew/bin/pinentry-mac

May need to kill gpg-agent to reload config.

gpgconf --kill gpg-agent

13 March 2017 Installing gnuplot on macOS

UPDATE(2019-05-19 Sun): Plan A and B use options no longer available since the recent changes to remove all options from Homebrew/homebrew-core formulae. See Plan C.

Plan A

Install gnuplot Qt

If you have the resources, you can try the Qt flavor. You need at least 15GB to download and a long build. Ran out of space on my Macbook Air. Aborted.

brew install gnuplot --with-qt

Plan B

Install xquartz

brew install Caskroom/cask/xquartz

Install gnuplot x11

brew install gnuplot --with-x11

Install feedgnuplot

Feedgnuplot is handy for plotting data streams realtime.

brew install feedgnuplot

Plan C

Install with no options

brew install gnuplot

So far so good, but default gnuplot formula uses Qt and the Cocoa plugin could not be loaded:

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""



    Turns out you can get plugin logs using the QT_DEBUG_PLUGINS environment variable:

    export QT_DEBUG_PLUGINS=1

    QFactoryLoader::QFactoryLoader() checking directory path "/Users/myuser/homebrew/Cellar/gnuplot/5.2.6_1/libexec/gnuplot/5.2/platforms" …

    This led me to find out about the gnuplot/5.2/gnuplot_qt binary.

  • qt_prfxpath

    Getting the Qt prefix can be done by inspecting QtCore's strings:

    strings /Users/myuser/homebrew/Cellar/qt/5.12.3/Frameworks/QtCore.framework/QtCore | grep qt_prfxpath

    Ok so qt_prfxpath is pointing to /usr/local/Cellar/qt, while my installation's is at /Users/myuser/homebrew/Cellar/qt. This is problematic and indeed my fault for installing homebrew in /Users/myuser/homebrew instead of the recommended /usr/local.

    Symlinking did the job:

    sudo mkdir -p /usr/local/Cellar
    sudo ln -s ~/homebrew/Cellar/qt /usr/local/Cellar/qt
    QFactoryLoader::QFactoryLoader() checking directory path "/Users/myuser/homebrew/Cellar/qt/5.12.3/plugins/platforms" ...
    QFactoryLoader::QFactoryLoader() looking at "/Users/myuser/homebrew/Cellar/qt/5.12.3/plugins/platforms/libqcocoa.dylib"
    Found metadata in lib /Users/myuser/homebrew/Cellar/qt/5.12.3/plugins/platforms/libqcocoa.dylib


22 January 2017 Tel Aviv travel bookmarks

updated: 27 January 2019
  • Breakfast club (dancing).
  • Claro/Sarona Market.
  • Dizengoff Square - Wikipedia.
  • Drink Cafe hafuch at Rothschild 12.
  • Jaffa's Flea market.
  • Nightlife: Kuli Alma's hipster haven. Imperial craft cocktail bar (drink Gold fashioned).
  • Park HaYarkon.
  • Tel Aviv museum of art.

22 January 2017 Jerusalem travel bookmarks

  • Jerusalem: Rooftop Mamilla restarurant.

22 January 2017 Nepal travel bookmarks

02 December 2016 Singapore notes

  • Hotel Mono, 18 Mosque street #01-04.
  • Buddha tooth relic museum.
  • Best Hawker centers.
  • Kong Meng San Phor Kark See Monastery.
  • Go there (figure out fastest MRT route).
  • What to eat at ABC Market (Hawker Centre) aka ABC Brickworks Food Centre?.
  • Curry puffs (see Taste test: Crisp curry puffs).
  • Singapore’s 17 Michelin-rated Hawker Stalls in 2016.
  • Temples
  • Hawkers
    • Mr and Mrs Mohgan's Super Crispy Roti Prata (source) on Crane Road. Dhal/fish/mutton curry side.
    • Roast Paradise (maybe) Address: #01-122 Old Airport Road Food Centre. Hours: Tues-Sun: 11am to 4pm or till sold out, Wed and Sun: 11am to 2pm, Closed on Mondays.
    • Fatty Cheong, 肥仔详, (#01-120, ABC Brickworks Food Centre, 6 Jalan Bukit Merah Singapore 150006): char siew and xio bak rice and char siew noodles.
    • Hoo Kee Bak Chang (Amoy Street Food Centre): bak zhang (glutinous rice dumpling). Try Choose from three kinds: chestnut ($2.80); chestnut with salted egg yolk ($3.60); and chestnut with mushroom ($3.60).
    • Lim Kee (Orchard) Banana Fritters (Maxwell food centre, source).
    • Mr Avocado Exotic Juice (Alexandra village food centre, source).
    • Tanglin Crispy Curry Puff (Hong Lim Food Centre or Maxwell, source) (东陵酥皮咖喱角). Try sardine curry puff?
    • Chuan Kee Satay (source). Long queue for pork satay.
    • Selera Rasa Nasi Lemak (source).
    • Fu Shun Jin Ji Shao La Mian Jia (Maxwell food centre, source): Char siu + noodles.
    • Shanghai La Mian Xiao Long Bao (Alexandra Village food centre, source): xiao long bao or soup dumplings ($4.50 for 7 pieces).
  • Timbre+ (hipster hawker centre? source).
  • Supertree Grove (go at dusk, see lights turn on).
  • Singapore Botanic garden.
    • Ginger Garden.
    • Palms valley.
    • Orchid garden.
  • Sri Mariamman Temple.
  • Kusu Island?
  • Chilly crab (“Jumbo” Chilli Crab Restaurant in Clarke Quay or Harvest Seafood Restaurant)?
  • Afternoon tea?
  • Bumboats (£2.50 return) leave Changi Point between 6am and 9.30pm for the 10-minute crossing to Palau Ubin. Hire a bicycle in the village where the boats dock.
  • Haji Lane (colorful road).
  • Tiong Bahru 1930s public housing estate (**)
    • Chong Yu Wanton Mee (Tiong Bahru Market And Food Centre #02-30, 30 Seng Poh Road, source).
    • old-fashioned treats at Tiong Bahru Galicier (55 Tiong Bahru Rd).
  • Chinatown
    • Pek Sin Choon Tea: Oldest team merchants.
    • Ang Mo Kio: Sri Mariamman Hindu temple.
    • Strangelets: quirky stuff from around the world.
    • 40 Hands: Allegedly one of most popular coffee joints.
    • BooksActually: Coolest book shop.
  • Keong Saik (next to Chinatown)
  • Everton park (old housing estate), new meets old
    • Coffee
    • Sweets
      • Grin Affair ( natural ingredients into glass jar creations.
      • Batterworks ( pastries.
      • Seriously ice scream (
      • Ji Xiang Confectionery ( Traditional glutinous sweets. (**)
    • Food
      • The Provision Shop (Blk 3 Everton Park): for a classic and affordable meal.
      • Chew the Fat (Blk 6 Everton Park): comfort food.
      • Eden's Kitchen ( healthy, green tea, coconut oil, etc.
  • Jalan Besar
  • Geylang (preserved shophouses and rich in Malay history)

02 December 2016 Email provider bookmarks

01 December 2016 Go snippets

Command-line flags

import (

type args struct {
      flag1  string
      flag2  string
        arg    string

func parseArgs() args {
      args := args{}

      flag.StringVar(&args.flag1, "flag1\n", "\n", "some flag 1 with sample `value`")
      flag.StringVar(&args.flag2, "flag2\n", "\n", "some flag 2 with sample `value`")

      flag.CommandLine.Usage = func() {
          fmt.Fprintf(os.Stderr, "Usage of %s:\n\n", os.Args[0])
          fmt.Fprintf(os.Stderr, "\n  myarg\n\n")


      args.arg = flag.Arg(0)

      if args.flag1 == "" || args.flag2 == "" || args.arg == "" {
      return args

func main() {
        args := parseArgs()
        fmt.Printf("Args: %#v\n", args)

go run main.go -flag1 val1 -flag2 val2 arg

01 December 2016 Javascript snippets

27 November 2016 Sydney travel bookmarks

16 October 2016 Laos travel bookmark

08 October 2016 Singapore travel bookmarks

01 October 2016 Cambodia travel bookmarks

  • Pub Street (Siem Reap, Cambodia).

01 October 2016 New York travel bookmarks

18 September 2016 API design bookmarks

18 September 2016 Handy pdf utilities

Straight out of How (and why) I made a zine, some handy utilities for generating pdfs…

Convert pngs to pdfs

# start with a bunch of PNG images of your zine pages
# convert them all to PDF
for i in *.png
      # imagemagick is the best thing in the world
      convert $i $i.pdf

Combine pdfs

Combine pdfs using pdftk:

pdftk *.pdf cat output zine.pdf

Combine pdfs using poppler:

pdf unite PDF1.pdf PDF2.pdf PDF3.pdf

Reorder pdf pages

# pdfmod is a GUI that lets you reorder pages
pdfmod zine.pdf

Add margins to pdf

# pdfcrop lets you add margins to the pdf. this is good because otherwise the
# printer will cut off stuff at the edges
pdfcrop --margin '29 29 29 29' zine.pdf zine-intermediate.pdf

Turn pdf into booklet

# pdfjam is this wizard tool that lets you take a normal ordered pdf and turn
# it into something you can print as a booklet on a regular printer.
# no more worrying about photocopying machines
pdfjam --booklet true --landscape --suffix book --letterpaper --signature 12 --booklet true --landscape zine-intermediate.pdf -o zine-booklet.pdf

15 September 2016 Fuzzy search Emacs compile history

I wrote about searching bash history with Emacs Helm some time ago. Since then, I've learned about completing-read to generically handle simple Emacs completions (very handy for supporting Helm, Ivy, and Ido completions).

Here's a simple way to combine completing-read and the compile command to enable fuzzy searching your compile history:


(defun ar/compile-completing ()
  "Compile with completing options."
  (let ((compile-command (completing-read "Compile command: " compile-history)))
    (compile compile-command)
    (add-to-list 'compile-history compile-command)))

05 September 2016 Jumping on the Emacs 25 bandwagon

Can't miss out on all the new fun. Emacs 25 RC2 is out and lots of people already using it. Since I'm mostly on MacOS these days, installing via homebrew with –devel, gets you RC2:

brew install emacs --devel --with-cocoa --with-gnutls --with-librsvg --with-imagemagick


The only hiccup so far's been org mode failing to export, which was fixed by re-installing it (follow this thread).

31 July 2016 San Francisco's Mission District travel bookmarks

  • Atlas Cafe.
  • Blue Bottle Coffee.
  • Cafe la Boheme.
  • Clarion Alley.
  • Coffee Bar.
  • Dynamo donut & coffee.
  • Four Barrel Coffee.
  • Grand Coffee.
  • Haus Coffee.
  • Kafe 99.
  • Linea cafe.
  • Mission skateboards.
  • Nakamoto's Bitcoin shop.
  • Philz Coffee.
  • Ritual Coffee roasters.
  • Rodger's coffee & tea.
  • Sightglass Coffee.
  • Stable Cafe.
  • Sugar lump coffee lounge.

25 July 2016 Moscow travel bookmarks

24 July 2016 Vietnam travel bookmarks

updated: 29 November 2019

19 July 2016 Pokémon Go bookmarks

03 July 2016 Coffee bookmarks

03 July 2016 Machine learning bookmarks

17 June 2016 Emacs and emotional vocab

Having read Are You in Despair? That’s Good, I was encouraged to expand my emotional vocabulary. As a zone.el fan (checkout nyan, sl, and rainbow), I looked into writing a zone program. When zone-when-idle is set, zone acts as a screensaver of sorts. We can use this to display random emotional vocab whenever Emacs is idle for a period of time. Let's get to it…

Zone keeps a list of programs to choose from when kicked off. Below is a basic zone-hello program, along with an interactive command for previewing. Not much to these. The tiny program prepares the screen for zoning and inserts text while no input is pending.

(defun zone-hello ()
  (setq mode-line-format nil)
  (zone-fill-out-screen (window-width) (window-height))
  (delete-region (point-min) (point-max))
  (goto-char (point-min))
  (while (not (input-pending-p))
    (insert "hello zone\n")
    (zone-park/sit-for (point-min) 0.2)))

(defun zone-hello-preview ()
  (let ((zone-programs [zone-hello]))

Here's what zone-hello looks like:


Back to improving our emotional vocabulary, we'll need a dictionary for our goal. A quick search yields a potential list of words. We can use WordNet to define them while offline. These two sources will do for now. We tie it all together in zone-words.el and the resulting zone program looks as follow:


UPDATE: Just came across Animations With Emacs. A post with awesome zone examples.

10 May 2016 Emacs: Find number of days between dates

Needed to find the number of days between two dates. Emacs calendar must know this…

  • Fire up the manual (M-x info-emacs-manual or C-h r).
  • Info-goto-node (or g).
  • Type "counting days" and voilá:

To determine the number of days in a range, set the mark on one date using `C-<SPC>', move point to another date, and type `M-=' (`calendar-count-days-region'). The numbers of days shown is inclusive; that is, it includes the days specified by mark and point.


Note: you can use the mouse to jump to another date, or "g d" (calendar-goto-date).

08 May 2016 RoutingHTTPServer snippet

RoutingHTTPServer snippet:

RoutingHTTPServer *routingHTTPServer = [[RoutingHTTPServer alloc] init];
[routingHTTPServer setPort:8000];
[routingHTTPServer setDefaultHeader:@"Server" value:@"YourAwesomeApp/1.0"];
[routingHTTPServer handleMethod:@"GET"
                          block:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:@"Hello!"];
NSError *error = nil;
if (![routingHTTPServer start:&error]) {
  NSLog(@"Error starting HTTP Server: %@\n", error);

06 May 2016 Alaska travel bookmarks

  • Anchorage.
  • Denali NP.
  • Exit Glacier / Kenai Fjord NP.
  • Ice Falls Hike.
  • Iditarod race husky camp.
  • Seward: Kenai Fjord Wildlife cruise (Major Marine cruises).
  • Talkeetna fishing.

06 May 2016 UIViewController bookmarks

03 May 2016 When OOO impulse kicks in…

  • You start moving trivial bits of code into classes, with the anticipation that you might use it one day. Stop.
  • On naming, semantic clarity trumps brevity. Yup, the verbosity may be worth it.

02 May 2016 Pakistan travel bookmarks

  • Lahore.
  • Karachi.
  • Rabelpindi.

02 May 2016 Money bookmarks

updated: 23 November 2021

02 May 2016 Scotland travel bookmarks

02 May 2016 St. Petersburg travel bookmarks

02 May 2016 8 week half-marathon training

An 8-week training schedule:

1 Rest 5 Km 5 Km Cycle Rest 5 Km 8 Km 9 Km
    29:56 29:54     29:45 1:00:55
2 Rest 7 Km 5 Km Cycle Rest 5 Km 10 Km
    41:36 27:52     28:23 59:17
3 Rest 8 Km 8.1 Km 5 Km Cycle Rest 5 Km 12 Km
    49:29 29:33     27:50 1:06
4 Rest 8 Km Rest 8 Km Rest 5 Km 14 Km
    46:39   49:28   29:40  
5 Rest 8 Km Rest 8 Km Rest 6 Km 16 Km 10 Km
    48:50         53:38
6 Rest 8 Km 8 Km 8 Km Rest 8 Km 19 Km
        51:39   37:09 2:02
7 Rest 8 Km Rest 12 Km Rest 8 Km 16 Km
8 Rest 8 Km Rest 5 Km 5 K Rest Race

02 May 2016 Haskell bookmarks

17 April 2016 Haskell notes

Referential transparency

An expression consistently evaluating to the same result, regardless of context.

28 March 2016 Emacs Objective-C tagging with RTags

Install libclang on Mac

brew install llvm --with-clang

Install RTags

git clone --recursive
cd rtags
cmake -DCMAKE_PREFIX_PATH=/Users/your-user-name/homebrew/opt/llvm -DCMAKE_EXPORT_COMPILE_COMMANDS=1 .

Start RTags daemon

path/to/rtags/bin/rdm 2> /tmp/rdm.log

Compilation database

Install xctool

brew install xctool

Generate a compilation database

cd path/to/your/objc-project
xctool -sdk iphonesimulator -arch x86_64 -scheme SomeScheme -reporter pretty -reporter json-compilation-database:compile_commands.json clean build

Load compilation database

path/to/rtags/bin/rc -J path/to/your/objc-project/compile_commands.json

Install RTags Emacs package

(use-package rtags :ensure t
  (setq rtags-use-helm t) ;; Optional. Enable if helm fan (I am!).
  (setq rtags-path "path/to/rtags/bin/"))

Ready to go

Use any of the rtags interactive commands. For example:

M-x rtags-find-symbol

10 March 2016 Database bookmarks

06 March 2016 Python tips backlog

05 March 2016 Bruges travel bookmarks

02 March 2016 Emacs lisp snippets

cl-loop for in

(cl-loop for day in '("mon" "tue" "wed" "thu" "fri" "sat" "sun")
         do (print day))








cl-loop for from to

(cl-loop for x from 1 to 5
         do (print x))






pcase literal matching

(pcase "word"
  ('word (message "Matched 'word symbol"))
  ("word" (message "Matched \"word\" string")))
Matched "word" string

Avoid nesting with the help of thread-first and thread-last.

(thread-last "12.....34"
  (string-remove-prefix "1")
  (string-remove-suffix "4"))

Find file upwards, up parents, up hierarchy

(locate-dominating-file FILE NAME)

Find executable in PATH

(executable-find COMMAND)

Read string with completion (helm/ido/ivy friendly)


Execute command/process and return list (similar to shell-command-to-string)

(process-lines PROGRAM &rest ARGS)

Iterating org buffer

(org-element-map (org-element-parse-buffer) '(headline link)
  (lambda (element)
     ((and (eq (org-element-type element) 'headline)
           (= (org-element-property :level element) 1))
      (print "headline"))
     ((eq (org-element-type element) 'link)
      (print "link")))

18 February 2016 Some modern Objective-C idioms

NSNumber literals

NSNumber *number1 = @1024;
NSNumber *number2 = @1024.123f;
NSNumber *number3 = @'A';
NSNumber *number4 = @YES;
NSNumber *number5 = @24ul; // Unsigned long.
NSNumber *number6 = @123456ll; // Long Long.
NSNumber *number7 = @5050.50; // Float.
NSNumber *number8 = @1543; // Integer
NSNumber *number9 = @111.456; // Double

Array literals

NSArray *names = @[@"John\n", @"Peter\n", @"Jaye\n", @"George\n", @"Max"];
NSArray *mutableNames = [@[@"John\n", @"Peter\n", @"Jaye\n", @"George\n", @"Max"] mutableCopy];

16 February 2016 Cross-platform development bookmarks

15 February 2016 Generating a random MAC address

As some point I had to generate a random MAC address. This is the snippet I used:

import random

def randomMAC():
  mac = [0x00, 0x16, 0x3e,
         random.randint(0x00, 0x7f),
         random.randint(0x00, 0xff),
         random.randint(0x00, 0xff),
  return ':'.join(map(lambda x: "%02x" % x, mac))

print 'MAC => %s' % randomMAC()
MAC => 00:16:3e:7e:f7:fa

14 February 2016 Defined elisp variables matching regexp

You can use "M-x apropos-variable" to get documentation for variables matching a pattern. For more flexibility, some elisp can help with getting a list of all variables matching a regexp:

(defun ar/variables-matching-pattern (pattern)
  "Get a list of all variables matching PATTERN."
  (let ((matched-variables '()))
     (lambda (symbol)
       ;; Symbol is variable?
       (when (and (boundp symbol)
                  (string-match pattern (symbol-name symbol)))
         (add-to-list 'matched-variables symbol))))

(let ((variables ""))
  (mapc (lambda (variable-symbol)
          (setq variables
                (concat variables
                        (format "%s => %s\n"
                                (symbol-name variable-symbol)
                                (symbol-value variable-symbol)))))
        (ar/variables-matching-pattern "^tern-.*"))
tern-mode-keymap => (keymap (3 keymap (4 . tern-get-docs) (3 . tern-get-type) (18 . tern-rename-variable)) (27 keymap (44 . tern-pop-find-definition) (67108910 . tern-find-definition-by-name) (46 . tern-find-definition)))
tern-update-argument-hints-async => nil
tern-known-port => nil
tern-mode => nil
tern-activity-since-command => -1
tern-project-dir => nil
tern-last-point-pos => nil
tern-last-completions => nil
tern-explicit-port => nil
tern-idle-time => 2.5
tern-find-definition-stack => nil
tern-last-argument-hints => nil
tern-idle-timer => nil
tern-server => nil
tern-last-docs-url => nil
tern-buffer-is-dirty => nil
tern-command-generation => 0
tern-flash-timeout => 0.5
tern-update-argument-hints-timer => 500
tern-mode-hook => nil
tern-command => (tern)

13 February 2016 Proselint via Emacs flycheck

Based on Linting Prose in Emacs

Needs proselint installed:

pip install proselint

Also needs a flycheck checker defined:

(flycheck-define-checker proselint
  "A linter for prose."
  :command ("proselint" source-inplace)
  ((warning line-start (file-name) ":" line ":" column ": "
            (id (one-or-more (not (any " "))))
            (message) line-end))
  :modes (gfm-mode

(add-to-list 'flycheck-checkers 'proselint)

11 February 2016 Generate go struct definition from json file

From Generate go struct definition from json file, and before I forget:

curl http://url.tld/file.json | gojson -name=Repository

11 February 2016 Doh! undo last commit (Magit edition)

I previously noted how to undo your last git commit (ie. soft reset). Using Magit:

  1. M-x magit-log-current.
  2. Move point to prior revision.
  3. M-x magit-reset-soft (defaults to revision at point).

Or if you want a single function:

(require 'magit)

(defun ar/magit-soft-reset-head~1 ()
  "Soft reset current git repo to HEAD~1."
  (magit-reset-soft "HEAD~1"))

06 February 2016 Redux bookmarks

06 February 2016 Javascript tips backlog

updated: 13 February 2016

06 February 2016 Emacs lisp tips backlog

updated: 27 December 2018

04 February 2016 Entering accents in Emacs

Via Irreal's Entering Accented Characters in Emacs, a reminder on how to enter accents using C-x 8. For example:

C-x 8 ' A -> Á

04 February 2016 Really delete iPhone photos

After deleting photos, go to:

Albums -> Recently Deleted -> Select -> Delete All

03 February 2016 Vancouver travel bookmarks

03 February 2016 Schnitzel recipe

Since eating at Fischers's, I've been inclined to make Schnitzel. This is my attempt.


  • Salt and ground black pepper.
  • All-purpose flour.
  • Eggs (beaten).
  • Bread crumbs (natural).
  • Oil.


  • Flatten the pork/chicken/veal.
  • Season (salt and pepper).
  • Heat pan with a generous amount of oil.
  • Dip into flour -> egg -> bread crumbs.


  • Anchovies.
  • Capers.



03 February 2016 Hot reloading with react and redux

By Robert Knight (@robknight_).


03 February 2016 Converting Unix epoc time to human readable date


date -d @192179700
Tue Feb  3 07:15:00 GMT 1976


date -r 192179700
Tue Feb  3 07:15:00 GMT 1976

03 February 2016 Objective-C bookmarks

02 February 2016 Timesinking bookmarks

02 February 2016 Suspend and reattach processes

Via climagic's Suspend and reattach a process to screen:

longcmd ; [Ctrl-Z] ; bg ; disown ; screen ; reptyr $( pidof longcmd )

02 February 2016 Czech Republic travel bookmarks

02 February 2016 Meditation tips backlog

02 February 2016 Append jpegs in a video sequence

Via climagic's make slideshow from *.jpg:

for p in *.jpg; do
    ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi;

02 February 2016 Regular expressions bookmarks

02 February 2016 Typescript bookmarks

02 February 2016 Hiding HTML elements

Hide with display:none (exclude from layout) and visibility:hidden (include in layout).

01 February 2016 Echo Emacs keybiding from function name

Picked up via Emacs Redux's Display the Keybinding for a Command With Substitute-command-keys, with my own example:

(message (substitute-command-keys "Press \\[ar/ox-html-export] to export org file"))
Press <f6> to export org file

01 February 2016 Emacs dired for batch byte compilation

Recently updated org-mode and started seeing an invalid function error:

Error (use-package): ob :config: Invalid function: org-babel-header-args-safe-fn

Just learned dired enables you to mark files and byte compile via M-x dired-do-byte-compile.

29 January 2016 Serializing to JSON on iOS

NSDictionary *dictionary = @{
  @"key1" : @"val1\n",
  @"key2" : @"val2\n",
  @"key3" : @"val3\n",
  @"key4" : @"val4\n",
  @"key5" : @"val5\n",
  @"key6" : @"val6\n",
NSError *error;
NSData *jsonData =
    [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
if (error) {
  // noooooooooo!
NSString *json =
    [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

25 January 2016 Fischer's London: yes, but…


Step into a Viennese blast from the past. Beautiful setting and pleasant vibe. Ordered a dirty martini on the rocks, a bottle of Merlot, Käsespätzle (with bacon), and Wiener Schnitzel (with anchovy/capers/egg). All very tasty.


Surprisingly, desserts (Topfenstrudel, Berggasse and coffee) were nothing spectacular. Also not a cheap eat (£50 per person).


fischers-03.JPG fischers-04.JPG fischers-05.JPG fischers-06.JPG fischers-07.JPG fischers-08.JPG fischers-09.JPG fischers-10.JPG fischers-11.JPG fischers-12.JPG

25 January 2016 Polar travel bookmarks

24 January 2016 Sweden travel bookmarks

20 January 2016 Handwriting bookmarks

20 January 2016 Chocolate fondant recipe

My girlfriend recently made a delicious chocolate fondant. Saving the The Guardian's recipe:

Ingredients (2 servings)

  • 60g unsalted butter, cut into dice, plus extra to grease
  • 1 tbsp cocoa powder
  • 60g dark chocolate, broken into pieces
  • 1 egg and 1 egg yolk
  • 60g caster sugar
  • 1 tbsp plain flour


  1. Pre-heat the oven to 200C if cooking immediately, and put a baking tray on the middle shelf. Butter the inside of 2 small ramekins or pudding moulds, and then put the cocoa in one and turn it to coat the inside, holding it over the second mould to catch any that escapes. Do the same with the other mould.
  2. Put the butter and chocolate into a heatproof bowl set over, but not touching, a pan of simmering water and stir occasionally until melted. Allow to cool slightly.
  3. Vigorously whisk together the egg, yolk, sugar and a pinch of salt until pale and fluffy. Gently fold in the melted chocolate and butter, and then the flour. Spoon into the prepared moulds, stopping just shy of the top – at this point the mixture can be refrigerated until needed, or even frozen, as the puddings will not wait around once cooked.
  4. Put on to a hot baking tray and cook for 12 minutes (14 if from cold, 16 if frozen) until the tops are set and coming away from the sides of the moulds. Leave to rest for 30 seconds and then serve in the ramekins or turn out on to plates if you're feeling confident – they're great with clotted cream or plain ice cream.

20 January 2016 Parenting bookmarks

updated: 03 July 2021

19 January 2016 Ippudo London: yes, but…


Central St. Giles location. Ordered a Kirin Ichiban beer and a Spicy Tonkotsu with a seasoned boiled egg. Awesome medium-spice broth, tasty egg and firm noodles. Got additional noodles for £1.50.


The space feels soulless. Think generic, chain, Pizza Express…


ipuddo_00.JPG ipuddo_01.JPG ipuddo_02.JPG ipuddo_03.JPG ipuddo_04.JPG ipuddo_05.JPG ipuddo_06.JPG ipuddo_07.JPG

19 January 2016 Added Emacs zone-rainbow

kawabata's zone-rainbow popped up on melpa today. Added to zone-programs. Just because :)

(use-package zone-rainbow :ensure t
  :after zone
  (setq zone-programs (vconcat [zone-rainbow] zone-programs)))


19 January 2016 Safari's Web Inspector keyboard shortcuts

Via WebKit's blog, Web Inspector Keyboard Shortcuts:

  • ⌃⌘Y or ⌘\ continue.
  • F8 or ⇧⌘; step out.
  • F7 or ⌘; step in.
  • F6 or ⌘’ step over.

14 January 2016 Copenhagen travel bookmarks

updated: 01 September 2019

12 January 2016 Import UIKit for simpler debugging

I bookmarked An @import-ant Change in Xcode and immediately forgot about it. The gist is to import UIKit to simplify inspecting objects during an lldb session:

(lldb) expr @import UIKit

Shorten typing by creating aliases in ~/.lldbinit:

command alias uikit expr @import UIKit
command alias foundation expr @import Foundation

12 January 2016 iOS development tips backlog

updated: 12 January 2016

11 January 2016 Basic Emacs keybindings on Linux desktop

Miss C-a, C-e in your browser and other Linux apps? You can enable the GTK Emacs key theme:

$ gsettings set org.gnome.desktop.interface gtk-key-theme "Emacs"

or if on Cinnamon:

$ gsettings set org.cinnamon.desktop.interface gtk-key-theme Emacs

If your desktop environment is not running gnome-settings-daemon, start it with:

$ gnome-settings-daemon

More at Emacs Keybindings in Chrome Without Gnome and How to get Emacs key bindings in Ubuntu.

08 January 2016 Emacs Objective-C completion with Irony

Install libclang on Mac

brew install llvm --with-clang

Configure Emacs

(use-package irony :ensure t
  (add-hook 'objc-mode-hook 'irony-mode)
  (add-hook 'irony-mode-hook 'irony-cdb-autosetup-compile-options))

(use-package company-irony :ensure t
  (add-hook  'objc-mode-hook (lambda ()
                               (setq-local company-backends '((company-irony)))))
  (add-hook 'irony-mode-hook 'company-irony-setup-begin-commands))

install irony server


M-x irony-install-server

NOTE: Needs libclang: Install with "brew install llvm –with-clang" By default, irony-install-server did not find libclang on Mac OS. irony-install-server invokes cmake for you. Work around by adding:


For example:

cmake -DCMAKE_PREFIX_PATH=/Users/your-user-name/homebrew/opt/llvm -DCMAKE_INSTALL_PREFIX\=/Users/your-user-name/.emacs.d/irony/ /Users/your-user-name/.emacs.d/elpa/irony-20160106.1223/server && cmake --build . --use-stderr --config Release --target install

Compilation database

Install xctool

brew install xctool

Generate compilation database

xctool -sdk iphonesimulator -arch x86_64 -scheme SomeScheme -reporter pretty -reporter json-compilation-database:compile_commands.json clean build

Set Irony's database path

M-x irony-cdb-json-add-compile-commands-path

07 January 2016 Finland travel bookmarks

updated: 13 October 2018

07 January 2016 Northern lights travel bookmarks

updated: 07 January 2016

06 January 2016 Mexico travel bookmarks

03 January 2016 Emacs highlight-symbol-mode

Been a fan of highlight-thing-mode. It automatically highlights all instances of symbol at point. Today, I gave highlight-symbol a try. Similar concept, but also adds the ability to jump to next/previous instances of symbol at point.

(use-package highlight-symbol :ensure t
  (set-face-attribute 'highlight-symbol-face nil
                      :background "default"
                      :foreground "#FA009A")
  (setq highlight-symbol-idle-delay 0)
  (setq highlight-symbol-on-navigation-p t)
  (add-hook 'prog-mode-hook #'highlight-symbol-mode)
  (add-hook 'prog-mode-hook #'highlight-symbol-nav-mode))


03 January 2016 Gandhi's ever-contemporary wisdom


"I do get angry, but I feel angry with myself for it. Full conquest of anger is possible only through self-realization. We should love even those who have the worst opinion of us. This is ahimsa, the rest is only ignorance."

Bad handwriting

"I am now of opinion that children should first be taught the art of drawing before learning how to write. Let the child learn his letters by observation as he does different objectives, such as flowers, birds, etc., and let him learn handwriting only after he has learned to draw objects."

Conduct of the Ashram

"Service without humility is selfishness and egotism."


"There is a great deal of truth in the saying that man becomes what he eats. The grosser the food, the grosser the body."


"There are chords in every human heart. If we only know how to strike the right chord, we bring out the music."

Moral law

The law of truth and love.

Renouncing or forgoing

Nishkulanand sings: "Renunciation of objects, without the renunciation of desires, is short-lived, however hard you may try."


"Man spoils matters much more by speech than by silence."


"Every minute that runs to waste never returns. Yet, knowing this, how much time do we waste?"

The palate

"Turn to the birds and beasts, and what do you find? They never eat merely to please the palate, they never go on eating till their inside is full to overflowing. And yet, we regard ourselves as superior to the animal creation!"

Vow of Swadeshi

"The person who has taken the vow of swadeshi will never use articles which conceivably involve violation of truth in their manufature or on the part of their manufacturers."

02 January 2016 Functional programming bookmarks

02 January 2016 9 Productivity tips

From HBR's 9 Productivity Tips from People Who Write About Productivity:

  1. Block time away from reactive tasks (email).
  2. Business = wasted energy.
  3. Exercise, sleep, and 90 minute work bursts.
  4. Incomplete tasks prompt healthy thinking out of context.
  5. Time off or stepping back is invaluable.
  6. Genuinely help were most successful/enjoyable.
  7. Plan for saying no while highlighting priority and seeking feedback.
  8. Measure important behavior change.
  9. Make time now (automate, simplify, etc.).

01 January 2016 First meal of 2016


  • 1 teaspoon of salt.
  • 1.5 cups of milk.
  • 2 cups of flour.
  • 2 eggs.
  • 2 tablespoons sugar.
  • 4 tablespoons of melted butter.
  • 6 teaspoons of baking powder.

Makes 10/11 pancakes.


01 January 2016 Last meal of 2015

For our last meal of 2015, I contributed dal and rotis. This is my first attempt at making either one of these. Both recipes based on Anupy Singla's Indian for Everyone.

Dal Makhani (Buttered black lentils)

dal-grid.png dal.jpg


roti-grid.png roti.jpg

30 December 2015 Find in $PATH with type and which

I typically use which to figure out the first binary found in $PATH:

which -a emacsclient

I always forget about type though:

type -a emacsclient
emacsclient is /Users/user/homebrew/bin/emacsclient
emacsclient is /usr/bin/emacsclient

30 December 2015 npm basics

Global vs local package installation location




View npm config

npm config list
; cli configs
user-agent = "npm/2.14.2 node/v4.0.0 darwin x64"

; node bin location = /Users/user/.nvm/versions/node/v4.0.0/bin/node
; cwd = /Users/user/stuff/active/blog
; HOME = /Users/user
; 'npm config ls -l' to show all defaults.

Get config value

npm config get prefix

Set config value

npm config set prefix=$HOME/some/location

Install package globally

node install --global <package-name>


node install -g <package-name>

List global packages

npm list --global

You can also use –depth=0 to make less verbose.

├─┬ babel-eslint@4.1.3
│ ├── acorn-to-esprima@1.0.4
│ ├─┬ babel-core@5.8.25
│ │ ├── babel-plugin-constant-folding@1.0.1
│ │ ├── babel-plugin-dead-code-elimination@1.0.2

Install local package

npm install <package-name> --save

–save will add <package-name> dependency to your package.json.


Uninstall package

npm uninstall <package-name>

Install package at version

npm install <package-name>@1.7.0

Search packages

npm search linter

Online documentation

Online documentation is great so far. More at

25 December 2015 Clojure bookmarks

21 December 2015 Mac OS X tips backlog

updated: 06 March 2016

20 December 2015 Search bash history with Emacs helm

Following up from changing CWD with helm projectile, here's a way to search your bash history with helm:


(defun ar/helm-helm (title candidates on-select-function)
  (helm :sources `((name . ,title)
                   (candidates . ,candidates)
                   (action . ,on-select-function))
        :buffer "*helm-exec*"
        :candidate-number-limit 10000))

(defun ar/shell-send-command (command)
  "Send COMMAND to shell mode."
  (assert (string-equal mode-name "Shell") nil "Not in Shell mode")
  (goto-char (point-max))
  (insert command)

(defun ar/helm-shell-search-history ()
  "Narrow down bash history with helm."
  (assert (string-equal mode-name "Shell") nil "Not in Shell mode")
  (ar/helm-helm "bash history"
                  (insert-file-contents "~/.bash_history")
                    (split-string (buffer-string) "\n"))))

Bonus: Replace existing M-r binding to use ar/helm-shell-search-history.

(bind-key "M-r" #'ar/helm-shell-search-history shell-mode-map)

19 December 2015 Medicine bookmarks

19 December 2015 View DICOM files from your X-ray

Got a CD with my chest X-ray from the hospital. Was expecting a pdf or an image of sorts, but the CD content was rather different. For starters, it was targeted at Windows users (AUTORUN.INF, MediaViewerLauncher.EXE and a bunch of DLLs):

$ find . -exec file --mime-type '{}' \;

./AUTORUN.INF: text/plain
./DICOMDIR: application/dicom
./MediaViewerLauncher.EXE: application/octet-stream
./Libraries/BASEPRINTER.DLL: application/octet-stream
./Libraries/CDDATABURNER.DLL: application/octet-stream
./Libraries/COM.DLL: application/octet-stream
./Libraries/ACE.DLL: application/octet-stream
./Libraries/ACE_SSL.DLL: application/octet-stream
./Libraries/ATL90.DLL: application/octet-stream
./DICOM/PAT_0000: application/x-directory
./DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001: application/dicom
./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001: application/dicom
./DICOM/PAT_0000/STD_0000/SER_0002/OBJ_0001/ED_0001: application/dicom
./Worklist/ClinicalInfo/067eccde-b299-e511-9114-005056ad3afe.mht: text/html
./Worklist/Report/067eccde-b299-e511-9114-005056ad3afe.mht: text/html
./Worklist/Worklist.wl: application/octet-stream

I'm on a Mac, so most of these files were not useful to me. The more interesting files were IM_0001 and ED_0001 with "application/dicom" MIME type. DICOM files stand for Digital Imaging and Communications in Medicine. How to view these on a Mac? OsiriX viewer is an option. OsiriX, though on the heavy side (100.7MB download), it rendered the X-ray successfully.


Unsurprisingly, ImageMagick's convert utility also handles DICOM files. Converting to PNG worked well.

$ convert ./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001 ED_0001.png


DICOM files also hold patient's metadata and optional reports. The file format is well known. OsiriX gives you access to it, but a few lines of python can also extract it for you. First install the pydicom package:

$ sudo pip install pydicom

Running the python interpreter is enough to peak at the metadata:

>>> import dicom
>>> ds = dicom.read_file("./DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001")
>>> ds
(0008, 0000) Group Length                        UL: 400
(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'
(0008, 0016) SOP Class UID                       UI: Computed Radiography Image Storage
(0008, 0020) Study Date                          DA: '20151203'
(0008, 0021) Series Date                         DA: '20151203'
(0008, 0023) Content Date                        DA: '20151203'
(0008, 0030) Study Time                          TM: '120519.000000'
(0008, 0031) Series Time                         TM: '120520.000000'
(0008, 0033) Content Time                        TM: '120643.000000'
(0008, 0060) Modality                            CS: 'CR'
(0008, 0070) Manufacturer                        LO: 'Canon Inc.'

There were other DICOM files with a report:

>>> import dicom
>>> ds = dicom.read_file("./DICOM/PAT_0000/STD_0000/SER_0001/OBJ_0001/ED_0001")
>>> ds
(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'
(0008, 0016) SOP Class UID                       UI: Encapsulated PDF Storage
(0042, 0012) MIME Type of Encapsulated Document  LO: 'application/pdf'

DCMTK is another alternative tool to extract DICOM metadata. The source is available and can be built:

$ tar xf dcmtk-3.6.0.tar.gz
$ cd dcmtk-3.6.0
$ cmake .
$ make

Or installed via homebrew:

$ brew install dcmtk

DCMTK includes dcmdump. You can use it to dump DICOM files:

$ dcmdata/apps/dcmdump DICOM/PAT_0000/STD_0000/SER_0000/OBJ_0001/IM_0001
# Dicom-File-Format

# Dicom-Meta-Information-Header
# Used TransferSyntax: Little Endian Explicit
(0002,0000) UL 192                                      #   4, 1 FileMetaInformationGroupLength
(0002,0001) OB 01\00                                    #   2, 1 FileMetaInformationVersion
(0002,0002) UI =ComputedRadiographyImageStorage         #  26, 1 MediaStorageSOPClassUID
(0002,0003) UI [1.2.392.200046.] #  52, 1 MediaStorageSOPInstanceUID
(0002,0010) UI =LittleEndianExplicit                    #  20, 1 TransferSyntaxUID
(0002,0012) UI []               #  24, 1 ImplementationClassUID
(0002,0013) SH [PhilipsISPACS445]                       #  16, 1 ImplementationVersionName

Of interest, David Clunie's Medical Image Format Site.

18 December 2015 Tip: GOOGLETRANSLATE your Spreadsheet

Examples from reference:

=GOOGLETRANSLATE("Hello World\n","en\n","es")

18 December 2015 Organize your data with camlistore

Checking out camlistore to organize all sorts of data. Scaleway enables you to deploy camlistore servers.

17 December 2015 Maps dev bookmarks

17 December 2015 Use ImageMagick to convert image to grayscale

Another ImageMagick one-liner I'll likely forget.

mogrify -type Grayscale image.png

14 December 2015 Drill down Emacs dired with dired-subtree

JCS, from Irreal, recently highlighted fuco's dired-hacks. dired-subtree is super handy for drilling subdirectories down. Bound <tab> and <backtab> to toggle and cycle subtrees.

(use-package dired-subtree :ensure t
  :after dired
  (bind-key "<tab>" #'dired-subtree-toggle dired-mode-map)
  (bind-key "<backtab>" #'dired-subtree-cycle dired-mode-map))


14 December 2015 GPG (GnuPG) examples

Generate key

gpg --full-generate-key

Export private key

gpg --export-secret-key -a <keyid> > <private.asc>

Import key

gpg --import < <private.asc>

Delete public key

gpg --delete-keys <keyid>

Delete private key

gpg --delete-secret-keys <keyid>

Edit key

gpg --edit-key <keyid>
gpg> uid (lists IDs)
gpg> uid 2 (marks ID)
gpg> deluid (deletes marked ID)
Really remove this user ID? (y/N) y

Change passphrase of the secret key

gpg --edit-key Your-Key-ID-Here
gpg> passwd
gpg> save

14 December 2015 CSS bookmarks

12 December 2015 Resume partial downloads with ssh and rsync

rsync --rsync-path=/usr/local/bin/rsync \
      --partial \
      --progress \
      --rsh=ssh \
      john@host:/path/to/file \

12 December 2015 Emacs text faces

  • Text faces = Text styles.
  • Face attributes: font, height, weight, slant, foreground/background color, and underlining or overlining.
  • Font lock mode automatically assigns faces to text.
  • M-x list-faces-display: Shows faces defined.
  • M-x helm-colors: Also handy.
  • Unspecified attributes are taken from 'default' face.

08 December 2015 Preview HTML pages on github

07 December 2015 Flutter setup

Based on Getting Started with Flutter.

$ curl -O
$ unzip
$ export PATH=`pwd`/dart-sdk/bin:$PATH

Verify with:

$ pub --version

07 December 2015 Playing with Dart's analysis server

Dart SDK ships with an analysis server. Very handy if you'd like to write a completion plugin for your favorite editor. The API is well documented. Of interest, there's, part of dartedit.

$ dart path/to/bin/snapshots/analysis_server.dart.snapshot  --sdk=path/to/dart-sdk

NOTE: The server reads requests from standard input. Either escape or execute the following as one-liner json requests.

  "id": "1\n",
  "method": "analysis.setAnalysisRoots\n",
  "params": {
    "included": [
    "excluded": []
  "id": "3\n",
  "method": "completion.getSuggestions\n",
  "params": {
    "file": "path/to/some/file.dart\n",
    "offset": 673

07 December 2015 Dart bookmarks

06 December 2015 Flutter bookmarks

06 December 2015 Swift bookmarks

updated: 23 November 2021

30 November 2015 Installing Emacs spaceline

Gave Spaceline a try. Spacemacs's powerline theme. Setup was super simple (Thanks Eivind Fonn and Sylvain Benner):

(use-package spaceline :ensure t
  (use-package spaceline-config
    (setq powerline-default-separator 'rounded)
    (setq spaceline-highlight-face-func 'spaceline-highlight-face-evil-state)
    (spaceline-define-segment line-column
      "The current line and column numbers."
      "l:%l c:%2c")
    (spaceline-define-segment time
      "The current time."
      (format-time-string "%H:%M"))
    (spaceline-define-segment date
      "The current date."
      (format-time-string "%h %d"))
    (spaceline-emacs-theme 'date 'time))


29 November 2015 package.el incomprehensible buffer

Came across "incomprehensible buffer" error in package.el. Workaround patch:

--- a/lisp/emacs-lisp/package.el
+++ b/lisp/emacs-lisp/package.el
@@ -1161,6 +1161,7 @@ package--with-work-buffer
(let* ((url (concat ,url-1 ,file))
       (callback (lambda (status)
                   (let ((b (current-buffer)))
+                    (goto-char (point-min))
                     (unwind-protect (wrap-errors
                                      (when-let ((er (plist-get
                                                      status :error)))
                                        (error "Error retrieving: %s %S" url er))

29 November 2015 Leading bookmarks

29 November 2015 Online reading backlog

updated: 21 May 2016

28 November 2015 Travel lifestyle bookmarks

26 November 2015 SQL bookmarks

26 November 2015 Unix/Linux tools bookmarks

updated: 23 November 2021

26 November 2015 Couchbase React Native bookmarks

26 November 2015 Installing Emacs 25 devel on Mac OS X


brew update
brew install emacs --HEAD --use-git-head --with-cocoa --with-srgb --with-gnutls
brew linkapps emacs


  brew update
  brew install emacs --devel --with-cocoa --with-srgb --with-gnutls
  brew linkapps emacs

Had problems loading seq. Removed byte-compiled packages:

$ find ~/.emacs.d/elpa -iname *.elc -exec rm '{}' \;

25 November 2015 Diagram tools bookmarks

24 November 2015 Licensing bookmarks

23 November 2015 Synology bookmarks

22 November 2015 Backup bookmarks

22 November 2015 Making hummus

Made hummus, based on Delicious Istanbul's 5 Secrets to Perfect Hummus (wayback machine) post.

  • 160 g dry chickpeas.
  • 4 cloves garlic minced.
  • 1 tsp fine sea salt.
  • 1 1/2 tbsp lemon juice.
  • 1/4 tsp ground cumin.
  • 6 tbsp tahini paste.
  • 2/3 cup cooking water.
  • Extra virgin olive oil, for serving.
  • Red pepper flakes, for serving.
  • Zahter mixture, for serving.
  • Soak chickpeas overnight.
  • Discard water and rinse chickpeas.
  • Cook in low heat (about 5 cups water) for 1.5 hours for until soft (but keeping shape.) Check if can be mashed with thumnb.
  • Save cooking water.
  • Peal chickpeas (optional).
  • Blend ingredients until silky paste. Taste and add lemon/salt/cooking water.

Keeps in fridge for 3-4 days. Freeze otherwise.

hummus-01.jpg hummus-02.jpg hummus-03.jpg hummus-04.jpg hummus-05.jpg hummus-06.jpg hummus-07.jpg hummus-08.jpg hummus-09.jpg

22 November 2015 Nara travel bookmarks

21 November 2015 Kubernetes bookmarks

21 November 2015 Docker bookmarks

21 November 2015 Angular bookmarks

21 November 2015 Mac OS bookmarks

21 November 2015 easy_install->pip->conda

Spotted Conda package manager. It handles python installations, in addition to package management. There's also a package index provided by Binstar. Installed Miniconda, the bare bones Conda environment.

Can't find a python package in Binstar? Here's a post on Using PyPi Packages with Conda. If that fails, you can try pip from your Conda python environment.

16 November 2015 Traditional music bookmarks

04 November 2015 Recover from an unresponsive Emacs

Wilfred Hughes has a handy tip to bail you out of a hung Emacs instance:

pkill -SIGUSR2 emacs

ps. Not had a chance to try it, but next time it happens…

25 October 2015 Training for under 50 min 10k run

Not much training time for an under 50 minute 10k run, but here's an attempt (based on time-to-run's sub-50):

Mon Tue Wed Thu Fri Sat Sun
Oct 26 Oct 27 Oct 28 Oct 29 Oct 30 Oct 31 Nov 1
    60 min 30 min 2k @ 4.55/k rest 105 min
        2 min rest    
      (repeat x 3)    
Nov 2 Nov 3 Nov 4 Nov 5 Nov 6 Nov 7 Nov 8
30 min 30 min 1k @ 4.50/k 30 min 30 min rest 5k @ 4.55/k
    90 sec rest        
    (repeat x 5)        
Nov 9 Nov 10 Nov 11 Nov 12 Nov 13 Nov 14 Nov 15
10k easy 30 min 1k @ 4.55/k 30 min 30 min rest race day
    1 min easy        
    (repeat x 3)        

25 October 2015 Reading a running training plan

A sample from Kona Part 2's comments:

2.5 w/u to 4x(1.25@11.5 w/0.25R@7) to 3x(3.75@10.5 w/0.5R@7) to 2.5 c/d.

Is read from left to right as:

2.5 mile warm up to four times through 1.25 miles at 11.5 miles per hour with 0.25 miles recovery at 7 miles per hour to three times through 3.75 miles at 10.5 miles per hour with 0.5 miles recovery at 7 miles per hour to 2.5 miles cool down.

23 October 2015 Find binary in PATH using python

import distutils.spawn
print distutils.spawn.find_executable('git')

22 October 2015 Indonesia travel bookmarks

22 October 2015 Malaysia travel bookmarks

22 October 2015 Mongolia travel bookmarks

22 October 2015 Running bookmarks

22 October 2015 Media player bookmarks

16 October 2015 UX toolbox bookmarks

08 October 2015 Change Emacs shell's CWD with helm projectile

If using Emacs shell and helm projectile, you can wire these up to quickly change your current working directory.


(require 'helm-projectile)

(defun ar/shell-cd (dir-path)
"Like shell-pop--cd-to-cwd-shell, but without recentering."
  (unless (string-equal mode-name "Shell")
    (error "Not in Shell mode"))
  (message mode-name)
  (goto-char (point-max))
  (insert (concat "cd " (shell-quote-argument dir-path)))
  (let ((comint-process-echoes t))

(defun ar/helm-projectile-shell-cd ()
  "Change shell current working directory using helm projectile."
  (unless (string-equal mode-name "Shell")
    (error "Not in Shell mode"))
  (let ((helm-dir-source (copy-tree  helm-source-projectile-directories-list)))
    (add-to-list 'helm-dir-source '(action . ar/shell-cd))
    (add-to-list 'helm-dir-source '(keymap . nil))
    (add-to-list 'helm-dir-source '(header-line . "cd to directory..."))
    (helm :sources helm-dir-source
          :buffer "*helm-dirs*"
          :candidate-number-limit 10000)))

07 October 2015 Thermostat reset on Bosch WKD28350GB

My Bosch washer/dryer (WKD28350GB) stopped drying recently. Resetting the dryer's thermostat red breaker did the trick.

WKD28350GB-01.jpg WKD28350GB-02.jpg WKD28350GB-03.jpg WKD28350GB-04.jpg

Edit: Similar post here.

05 October 2015 Javascript fetch node sample

Playing with node and fetch:

// Requisite: npm install node-fetch --save
// Save to fetch-demo.js
// Run: node fetch-demo.js

var fetch = require('node-fetch');

fetch("\n", {
  method: 'GET',
  timeout: 5000
}).then(function(response) {
  return response.json();
}).then(function(response) {
  console.log('subject: ' + response.subject);
  console.log('body: ' + response.body);
}).catch(function(reason) {

01 October 2015 Extract dominant colors in images

There's a handy HN post pointing to Javier López's Using imagemagick, awk and kmeans to find dominant colors in images. A comment also highlights color-extract, written in Go.

28 September 2015 Find a word with regex and WordNet

Recently wanted to come up with a random keyword. Querying WordNet and a regular expression did the job.

Installed WordNet on Mac:

$ brew install wordnet

Want a word ending in "esome"?

$ wn esome -grepn -grepv -grepa -grepr | egrep -o -e "\w*esome\b" | sort | uniq


26 September 2015 Soundcloud's Go best practices (GopherCon 2014)

Having watched the video, some takeaways:



Repo structure

  • Makefile
  • main.go
  • support.go
  • foo
    • foo.go
    • bar.go
  • whatever-server
    • main.go
  • wharever-worker
    • main.go

Formatting and style

Use gofmt.

Google's codereview guidelines.

Avoid named return parameters.

Avoid make and new (unless you know sizes).

Use struct{} for sentinel values: sets, signal chans.

  • Conveys no information in it this part.
  • Instead of empty interface.
  • instead of boolean.

Break long lines at parameters

  • No need to compact.
  • Keep trailing coma in last argument.


func main() {
  var (
    foo = flags.String("foo\n", "doch\n", "...")
    bar = flat.Int("bar\n", 34, "...")
  // ...


  • package log
  • Telemetry
  • Push model (gets expensive over time)
    • Graphite
    • Statsd
    • AirBrake
  • Pull model (chosen)
    • expvar
    • Prometheus


  • package testing
    • Unit tests
    • reflect.DeepEqual
  • Integration
    • Use flags for starting services
    • // +build integration

Code validation

  • On Save
    • Go fmt
    • Go import (go fmt++)
  • On Build
    • Go vet
    • Golint
    • Go test
  • On Deploy
    • go test -tags=integration
  • GoCov?

Dependency management

  • Unimportant projects
    • go get -d (and hope)
  • Important
    • VENDOR (ie. copy into your repo)
      • Git submodules (no!).
      • Git subtrees (seem OK).
      • Tool (godep?).
      • Build
      • For binaries (use _vendor subdir)

23 September 2015 Sync pip with Mac OS updates

My pip installation recently broke after a Mac OS update.

$ pip
Traceback (most recent call last):
  File "/usr/local/bin/pip\n", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\n", line 2793, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\n", line 673, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\n", line 576, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==1.1

Updating my pip installation fixes the break:

$ sudo easy_install -U pip

20 September 2015 Chinatown treats review

Recommended? yep

There's a corner in Chinatown hosting some truly superb treats. If you get caught in the rush between Newport court and Newport place, you'd likely fail to notice some the awesome street food stands.

chinatown.jpg newport-court.jpg

Chilly squid

I've walked past this place many times and never noticed it. They serve a handful of items, but the grilled chilly squid skewers caught my attention. They're grilled, brushed with chilly sauce and finished with sprinkled sesame and cumin seeds. Super tasty.


chilly-squid-1.jpg chilly-squid-2.jpg

Pancake + Crisp + Egg + Hot chillies = Jiān Bǐng 煎餅

I first had these delicious breakfast savory pancakes at a Beijing street food stall. Never expected to randomly find Jiān Bǐng in London. It's a crepe with an additional egg spread, hoisin sauce, chilly sauce, hot chillies, topped with spring onions and coriander, all wrapping a wonderfully crispy bread cracker. And.. it's awesome.


Tai Yaki

Chinatown Bakery is hard to miss. Pedestrian traffic slows down as we all fall under the spell of the Tai Yaki machine. This wonderful assembly line produces fish-shaped sweet waffles filled with custard. They are the perfect dessert after some savory street snacks. You can get a bag of 4 for £2.

fish-1.jpg fish-4.jpg

All near each other

All these delights are within a stone's throw away from each other.



Was this post useful to you? do reply!

Better suggestion?

London is full of overhyped, gimmicky, and unnecessarily expensive restaurants. Very few deliver truly awesome food (even those expensive ones). Got suggestions? I'd love to hear from you @xenodium.

18 September 2015 React bookmarks

updated: 12 July 2018