How to Convert Rich Text in the Clipboard into Markdown?

I didn't either, but I did search for “RTF” – and what did I find?

Your Swift code is not going to work unless the HTML class is already on the clipboard.

AppleScript ⇢ AppleScriptObjC ⇢ Code
--------------------------------------------------------
# Auth: Christopher Stone { Heavy Lifting by Shane Stanley }
# dCre: 2021/10/11 23:34
# dMod: 2021/10/11 23:34 
# Appl: AppleScriptObjC
# Task: Convert RTF on the Clipboard to HTML.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @ASObjC, @Convert, @Clipboard, @RTF, @HTML
# Test: Only on macOS 10.14.6
# Vers: 1.00
--------------------------------------------------------
(*

References:

Script Debugger Forum:
https://forum.latenightsw.com/t/converting-an-nsattributedstring-into-an-html-string/1048/2

Keyboard Maestro Forum:
https://forum.keyboardmaestro.com/t/how-to-convert-rich-text-in-the-clipboard-into-markdown/24203/7

*)
--------------------------------------------------------
use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions
--------------------------------------------------------

# Get the pasteboard.
set thePasteboard to current application's NSPasteboard's generalPasteboard()

# Get RTF data from the pasteboard.
set theData to thePasteboard's dataForType:(current application's NSPasteboardTypeRTF)
if theData = missing value then error "No rtf data found on clipboard"

# Make |theData| into an attributed string.
set theAttString to current application's NSAttributedString's alloc()'s initWithRTF:theData documentAttributes:(missing value)

set elementsToSkip to {}
# set elementsToSkip to {"doctype", "html", "body", "xml", "style", "p", "font", "head", "span"} -- ammend to taste

# Create an NSDictionary.
set theDict to current application's NSDictionary's dictionaryWithObjects:{current application's NSHTMLTextDocumentType, elementsToSkip} forKeys:{current application's NSDocumentTypeDocumentAttribute, current application's NSExcludedElementsDocumentAttribute}

# Extract |htmlData| from |theAttString| Using |theDict|.
set {htmlData, theError} to theAttString's dataFromRange:{0, theAttString's |length|()} documentAttributes:theDict |error|:(reference)
if htmlData = missing value then error theError's localizedDescription() as text

# Convert |htmlData| to an NSString.
set theNSString to current application's NSString's alloc()'s initWithData:htmlData encoding:(current application's NSUTF8StringEncoding)

# Convert NSString to text.
return theNSString as text

--------------------------------------------------------

This is a bit verbose, but it's flexible and quick.

-Chris

1 Like