oft: Bash function for opening a specific filetype

Here’s another simple Bash function that I’ve used so much recently I thought I should share. It’s called oft, which stands for Open File Type, and can be used as a standalone shell script or as a function in your .bash_profile. When run, it looks in the current directory for files with extensions that match (or partially match) the first argument and opens them.

My most obvious use case is Xcode projects, where I may have dozens (and dozens) of files, but there’s only one .xcodeproj file (folder). I don’t always know the name of the project in the folder, but if I run oft xco it will open it without my having to search. If there is more than one result, it gives you a numeric menu to select the file you want to open. You can cancel, select a single file or “Open ALL” from that menu. If you run oft with no arguments, it will read a (partial) extension from a prompt.

This is a script born of laziness (so many good ones are, though). You can accomplish the same with an ls *.ext, spot the file and open filename.ext. This is just faster and better for me when I’m working with less-than-optimal amounts of sleep.

# Open filetype
# Finds every file in folder whose extension starts with the first parameter passed
# if more than one file of given type is found, it offers a menu
oft () {
  if [[ $# == 0 ]]; then
    echo -n "Enter an extension or partial extension: "
    read extension
  fi
  if [[ $# > 1 ]]; then
    echo "Usage: oft [(partial) file extension]"
    return
  fi
  extension=$1

  ls *.*$extension* > /dev/null
  if [[ $? == 1 ]]; then
    echo "No files matching \"$extension\" found."
    return
  fi
  declare -a fileList=( *\.*$extension* )

  if [[ ${#fileList[*]} -gt 1 ]]; then
    IFS=$'\n'
    PS3='Open which file? '
    select OPT in "Cancel" ${fileList[*]} "Open ALL"; do
      if [ $OPT == "Open ALL" ]; then
        read -n1 -p "Open all matching files? (y/N): "
        [[ $REPLY = [Yy] ]] && $(/usr/bin/open ${fileList[*]})
      elif [ $OPT != "Cancel" ]; then
        $(/usr/bin/open "$OPT")
      fi
      unset IFS
      break
    done
  else
    $(/usr/bin/open "${fileList[0]}")
  fi
}

OTask: CLI for OmniFocus

I’ve been sitting on this one for a while, until I got a request from Patrick regarding an OmniFocus CLI and LaunchBar. I thought it might be time to dig this up and post it.


A reader named Tony left a comment on my Duplicating Safari browsing sessions post, recommending that I try out appscript for my AppleScript bridging needs. I frequently use system calls to osascript to do this, and I’ve shied away from scripting bridges in the past because they make things much harder to share and distribute. I thought I’d give it a try, though.

I like it. I like it a lot. It’s frustrating that I can’t just hand you this script without a list of requirements and dependencies, but I’m going share it anyway, just to show off some of the appscript’s capabilities.

What I built was a CLI for OmniFocus. I had an AppleScript/Ruby monstrosity that actually worked with TaskPaper, The Hit List, Things and OmniFocus, but that one got out of hand. I took the good parts of it, concentrated on OmniFocus and converted it to appscript in short time. The result is OTask.

Requirements

You need a few things before this will even think about running for you. RubyGems is a must. I still haven’t figured out if that’s part of the default OS X install or not, but if you have Developer tools, you’ve got it. Then you need the ‘rb-appscript’ gem. You also need the gems ‘chronic’ and ‘amatch’. You can install each by using gem install gemname, and you may have to run the command with sudo, depending on your system’s permissions. If you’re still on board, here are the docs, and the script is on GitHub.

Documentation

OTask uses a custom syntax to allow entry of the various elements of an action in one line of text. The following formats can be used anywhere in the line, with the exception of the flag (!) which must be the last character on the line, preceded by a space.

  • @context (fragment, no spaces)
  • #project (fragment, no spaces)
  • due(due date) (can be shortened as d(date))
  • start(start date) (can be shortened as s(date))
  • (notes)
  • ! (sets task as flagged)

Contexts and project specifiers should not include spaces. The algorithm that is used will find the best match for the string you give it, so you only need to include enough of it to distinguish it from other contexts or projects. For example, if I were going to put an action directly into my Markdown QuickTags folder, I could just use “#mdqt” and it will find it. “@corr” will get me the “correspondence” context.

Dates are entered in natural language format. You can type “tomorrow,” “in 3 days,” “next tuesday,” etc. You can also use “+3” to set a date 3 days from the current day, “+7” for a week, and so on.

Command line options

-h, –help Displays help message
-q, –quiet Output as little as possible, overrides verbose
-V, –verbose Verbose output
-g, –growl Use Growl for feedback

Example usage

$ otask "Write a letter to mom"

This will put a task into your inbox with the name “Write a letter to mom.” Nothing else will be set, it will wait there for you to pick it up.

$ otask -g "Pick up the kids from school @err #single due(today 3pm) !"

This creates a new task in a project called Single Tasks, with a context of “errands”, a due date of 3pm on the current day, and flags the task.

The task will go to your inbox by default, and–if provided–project and context will be set. Your settings for automatic cleanup will determine what happens after that. Task elements not specified are left unset.

The -g parameter gives us our feedback via Growl, which is handy if you’re calling it from a background script or application launcher like Quicksilver or LaunchBar.

$ otask "Brainstorm for the morning meeting (Bill had some ideas, it might be worth checking in with him this afternoon) d(tomorrow 8am) #hipstartup @think"

This will create a task with a note. Everything in parenthesis is removed from the task name and placed into the notes of the action, sans parenthesis. Note that the due date prefix can be shortened to just “d,” (and the start date prefix can be just “s”).

OTask looks for notes in parenthesis, but it can also receive piped input from other applications as a note for the task. If you wanted to include text from a file, the output of a command or the plain-text contents of your clipboard, you can just pipe the output into the command, specifying the rest of the options as usual.

$ pbpaste - otask "Notes from the morning meeting @ref"

That would take the current contents of your clipboard and make them the attached note on the “Notes from the morning meeting” task (with the context “reference”).

Calling from LaunchBar (et al.)

You can do this with any app that can run a script with input, or call it from automated scripts if you could think of a reason to. Below is the AppleScript for a LaunchBar action. Create a new script in AppleScript Editor and paste the code in. Edit the path in the last function to point to wherever you put the otask script. Save the AppleScript as OTask.scpt in ~/Library/Application Support/LaunchBar/Actions.

You’ll find the Action in LaunchBar after it indexes. Type ‘ota’ (or as much as you need to get it to come up) and then press space bar. Use the syntax shown above to write out your action and its elements, but leave out the ‘otask’ part and any parameters. Hit return and Growl (you have it installed, right?) will tell you what’s up.

on handle_string(actionString)
	if (length of actionString is not 0) then
		my runRubyScript(actionString)
	end if
	open location "x-launchbar:hide"
end handle_string

on runRubyScript(action)
	set res to do shell script "$HOME/scripts/otask.rb -g \"" & action & "\""
end runRubyScript

Download

https://github.com/ttscoff/OTask

Web excursions: June 28, 2011 - June 30, 2011

Links of interest from June 28, 2011 through June 30, 2011:

Web excursions: June 15, 2011 - June 23, 2011

Links of interest from June 15, 2011 through June 23, 2011:

A Bash function for Markdown bloggers

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 () {
  WRITINGDIR="~/Dropbox/Writing"
  EDITCMD="mate"
  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
    else
      IFS=$'\n'
      PS3='Edit which file? (1 to cancel): '
      select OPT in "Cancel" $filelist; do
        if [ $OPT != "Cancel" ]; then
          $EDITCMD $OPT
        fi
        break
      done
    fi
  else
    return 1
  fi
  return 0
}
  1. I save drafts and posts to my desktop as .md files. During my daily review I use Tags.app 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.

Thanks WWDC

Photo of the TUAW Dev Interviews setup Thanks to everyone I met at WWDC this year and to the friends I got to see for a great time. San Francisco was as beautiful as ever and the Mac and iOS development communities are, as usual, full of new and brilliant ideas. It’s always heartening to see. TUAW and MacTech will be posting the result of our blogging work at WWDC over the next few weeks.

The Smile party was a blast, and thanks to Jean MacDonald and Smile for throwing such a great geekfest. The TUAW bash was a great time, too, and it was great to see some Apple employees show up (happens less often than you’d think). They were there with Daniel Jalkut, and it was great to finally meet him, too. Violet Blue, Jim Dalrymple, Manton Reese and more than I can remember right now, great to meet you all!

I’m headed back to Minnesota right now, and not looking forward to the two-hour drive I’ll be in for after landing. Then I’ll have about 5 days to get things in order at work, get nvALT 2.1 released and pack before I head off to a family reunion for almost a week. I seem to be moving around a lot for a grumpy homebody. Oh, well.

Feel free to browse my WWDC 2011 photos to see a bit of what went on.

Addendum

So I’m sitting and waiting for a tow truck to come start my car right now, and I realize I forgot to thank Victor Agreda, Jr.1 who instigated most of these meetings, kept me alive and introduced me to In-n-Out Burger. Thanks, Victor!

  1. See his amazing HTML1-compliant page for more info.

Web excursions: June 6, 2011 - June 8, 2011

Links of interest from June 6, 2011 through June 8, 2011:

Quick Tip: fixing the "other account" Mac App Store issue

I like the Mac App Store. I’ve purchased a lot of apps since it opened, and I dig the centralized update system. I’ve been having this issue on my MacBook Air, though, where trying to update an installed app would trigger a dialog which says “You have updates available for other accounts…” and suggest that I log in with that account to update my software. Thing is, I only have one Apple ID, one account.

After digging around and trying various things, I found this thread in the Apple Support Communities. The solution, buried in there somewhere, was to both repair disk permissions in Disk Utility and rebuild my Spotlight index. You can rebuild your index simply by adding your entire hard drive to the Privacy settings in Spotlight’s System Preferences panel and then removing it. You can do it from the command line or from a utility such as Cocktail1, too, but don’t make it complicated.

After doing both (in that order), I’ve been able to update without hassle. Somehow, it made LaunchBar stop indexing my applications, but I’ll figure that out when I have time…

  1. Cocktail’s a great utility app for cleaning up log files, caches, etc. and handling a gazillion system tasks and maintenance. Plus, it doesn’t mess up apps like 1Password the way that other “cleaning” apps tend to. Check it out.

Taking the Markdown to Evernote service further

Martin Kopischke has taken my little Markdown to Evernote Service and made it whole. I dropped the project pretty quickly as I stopped using Evernote as my primary storage for text notes, and I left it in pretty poor shape. Martin has fixed that.

The new Service adds way better tag handling, MultiMarkdown-style metadata hooks for Notebook, tags and more, and generally amped up the parser and error handling, as well as the Evernote side of things. Check it out at NSUserView. Thanks Martin, nice work!

Web excursions: May 24, 2011 - May 31, 2011

Links of interest from May 24, 2011 through May 31, 2011: