--Applescript direct

-- Script that inserts the \input{•}, \include{•} or \includegraphics{•},
-- where • is either a relative or absolute path.
-- It tries to be smart about spaces in file paths.
-- Beware that that for \include{•} the path • can only be to the directory 
-- of the target document or a subdirectory thereof.
-- Therefore, if an \include{•} is impossible, no choice will be
-- presented, and an \input{•} will be automatically entered.
-- This might be confusing to a user that does not know of this limitation.

-- Ramon Figueroa-Centeno (March 14, 2009)
-- http://www2.hawaii.edu/~ramonf

-- To forbid spaces in paths set no_spaces to "true":
property no_spaces : false

-- To also be given the choice, when possible, to use absolute paths 
--  set absolute to "true":
property absolute : false

-- Suffixes that \include and \input can handle (as far as I know only "tex")
property Texts : {"tex"}

-- Suffixes that \includegraphics can handle (probably incomplete).
-- See "Including Graphics" in the TeXShop Manual.
property Graphics : {"pdf", "png", "tif", "tiff", "ps", "eps", "jpg", "PDF", "PNG", "JPG", "JPEG", "mps", "jbig2", "jb2", "JBIG2", "JB2"}

-- Now, what \includegraphics can handle depends on the platform. 
-- So you can switch off file type checking by setting ignore_suffix to true.
property ignore_suffix : false

-- Suffixes for graphics files which do not work if their 
-- paths have spaces in them (probably incomplete).
property GraphicsWithoutSpaces : {"tif", "jpg"}

-- Omitting the suffix in the path of a graphics file can be very useful.
-- For example if you have EPS files and you are using pdfTeX, then
-- your document preamble should include
--    \usepackage{graphicx}
--    \usepackage{epstopdf}
-- then on the first run all the EPS files get converted to PDF; but not on the
-- subsequent runs, if you do not use the file suffix, otherwise they will be
-- converted every time. Moreover, If you then use TeX and DVI, the files the 
-- your document will still typeset seemlessly as the EPS files are still present.
-- Now, TIFFs need something extra in the preamble:
--    \DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `basename #1 .tif`.png}
--   \DeclareGraphicsExtensions{.pdf,.eps,.png,.jpg,.tif}
-- This list must contain all of the suffixes we are using, in
-- their order of importance. Thus the suffix ".png" should come before ".tif",
-- as in that way the TIFFs are converted to PNGs only once.
-- Therefore, here is a property to toggle the use of suffixes for every graphic file:
property use_suffix : false

