Created
April 9, 2026 01:06
-
-
Save cedricvidal/d823f86f6c08d1fb8e3c1880fd094e3b to your computer and use it in GitHub Desktop.
Converts rich document in Clipboard to a Markdown document in clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Convert rich text (HTML) from clipboard to Markdown and copy it back | |
| # Usage: rich2md.sh (reads HTML from clipboard) | |
| # echo "<h1>Hello</h1>" | rich2md.sh (reads HTML from stdin) | |
| export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH" | |
| if [ -p /dev/stdin ]; then | |
| # HTML piped via stdin | |
| html=$(cat) | |
| else | |
| # Extract HTML from clipboard using Swift (reliable binary-safe method) | |
| html=$(swift -e ' | |
| import AppKit | |
| if let data = NSPasteboard.general.data(forType: .html), | |
| let html = String(data: data, encoding: .utf8) { | |
| print(html, terminator: "") | |
| } else { | |
| exit(1) | |
| } | |
| ' 2>/dev/null) | |
| if [ $? -ne 0 ] || [ -z "$html" ]; then | |
| echo "No rich text found on clipboard. Copy some rich text first." >&2 | |
| exit 1 | |
| fi | |
| fi | |
| # Strip style, class, and id attributes from HTML for cleaner conversion | |
| html=$(echo "$html" | sed -E 's/ (style|class|id)="[^"]*"//g') | |
| # Convert HTML to Markdown via pandoc (gfm = cleaner output, no escaped quotes) | |
| markdown=$(echo "$html" | pandoc -f html -t gfm --wrap=auto | sed '/^[\\]$/d') | |
| # Pretty print the result | |
| echo "Converted Markdown:" | |
| echo "------------------------" | |
| echo "$markdown" | |
| echo "------------------------" | |
| # Copy Markdown to clipboard | |
| echo -n "$markdown" | pbcopy | |
| # Notify user | |
| echo "Markdown has been copied to the clipboard. ✨" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment