Authoring Markdown externally and pasting the 'pretty' output into Slack (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 with trying to copy rich text out of the clipboard, it's also painful to copy rich text into the clipboard.

With thanks to GPT-4.1 (GitHub Copilot), we worked out the following Swift code is what we need, to take rich text input, perform some (rough) stripping of the HTML so there's a plain and rich text format, and make it then available to Slack:

#!/usr/bin/env swift
import Cocoa

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

// Read all of stdin into a string, handling errors
let inputData = try? FileHandle.standardInput.readToEnd()
let htmlString = inputData.flatMap { String(data: $0, encoding: .utf8) } ?? ""

// NOTE that we could alternatively use `Markdown` as a plain-text version, but this works fairly well
// Strip HTML tags for plain text fallback
let plainText: String
if let data = htmlString.data(using: .utf8),
   let attributed = try? NSAttributedString(
        data: data,
        options: [.documentType: NSAttributedString.DocumentType.html],
        documentAttributes: nil
   ) {
    plainText = attributed.string
} else {
    plainText = htmlString
}

let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.declareTypes([.html, .string], owner: nil)
pasteboard.setString(htmlString, forType: .html)
pasteboard.setString(plainText, forType: .string)

This can then be invoked such as:

# NOTE that we could wrap this to have the plain-text from `pandoc`, but right now let's leave it as "Markdown"
pandoc /path/to/file.md -t html | ~/bin/pbcopy_html

From here, this now allows us to paste into Slack πŸš€

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 #slack #markdown #mac.

πŸ€– 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.