tell application "TeXShop"
	
	-- Include absolute paths?:
	set also_absolute to absolute
	
	try
		path of the front document
		set TeX_path to the result
	on error
		-- There is no front document  or it has not ever been saved
		beep
		display dialog "there is no front document" & return & "or it has not been saved ever!" buttons {"Ok"} default button "Ok" with icon stop giving up after 20
		return
	end try
	
	set TeX_path to do shell script "dirname " & quoted form of TeX_path
	
	-- Get the absolute path to the document to be included.
	try
		set target_abs_path to POSIX path of (choose file with prompt "Pick the file whose path you wish to insert:")
	on error
		return
	end try
	
	-- Use perl to convert the absolute path to the target document 
	-- to a relative path to it.
	set command to "perl -e 'use File::Spec; "
	set command to command & "$rel_path = File::Spec->abs2rel"
	set command to command & "( \"" & target_abs_path & "\","
	set command to command & "\"" & TeX_path & "\" ) ; "
	set command to command & "print $rel_path'"
	tell me to set target_rel_path to do shell script command
	
	if target_rel_path contains " " and no_spaces then
		-- If we are enforcing no spaces in paths stop.
		beep
		set message to "Paths may not contain spaces!"
		display dialog message buttons {"Ok"} default button "Ok" with icon stop giving up after 30
		-- Abort
		return
	else if target_abs_path contains " " and no_spaces then
		-- The relative path may contain no spaces, whilst the absolute path does.
		set also_absolute to false
	end if
	
	-- Get the file's suffix
	-- (I would like to do this more elegantly)
	try
		set suffix to (do shell script "expr \"" & target_abs_path & "\" : '.*\\.\\([^./]*\\)$'")
	on error
		beep
		display dialog "The file has no suffix!" buttons {"Ok"} default button "Ok" with icon stop giving up after 20
		return
	end try
	
	set suffix_length to (count of suffix) + 2
	
	-- display dialog suffix & ": " & suffix_length
	
	-- Remove the suffix from the relative path
	set target_rel_path to text 1 through -suffix_length of target_rel_path
	if also_absolute then
		-- Remove the suffix from the absolute path
		set target_abs_path to text 1 through -suffix_length of target_abs_path
	end if
	
	-- display dialog target_rel_path & return & target_abs_path
	
	-- De-select any current selection.
	set length of the selection of the front document to 0
	
	-- sed command to replace all spaces " " with "\space "
	set command to " | sed 's/ /\\\\space /g'"
	
	-- Handle TeX files.
	if suffix is in Texts then
		-- Handle "\input"
		set input_rel to target_rel_path
		-- Curiously \input needs spaces escaped with \space just as
		-- \include, only when there is more than two spaces in a row.
		if input_rel contains "  " then
			set input_rel to do shell script "echo " & quoted form of input_rel & command
		end if
		if input_rel contains " " then
			set input_rel to "\"" & input_rel & "\""
		end if
		set targets to {"\\input{" & input_rel & "}"}
		
		if also_absolute then
			set input_abs to target_abs_path
			if input_abs contains "  " then
				set input_abs to do shell script "echo " & quoted form of input_abs & command
			end if
			if input_abs contains " " then
				set input_abs to "\"" & input_abs & "\""
			end if
			set targets to targets & {"\\input{" & input_abs & "}"}
		end if
		
		--display dialog input_rel & return & input_abs
		
		-- Handle "\include"
		-- Note that \include can only point to the directory of the document 
		-- (or subdirectories thereof) that is, directories whose relative path
		-- starts with ".." should be ommitted.
		if target_rel_path does not start with ".." then
			set include_rel to target_rel_path
			-- Escape spaces in paths for \include. 
			if input_rel contains " " then
				set include_rel to do shell script "echo " & quoted form of include_rel & command
				set include_rel to "\"" & include_rel & "\""
			end if
			set targets to targets & {"\\include{" & include_rel & "}"}
			if also_absolute then
				set include_abs to target_abs_path
				if input_abs contains " " then
					set include_abs to do shell script "echo " & quoted form of include_abs & command
					set include_abs to "\"" & include_abs & "\""
				end if
				set targets to targets & {"\\include{" & include_abs & "}"}
			end if
			-- display dialog include_rel & return & include_abs
		end if
		tell me to set target to SelectTarget(targets, "Choose which one you wish to insert:")
		
		set the selection of the front document to target as string
		-- Handle graphic files.
	else if (suffix is in Graphics) or ignore_suffix then
		-- TIFF files with suffix "tiff" are not allowed.
		-- (Maybe I should give the option to rename the file for the user?)
		if the suffix is "tiff" then
			beep
			display dialog "Change the file suffix from \".tiff\" to \".tif\"!" buttons {"Ok"} default button "Ok" with icon stop giving up after 30
			-- Paths to TIFF and JPEG files may not contain spaces in \includegraphics.
		else if suffix is in GraphicsWithoutSpaces then
			if target_rel_path contains " " then
				-- If the relative path contains spaces, so does the absolute, so we abort.
				beep
				display dialog "Paths for files with suffix \"" & suffix & "\" may not contain spaces!" buttons {"Ok"} default button "Ok" with icon stop giving up after 20
				-- Abort
				return
			else
				-- The relative path does not contain spaces, but...
				if use_suffix then
					set targets to {target_rel_path & "." & suffix}
				else
					set targets to {target_rel_path}
				end if
				-- ...the absolute path may.
				if also_absolute and target_abs_path does not contain " " then
					-- If absolute paths are being considered, then we have a choice to make.
					if use_suffix then
						set targets to targets & {target_abs_path & "." & suffix}
					else
						set targets to targets & {target_abs_path}
					end if
				end if
				tell me to set target to SelectTarget(targets, "\\includegraphics{•}, where • is:")
			end if
		else
			-- Here we deal with graphic files whose paths may have spaces.
			set includegraphics_rel to target_rel_path
			
			-- Curiously \includegraphics needs spaces escaped with \space just as
			-- \include, only when there is more than two spaces in a row.
			if includegraphics_rel contains "  " then
				set includegraphics_rel to do shell script "echo " & quoted form of includegraphics_rel & command
			end if
			-- If there are spaces in the relative path then we put it in quotations.
			if includegraphics_rel contains " " then
				set includegraphics_rel to "\"" & includegraphics_rel & "\""
			end if
			if use_suffix then
				set includegraphics_rel to includegraphics_rel & "." & suffix
			end if
			set targets to {includegraphics_rel}
			if also_absolute then
				set includegraphics_abs to target_abs_path
				if includegraphics_abs contains "  " then
					set includegraphics_abs to do shell script "echo " & quoted form of includegraphics_abs & command
				end if
				-- If there are spaces in the absolute path then we put it in quotations.
				if includegraphics_abs contains " " then
					set includegraphics_abs to "\"" & includegraphics_abs & "\""
				end if
				if use_suffix then
					set includegraphics_abs to includegraphics_abs & "." & suffix
				end if
				set targets to targets & {includegraphics_abs}
			end if
			tell me to set target to SelectTarget(targets, "\\includegraphics[]{•}, where • is:")
		end if
		set the selection of the front document to "\\includegraphics[]{" & target & "}"
	else
		beep
		display dialog "I do not know the suffix \"" & suffix & "\"!" buttons {"Ok"} default button "Ok" with icon stop giving up after 30
	end if
end tell

-- Routine that selects which text to insert. 
on SelectTarget(targets, message)
	if (count of targets) = 1 then
		set target to (item 1 of targets)
	else
		-- There is more than one possibilty, so the user must choose:
		tell application "TeXShop"
			set the target to choose from list targets with prompt message default items item 1 of targets OK button name "OK" cancel button name "Cancel" without multiple selections allowed and empty selection allowed
		end tell
		if the result is false then
			-- Abort
			error number -128
		end if
	end if
	return target
end SelectTarget