aaron.harnly.net

Using snippets in Textmate templates

Pursuant to the post below, I found myself creating a simple Scala bundle for Textmate, as there isn’t one at the moment. (Getting in on the ground floor!)

The Textmate snippet system is a wonderful creation — simple, delightful, and helpful. Unfortunately, the templating system is not nearly so nice — just a Perl one-liner to substitute in some environment variables, and no snappy tab-tab autofill magic.

Then I ran across this great post by Henrik Nyh, in which he scrapes together a little Applescript to create a Textmate template as a snippet.

However, I found myself wanting both some templated boilerplate, with variable substitution, and some snippetized text below. This proved a little trickier than I first thought, since the Applescript inserts at the top of the document, and it would require a nasty keypress script to insert the snippet below.

So, I came up with a slightly modified version of Henrik’s system, which supports a template_in.txt file with the usual variable substitutions, as well as a snippet below.

The template script looks like this: if [[ ! -f "$TMNEWFILE" ]]; then TMYEAR=date +%Y \ TMDATE=date +%Y-%m-%d \ TMUSERNAME=niutil -readprop / /users/\$USER realname \ TMTEMPLATEOUTPUT=$(mktemp “/tmp/tmtemplate_XXXXXX”)

perl -pe ’s/\${([^}]*)}/$ENV{$1}/g’ \ < templatein.txt > “$TMTEMPLATE_OUTPUT”

touch “$TMNEWFILE”

{ # Insert the template & snippet!
osascript "${TM_BUNDLE_SUPPORT}/load_snippet.scpt" "$TM_TEMPLATE_OUTPUT" "snippet.txt" 
} &>/dev/null &

fi

and the Applescript is modified to this: on run args set templateoutputfile to (item 1 of args) set snippet_file to (item 2 of args)

-- retrieve the template and snippet text
set existing_text to read (POSIX file (template_output_file)) as «class utf8»
set loaded_snippet to read (POSIX file (snippet_file)) as «class utf8»

-- insert both into the document
tell application "TextMate"
    insert existing_text
    insert loaded_snippet with as snippet
end tell

-- remove the temporary file
do shell script "rm \"" & template_output_file & "\""

end run

You can download Snipplate2 (AWH) here.

Digg this     Create a del.icio.us Bookmark     Add to Newsvine

3 Responses to “Using snippets in Textmate templates”

  1. Henrik N Says:

    Very nice!

  2. aaronharnly Says:

    Oops, I made one mistake — the template script should be exporting those variables, so they get picked up by the perl script. I’ll post a corrected file in a moment.

  3. Vishnu Gopal Says:

    Hey, could you post the TextMate bundle up as well? It’ll be really useful :-)

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word