Paste and highlight

Select a para or two on a web page, and try this. It puts RTF, including a hyperlink to the source, into the clipboard.

A rough indicative draft. I leave two things as an exercise for the reader : -)

  1. Add a bit of CSS to get the font and style you want
  2. Encode any special characters in the copied text as HTML entities

( I know you're still holding off on Yosemite, so I've sketched it in Applescript. JavaScript is probably the more obvious tool to reach for with this kind of thing.

Copy from web as linked RTF.kmmacros (26.4 KB)

on run
	tell application "Keyboard Maestro Engine"
		set lstNameTab to {}
		set lstParas to {}
		set strLinkHTML to ""
		set strParasHTML to ""
		
		-- LIST OF COPIED PARAGRAPHS
		set lstParas to paragraphs of (my EscapeChars(the clipboard as Unicode text))
		
		-- NAME AND URL OF WEB PAGE
		set lstVars to (variables where name = "nameAndURL") as list
		if length of lstVars > 0 then
			set strNameTabUrl to value of item 1 of lstVars
			set {dlm, my text item delimiters} to {my text item delimiters, tab}
			set lstNameTab to text items of strNameTabUrl
			set my text item delimiters to dlm
		end if
		
		-- NAME AND URL AS HTML LINK
		if length of lstNameTab > 1 then
			set strLinkHTML to "<a href=\"" & item 2 of lstNameTab & "\">" & item 1 of lstNameTab & "</a>"
		end if
		
		-- APPENDED TO PARAS AS 'SOURCE:'
		set end of lstParas to "Source: " & strLinkHTML
		
		-- ALL WRAPPED IN <P> TAGS
		set {dlm, my text item delimiters} to {my text item delimiters, "</p><p>"}
		set strHTML to "<p>" & (lstParas as text) & "</p>"
		set my text item delimiters to dlm
		
		-- REWRITTEN AS RTF AND COPIED TO THE CLIPBOARD
		set strCMD to "echo " & quoted form of strHTML & " | textutil -format html -convert rtf -stdin -stdout | pbcopy -Prefer rtf"
		do shell script strCMD
	end tell
end run

on EscapeChars(str)
	-- QUOTE < > & ETC
	set strEncoded to (do shell script "python -c 'import sys; from xml.sax.saxutils import quoteattr; print quoteattr(sys.argv[1])' " & ¬
		quoted form of str)
	
	-- ENCODE DIACRITICS AND SPECIAL CHARACTERS
	set lstChars to characters of strEncoded
	repeat with i from 1 to length of lstChars
		set lngCode to id of item i of lstChars
		if lngCode > 127 then set item i of lstChars to ("&#" & lngCode as string) & ";"
	end repeat
	lstChars as Unicode text
end EscapeChars
1 Like