Friday, November 6, 2009

Replacement for SubEthaEdit's Command Line Tool

The see command line tool for SubEthaEdit makes scripting needlessly complex. Because it tries to write the contents of the document to stdout upon close of the document, you wind up having to jump through hoops to get sensible behavior. The end result is that it is easy to write an AppleScript where SubEthaEdit calls out to the shell, but hard to have the shell communicate back to SubEthaEdit.

Here, I present an alternative. It is a shell script that uses osascript to open a document in SubEthaEdit. Optionally, a specific line can be given, and, if UI scripting is enabled, the document will be scrolled to show the line.
#!/bin/sh

PROGRAM=$(basename $0)

usage()
{
echo "Usage: $PROGRAM [-gh] filename"
}

lineGiven=false
while getopts :g:h opt
do
case $opt in
g) lineGiven=true
lineToShow="$OPTARG"
;;
h) usage
exit 0
;;
'?') echo "$PROGRAM: invalid option -$OPTARG" >&2
usage >&2
exit 1
;;
esac
done

shift $((OPTIND - 1))

fileName="$1"

if [ -f "$fileName" ]
then
Dir="$(dirname "$fileName")"
Base="$(basename "$fileName")"
AbsDir="$(cd "$Dir" && pwd -P)"
AbsPath="$AbsDir/$Base"
else
echo "Unknown file: $fileName" >&2
exit 1
fi

echo $AbsPath

/usr/bin/osascript > /dev/null <<ASCPT
set fileToOpen to POSIX file "$AbsPath"

if $lineGiven then
showLine of fileToOpen at ${lineToShow:-0}
else
tell application "SubEthaEdit"
activate
open fileToOpen
end tell
end if

to showLine of fileToOpen at lineNumber
tell application "SubEthaEdit"
activate
set activeFile to open fileToOpen
tell activeFile
set selection to paragraph lineNumber
end tell
end tell
scrollToVisible()
end showLine

to scrollToVisible()
tell application "System Events"
if UI elements enabled then
tell process "SubEthaEdit"
tell menu bar 1
tell menu bar item "Find"
tell menu 1
click menu item "Jump to Selection"
end tell
end tell
end tell
end tell
end if
end tell
end scrollToVisible
ASCPT