Markdown Typewriter ImageI store all of my writing as separate Markdown files. A basic tagging system1 adds more “searchability,” and I can quickly locate any file with Spotlight2. Given the amount of time I spend in Terminal (well, iTerm 2 these days), I use mdfind quite a bit to do the Spotlight searching. This function just makes it a little more convenient to search for and quickly edit an existing document.

By default, it looks in a Dropbox “Writing” folder, but you can adjust that to restrict to any folder at the top of the script. You can also set your edit command there (mate, mvim, vim, etc.). Then it takes all arguments and uses them as a Spotlight search, restricted to your writing folder and the Markdown filetype, and offers you a quick menu of matches. Selecting a match opens the file with your preferred editor. If there’s only one match, it’s opened automatically.

It’s written as a function to be included in your .bash_profile (or sourced from there). If you want to run it as a shell script, just remove the edmd () { at the top and the closing }, put it in your path and run chmod a+x filename.

Once it’s installed you can just type edmd keyword to find posts and drafts related to keyword. You can use multiple words (no quotes required) and prefixes like “keyword:” or “tag:”, just like a Spotlight query.

# Edit Markdown File from Writing directory
# Finds Markdown files matching a Spotlight-style search query
# If there's more than one, you get a menu
edmd () {
  filelist=$(mdfind -onlyin "$WRITINGDIR" "($@) AND kind:markdown")
  listlength=$(mdfind -onlyin "$WRITINGDIR" -count "($@) AND kind:markdown")
  if [[ $listlength > 0 ]]; then
    if [[ $listlength == 1 ]]; then
      $EDITCMD $filelist
      PS3='Edit which file? (1 to cancel): '
      select OPT in "Cancel" $filelist; do
        if [ $OPT != "Cancel" ]; then
          $EDITCMD $OPT
    return 1
  return 0
  1. I save drafts and posts to my desktop as .md files. During my daily review I use or Filr to quickly add target keywords (‘blogging’, a tag for which blog it’s for and one, maybe two topical tags). Hazel picks these up and stores them in my Dropbox “Writing” folder, in subfolders based on blog and filetype. 

  2. I never realized it, but apparently Spotlight doesn’t search these by default. My use of the QLMarkdown Quick Look plugin fixes that, I guess. 

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.