Sunday, October 14, 2007

SEEing LaTeX 13: Accessing the Environment

In the preceding post, I showed a way to use a property list file to define the environment for shell scripts run from within a SubEthaEdit mode. For convenience, we can also use AppleScript to add an item to the mode menu that opens up the appropriate plist for the mode. I'll not discuss the AppleScript at any great length, but instead just give the gist of it.

The basic idea is that we can just open up the plist in whatever application happens to be appropriate; probably, but not certainly, that is the Property List Editor. There are a few ways to accomplish that. I decided, more or less arbitrarily, to use System Events to open the file.

However, we do need to deal with the case when there is no environment property list file. What I did was to put a string representing an empty plist onto the clipboard, and then run a shell script that uses pbpaste to dump that string to an appropriately named file in the preferences folder. This was actually the second approach I took. The first I tried was to just write the file directly using AppleScript, but this associated the resulting file with TextEdit, an undesirable choice for working with a plist. I didn't explore the reason, but assume that AppleScript defines (inappropriate) type and creator codes for the file.

One other odd thing I encountered was that SEE doesn't show an ellipsis "…" correctly in the menu. I just used three dots. Whatever.

Here's the AppleScript:
on seescriptsettings()
    return {displayName:"Mode Environment...", shortDisplayName:"Environment", inContextMenu:"no"}
end seescriptsettings

tell application "SubEthaEdit" to set activeMode to the mode of the front document
openEnvironmentSettings for activeMode

to openEnvironmentSettings for mode
    set envFilePath to (path to preferences from user domain as string) & "de.codingmonkeys.SubEthaEdit." & (name of mode) & "_environment.plist"
    tell application "System Events"
        if not exists file envFilePath
            my writeDefaultEnvironment at envFilePath
        end if
        open file envFilePath
    end tell
end openEnvironment

to writeDefaultEnvironment at envPath
    set savedClipboard to the clipboard
    set the clipboard to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"\">
<plist version=\"1.0\">
    do shell script "pbpaste > " & (POSIX path of envPath)
    set the clipboard to the savedClipboard
end writeDefaultEnvironment

No comments: