--Applescript

-- Script that sends the current selection to 
-- RPN2TeX. It strips $•$, $$•$$ and \[•\] 
-- from the selection. Multiple lines are NOT allowed.
-- Ramon Figueroa-Centeno (March 31, 2009)
-- http://www2.hawaii.edu/~ramonf

-- History:
-- 1.1 (April 6, 2009):
-- TeXShop's implementation of Applescript seems to have a bug,
-- which activates all applications mentioned in a a Macro
-- even if they do not get invoked. Thus, in this version
-- I am removing a "tell application 'System Preferences'" block.

tell application "RPN2TeX" to activate

tell application "TeXShop"
	
	-- The linefeed character.
	set linefeed to ASCII character 10
	
	-- Get the front document of TeXShop
	try
		set front_document to the front document
	on error
		-- If there is no front document abort
		return
	end try
	
	set eqn to the content of the selection of the front_document
	
	if eqn starts with return or the eqn starts with linefeed then
		try
			set eqn to text 2 through -1 of eqn
		on error
			set eqn to ""
		end try
	end if
	
	if eqn ends with return or the eqn ends with linefeed then
		try
			set eqn to text 1 through -2 of eqn
		on error
			set eqn to ""
		end try
	end if
	
	if the eqn contains linefeed or the eqn contains return then
		beep
		display dialog "The selection cannot contain multiple lines!" buttons {"Ok"} default button "Ok" with icon stop
		return
	end if
	
	if eqn starts with "$" and eqn ends with "$" then
		set eqn to text 2 through -2 of eqn
	end if
	-- try to strip a second pair of $'s
	if eqn starts with "$" and eqn ends with "$" then
		set eqn to text 2 through -2 of eqn
	end if
	
	-- Strip \[ and \] pair
	if eqn starts with "\\[" and eqn ends with "\\]" then
		set eqn to text 3 through -3 of eqn
	end if
	
	set eqn_length to count of eqn
	
	activate application "RPN2TeX"
	tell application "System Events"
		get system attribute "sysv"
		if result is greater than or equal to 4144 then -- Mac OS X 10.3.0
			if UI elements enabled then
				
				tell application process "RPN2TeX"
					-- insert GUI Scripting statements here
					--select text field 1 of window "RPN2TeX"
					if eqn_length > 0 then
						set the value of the text field 1 of window "RPN2TeX" to eqn
					end if
					set focused of text field 1 of window "RPN2TeX" to true
				end tell
				
				
			else
				beep
				activate
				display dialog "GUI Scripting is not enabled" & return & return & "Open System Preferences and check Enable Access for Assistive Devices in the Universal Access preference pane, then run this script again." buttons {"Ok"} default button "Ok" with icon stop
			end if
		else
			beep
			activate
			display dialog "This computer cannot run this script" & return & return & "The script uses GUI Scripting technology, which requires an upgrade to Mac OS X 10.3 Panther or newer." with icon caution buttons {"Quit"} default button "Quit"
		end if
	end tell
	
end tell