Script: Batch open selected text's links

Select some text and run the script to batch open links in tabs (instead of clicking(!) them one(!) by one(!)).

It’s great if you want to see fast what’s linked in a text. And it’s really great to open only links of a part of a text.

At the moment it finds http , https and x-devonthink-item links, should be easy to add more.

Todo: For ideal usage in markdown records the regex needs to be adjusted, so that it ignores the name part of links. Maybe someone more familiar with regex could take a look?

-- Open selected text's links

tell application id "DNtp"
	try
		set theWindow to think window 1
		
		try
			set selectedText to selected text of theWindow & "" as string
		on error
			error "No text selected."
		end try
		
		set theClipboard to the clipboard
		activate
		tell application "System Events" to tell process "DEVONthink 3" to keystroke "c" using {command down}
		set theResults to do shell script "osascript -e 'the clipboard as «class RTF »' | perl -ne 'print chr foreach unpack(\"C*\",pack(\"H*\",substr($_,11,-3)))' | egrep -o 'http[^\"]*|x-devonthink-item[^\"]*'" -- https://superuser.com/a/1409995/
		set theURLs to paragraphs of theResults
		set firstURL to true
		repeat with thisURL in theURLs
			set thisTab to open tab for URL thisURL in theWindow
			if firstURL = true then
				set current tab of theWindow to thisTab
				set firstURL to false
			end if
			delay 0.5
		end repeat
		set the clipboard to theClipboard
		
	on error error_message number error_number
		if the error_number is not -128 then display alert "DEVONthink" message error_message as warning
	end try
end tell