Teaching code 001

I had an unusal Support request today that lent itself to a quick bit o’ scripting. The client is using the URL field to link to other documents in DEVONthink - a not uncommon thing, as the Annotation template does this automatically. But he wanted to click the link and have the linked file open in it’s external application. Well, he can’t do that… but an AppleScript can.

Honestly, it didn’t make much sense to me when I first read it, but as I tested the script I thought, “Huh. Maybe this would be useful to others.” I talked it over with Eric and he asked if I would post the code as an example. So… here is the code, broken down and commented for the new kids in the class. It’s simple with a little advanced exploit of using a UNIX shell script for speed (and because it’s awesome 8) ). I hope it helps.

-- This is intended to externally open a file linked in DEVONthink.
-- Imagine you have an Annotation file that links back to the original file.
-- This would open the original file externally, NOT the current file.
-- © 2017 DEVONtechnologies, LLC - BLUEFROG / Jim Neumann

tell application id "DNtp"
	-- This will process one or more files, in succession
	repeat with thisRecord in (selection as list)
		-- Check for a URL
		if (exists (URL of thisRecord)) then
			-- Check if it's a DEVONthink link	.
			if (URL of thisRecord begins with "x-devonthink") then
				-- Get the current file's URL
				set recURL to URL of thisRecord
				-- Excise the x-devonthink:// section of the URL to get the UUID
				set recUUID to (do shell script "basename " & recURL)
				-- Get the document whose UUID is linked
				set linkedRec to get record with uuid recUUID
				-- Get the filesystem path of that record
				set linkedRecPath to path of linkedRec
				-- Tell Finder to open it.
				-- Finder wants an HFS (colon delimited path) so it is converted to a POSIX file.
				tell application "Finder" to open (linkedRecPath as POSIX file)
				-- No URL for the record? Warn and move on.
				-- This is optional, as it could just fail silently on those records with no URL.
				display alert "There is no URL associated with this record."
			end if
		end if
	end repeat
end tell

And the script itself is here too (though I suggest typing it over using the script or copy and paste if you’re new to scripting. Typos are the NUMBER ONE error you’ll run into in any coding language. It’s best to get these terms and the syntax under your fingers sooner rather than later. Cheers!
DT_Open Record URL Externally_TeachingEdition.scpt.zip (5.04 KB)