DEVONthink/Bates Source Link.scpt
2024-10-26 22:56:25 +02:00

64 lines
2.1 KiB
AppleScript

tell application id "DNtp"
try
-- Retrieve record details directly
set theRecord to content record of think window 1
set pageNumber to current page of think window 1
set theTitle to name of theRecord
set quotedText to (selected text of think window 1) as string
set sourceLink to reference URL of think window 1
-- Extract the numeric part and prefix from the document's title
set numericPart to my extractNumericPart(theTitle)
set prefix to my extractPrefix(theTitle)
-- Determine the Bates number or fallback
if numericPart is "" then
set batesFormatted to theTitle & " at " & pageNumber + 1
else
set batesNumber to numericPart + pageNumber
set batesFormatted to my formatBatesNumber(batesNumber, prefix)
end if
-- URL encoding using Perl
set encodedText to do shell script "perl -MURI::Escape -e 'print uri_escape(q{" & quotedText & "});'"
-- Create the markdown link
set markdownLink to "[" & batesFormatted & "](" & sourceLink & ")"
-- Compile the final clipboard content and update the clipboard
set finalClipboardContent to quotedText & " " & markdownLink & "."
set the clipboard to finalClipboardContent
on error errMsg
display dialog "Error: " & errMsg -- Show any errors that occur
end try
end tell
-- Formatting the Bates number without leading zeros
on formatBatesNumber(batesNumber, prefix)
return prefix & batesNumber -- Return formatted Bates number with prefix
end formatBatesNumber
-- Extract numeric part from the document title
on extractNumericPart(title)
try
-- Adjusted Perl script to capture only the numeric sequence following one or more uppercase letters and a space or underscore
set perlScript to "perl -ne 'print $1 if /^[A-Z]+[ _]([0-9]+)(?:-[0-9]+)?/; exit;'"
return do shell script "echo " & quoted form of title & " | " & perlScript
on error errMsg
return ""
end try
end extractNumericPart
-- Extract prefix (non-numeric part) from the document title
on extractPrefix(title)
set prefix to ""
repeat with aChar in characters of title
if aChar is in "0123456789" then exit repeat
set prefix to prefix & aChar
end repeat
return prefix
end extractPrefix