TIL: Convert Markdown to Rich Text and Copy to Clipboard on macOS

April 23, 2025 • productivity, macOS, TIL

If you, like me, take notes in Markdown and are looking for a way to copy-paste them as rich text into other apps (such as Slack or Firefox), this is for you.

It uses pandoc to convert Markdown to HTML first, then AppleScript to copy rich text to the clipboard, as suggested here.

# Install dependencies
brew install pandoc

echo "If you need to **convert** files from one _markup format_ into another, [pandoc](https://pandoc.org/) is your swiss-army knife. :wrench:" | \
  pandoc -f markdown -t html | \
  hexdump -ve '1/1 "%.2x"' | \
  xargs printf "set the clipboard to {text:\" \", «class HTML»:«data HTML%s»}" | \
  osascript -

Pasted into Slack:

Screenshot Slack

I turned this into a script (with the help of ChatGPT) and added it to my custom aliases. It takes input either from stdin or from the clipboard.

# Install dependencies
brew install pandoc
uv tool install rich-cli

# Function to convert Markdown to rich text and copy to clipboard
function md2rich() {
  # Detect if input is piped; otherwise, use clipboard content
  if [ -p /dev/stdin ]; then
    input=$(cat)
  else
    input=$(pbpaste)
  fi

  # Convert Markdown to HTML
  html=$(echo "$input" | pandoc -f markdown -t html)

  # Optional: Pretty print Markdown
  echo "Pretty printed Markdown:"
  echo "------------------------"
  if command -v rich >/dev/null 2>&1; then
    echo "$input" | rich - -m
  else
    echo "$input"
  fi
  echo "------------------------"

  # Convert HTML to hex string
  hex=$(echo -n "$html" | hexdump -ve '1/1 "%.2x"')

  # Prepare AppleScript to set clipboard with HTML data
  applescript_cmd=$(printf 'set the clipboard to {text:" ", «class HTML»:«data HTML%s»}' "$hex")

  # Execute AppleScript
  echo "$applescript_cmd" | osascript -

  # Notify user
  echo "Rich text has been copied to the clipboard. ✨"
}

Usage example:

Screenshot alias example

Happy copy-pasting!


Recent posts