--Applescript
-- Script to transfer the current TeXShop document to BBEdit
-- Ramon Figueroa-Centeno (March 10, 2009)


tell application "TeXShop"
	try
		if the front document is modified then
			set myButton to button returned of (display dialog "You need to save changes to your document!" buttons {"Cancel ", "Save"} default button 2 with icon caution)
			if myButton is "Cancel " then
				return
			else
				try
					save the front document
				on error
					return
				end try
			end if
		end if
		
		set FILEPATH to path of the front document
		set selection_offset to offset of the selection of the front document
		set selection_length to length of the selection of the front document
		
		tell application "BBEdit"
			activate
			-- set myTeXfile to open POSIX file #FILEPATH#
			set myTeXfile to open POSIX file FILEPATH
			tell myTeXfile
				if selection_length = 0 and selection_offset = 0 then
					select insertion point before character 1
				else if selection_length > 0 then
					select (characters (selection_offset + 1) thru (selection_offset + selection_length))
				else
					select insertion point after character selection_offset
				end if
			end tell
		end tell
		
		close front document
		
	on error
		beep
	end try
end tell