Getting access to rich-text data from the clipboard (on Mac)

Related to my post from last year around doing this on Linux, I've been trying to do the same on my work Mac.

As ever, I find that Mac makes things so much more difficult than they need to be, but alas.

Although it would be nice to have a single command-line tool to invoke, it appears that osascript doesn't seem to be able to export the raw HTML, so with thanks to GPT-4.1 (GitHub Copilot), we worked out the following Swift code is what we need:

#!/usr/bin/env swift
import Cocoa

// Co-authored-by: GPT-4.1 (GitHub Copilot)

let pasteboard = NSPasteboard.general
if let html = pasteboard.string(forType: .html) {
    print(html)
} else {
    // as I prefer to see this fail
    exit(1)
}

We can then see this in action:

# pbpaste only returns plaintext
$ pbpaste
renovate
# even with -Prefer=rtf
$ pbpaste -Prefer=rtf
renovate
$ pbpaste -Prefer rtf
renovate

# but our Swift script does what we want:
$ ~/bin/pbpaste_html
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><a data-target="context-region-crumb.linkElement" data-analytics-event="{&quot;category&quot;:&quot;SiteHeaderComponent&quot;,&quot;action&quot;:&quot;context_region_crumb&quot;,&quot;label&quot;:&quot;renovate&quot;,&quot;screen_size&quot;:&quot;full&quot;}" href="https://github.com/renovatebot/renovate" aria-current="page" id="contextregion-repositorycrumb-renovate-link" data-view-component="true" class="AppHeader-context-item"><span data-target="context-region-crumb.labelElement" class="AppHeader-context-item-label ">renovate</span></a></body></html>

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #mac #command-line.

πŸ€– Content in this blog post (prose or code snippets) includes code derived from the following LLMs:

  • gpt-4.1

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.