--Applescript direct
-- Script to invoke TeXCount <http://folk.uio.no/einarro/Comp/texwordcount.html>
-- Ramon Figueroa-Centeno (March 11, 2009)

-- History:
-- 1.1: Removed the reporting of the number of paragraphs as it is mostly useless and 
-- confusing. Useless because two documents with the same number of paragraphs can have 
-- exactly the same output. Confusing because the user might think that the number of 
-- paragraphs refers to the number of paragraphs in the ouput, not what it actually is, the 
-- number of lines in the TeX code.

tell application "TeXShop"
	set the front_document to the front document
	-- If the front document is not saved dump its 
	-- content to a temporary file and use that
	if the front_document is modified then
		-- The whole text of the document
		set whole_document to (the text of the front_document) as string
		tell me
			set texpath to do shell script "mktemp /tmp/XXXXXXXX"
			set TMP to POSIX file texpath
			open for access TMP with write permission
			write whole_document to TMP
			close access TMP
		end tell
		-- If the front document is saved then make a symbolic
		-- link to it in the /tmp directory. This way we avoid
		-- the "bug" (feature) in texcount that takes a file with
		-- spaces in its name name and takes it as a list of files
		-- even in quoted form or with escaped spaces.
		set texpath to the path of the front_document
		set symlinkpath to do shell script "mktemp /tmp/XXXXXXXX"
		do shell script "rm " & symlinkpath
		do shell script "ln -s " & (quoted form of texpath) & " " & symlinkpath
		set texpath to symlinkpath
		set TMP to texpath
	end if
	set command to "/usr/texbin/texcount " & texpath & " | tail -n +2"
	tell me to set TeXcount to do shell script command
	-- If a temporary file or symbolic link was created delete it.
		do shell script "rm " & POSIX path of TMP
	end try
	--set count_pars to count the paragraphs of the text of the front_document
	--display dialog TeXcount & "Paragraphs: " & count_pars buttons {"Ok"} default button "Ok"
	display dialog TeXcount buttons {"Ok"} default button "Ok"
end tell