Manipulating file link path

I have a script that gets the file path for a document in Devonthink and then tries to replace all spaces in that path name with “%20”. I have used a similar find and replace script and it works without any problems but when I use it in this script I get the error number -1708. I am sure that I am making a simple error but can’t seem to resolve it. Does anyone have any ideas? Any help much appreciated.

on replacetext(find, replace, subject)
	set prevTIDs to text item delimiters of AppleScript
	set text item delimiters of AppleScript to find
	set subject to text items of subject
	set text item delimiters of AppleScript to replace
	set subject to "" & subject
	set text item delimiters of AppleScript to prevTIDs
	return subject
end replacetext

tell application id "com.devon-technologies.thinkpro2"
		set theSelection to the selection
		if theSelection is {} then error "Please select a record"
		set filepath to the path of the first item of theSelection
	end try
	set filepath to get replacetext("", "%20", filepath)
	set the clipboard to "file://localhost" & filepath
end tell

to encode an url you could use PHP

set filepath to "path to file"
do shell script "php -r " & quoted form of ("echo rawurlencode('" & filepath & "');")

The call to the handler’s inside a ‘tell’ statement, so it needs ‘my’ in front of it to mark it as something belonging to the script rather than to the ‘tell’ target.

tell application id "com.devon-technologies.thinkpro2"

	-- Blah blah

	set filepath to my replacetext(" ", "%20", filepath)

end tell

. or indeed put the ‘end tell’ before the ‘set filepath .’.

Thank you very much Nigel. That worked. I thought it must be something silly but I did not realise that one has to put “my” in front of the subroutine call.

I will also try the php shell script

Thank you both for your help.