Copy text from one document and pasting it with reference

This script copies selected PDF text and a Markdown link.

Change property theDelimiter if you want the Markdown link e.g. below the text.

-- Copy selected PDF text and Markdown Link

use AppleScript version "2.4"
use framework "AppKit"
use scripting additions

property useSuffix : true
property theDelimiter : space -- or e.g. linefeed & linefeed

tell application id "DNtp"
	try
		if not (exists think window 1) then
			error "Please open a window"
		else
			set theWindow to think window 1
		end if
		
		set theRecord to content record of theWindow
		
		if theRecord ≠ missing value then
			set theType to (type of theRecord) as string
			if theType is in {"PDF document", "«constant ****pdf »"} then
				
				try
					set theSelectedText to selected text of theWindow & "" as string
				on error
					error "Please select some text"
				end try
				
				set thePage to current page of theWindow
				set theRefURL to reference URL of theRecord & "?page=" & thePage
				
				if useSuffix = true then
					set theName to name of theRecord
					if theName does not end with ".pdf" then set theName to theName & ".pdf"
				else
					set theName to name without extension of theRecord
				end if
				
				set theMarkdownLink to "[" & theName & "](" & theRefURL & ")"
				
				set theQuote to theSelectedText & theDelimiter & "(" & theMarkdownLink & ")"
				
				my setClipboardToPlainText(theQuote) -- necessary in macOS Mojave
				display notification "Copied"
			else
				error "Please open a PDF record"
			end if
		else
			error "Please open a PDF record"
		end if
		
	on error error_message number error_number
		if the error_number is not -128 then display alert "DEVONthink" message error_message as warning
		return
	end try
end tell

on setClipboardToPlainText(theText)
	set thePasteboard to current application's NSPasteboard's generalPasteboard()
	thePasteboard's clearContents()
	(thePasteboard's setString:theText forType:(current application's NSPasteboardTypeString))
end setClipboardToPlainText