A couple of buddies had mentioned on the Interblags that they wished TextExpander supported what they dubbed “random snippets”. In a nut, they want to be able to type (using Shawn’s example) “ttypo” and have TextExpander choose a random snippet from a predefined list. This is something I’ve thought about in the past, but had never given a whole lot of thought. Thankfully, TextExpander can do this out of the box with a little scripting-fu.
Part of what makes TextExpander so badass is that, in addition to its normal text substitution capabilities, you can also have it run scripty things (either shell scripts or AppleScript). Because we have access to the shell, we also have access to a whole host of full-blown programming languages from within TextExpander. This particular capability is what helped me quickly (like, in under five minutes) implement the feature my friends wanted. Here’s how I did it.
First, I wanted to be able to edit the “candidate snippets” — that is, the collection of snippets from which a random selection would be made — without having to edit the script itself. Luckily, TextExpander provides a way to embed snippets in other snippets. So, I started with the following snippets:
- typo1 - Found a typo!
- typo2 - Found another typo!
- typo3 - Find yet another typo!
Next, I created a new snippet and set it to type “Shell Script”. Here’s the code:
If you’ve written python code before, this is pretty straightforward. The first line, known as the “shebang” line, tells the shell to run the script using the Python interpreter. The next line imports the `random` and `sys` modules. The third line defines a collection of snippets (using their embedded-snippet syntax so we can edit the snippets themselves without monkeying around with this script). The last line chooses one element from our list at random and writes it to the system’s standard-out interface (STDOUT). This is where TextExpander listens for script output. It’s not terribly important that you understand all the guts of what’s going on here. The line where we define the list of snippets is really all you’ll need to edit when you customize this. The only known issue here is (and this may disappoint Shawn) is that your snippets can’t contain newlines (what’s inserted when you strike the Return key). If you want to include newlines in your snippet, you’ll have to express them using the newline character:
I realize this is a bit of a pain in the ass, but such is life.
Post any questions you have in the comments and I’ll try to sort you out. Go TextExpander!
[...] http://nerdgap.com/how-to-randomly-selected-snippets-in-textexpander/ [...]