Not many people realise that all the commands given to you by TextMate are written as simple scripts, editable by anyone, and in any language. PHP is a widespread language, but not many people are accustomed to using PHP for writing shell scripts, so they don’t know how to start writing a command – here I’ll explain how.
Let’s pretend we’re going to be writing some FAQ lists, so we’ll have a list of questions, like this:
And we want to convert it to a list of links to the questions, like this:
This is the first question This is the second question This is the *third* question
This is the first question This is the second questionThis is the third questionFirst, you’ll need to make a new command – open the bundle editor (Bundles → Bundle Editor → Show Bundle Editor… or
⌃⌥⌘B) and use the bottom left button (with a plus sign and an arrow) to create a “New Command”, and name it “Create FAQ Index”. The large text field on the right is where you’ll be entering the code for the command.
To start, you’ll need to tell TextMate that the command needs to run with PHP, which is done with a shebang:
TextMate commands basically have 3 factors:
#!/usr/bin/env php <?php //Our code will go here ?>
- Reading input (provided on standard input, and some information is given in environment variables)
- Processing the input
- Doing something with the result (generally either inserting some text into the current document, or showing a HTML window or tooltip)
So first we need to get the input from the document – if you look at the pop-up below the big text field you can see that the input for our command will come from the current selection (or the entire document if there is no selection). This is perfect for what we want.
We need to read the selection from standard input, the easiest way to do this is with:
We also need to know the name of the current file, which is given to us as an environment variable
TM_FILENAME(Use the Show TM_* Variables command in the Bundle Development bundle to see a full list)– these are accessible from PHP with either the
getenv()function or the
Now we want to split the input into lines and then print out the link for each line:
And that’s it! It’s not very interesting though, so let’s make the titles in the result into snippets:
This will echo some lines like
Which is TextMate’s syntax for snippets.
e_sn() is used to escape the characters which are special inside a snippet.
The completed command is repeated below (with an extended transformation to handle lower-casing the anchor name):
#!/usr/bin/env php $str); } ?>,
13 Responses to “TextMate Tip – Using PHP for Commands”