Skip to content

Instantly share code, notes, and snippets.

@doctaphred
Last active April 8, 2022 23:38
Show Gist options
  • Save doctaphred/a66ae9d142f21ff59f42b5e26d1d1af2 to your computer and use it in GitHub Desktop.
Save doctaphred/a66ae9d142f21ff59f42b5e26d1d1af2 to your computer and use it in GitHub Desktop.
Workaround for copy/pasting Slack's broken multiline code blocks
#!/usr/bin/env python3
"""
Slack's new WYSIWYG format broke copy/pasting multiline code blocks:
blank lines are omitted when pasting as plain text.
If you can get the HTML contents of the clipboard, this script can
output the expected text, blank lines and all.
The macOS clipboard is complicated, and the built-in `pbpaste` command
won't let you get the contents as HTML. (The `-Prefer` option seems to
not do anything at all: there's even a related bug documented in the
`pbpaste` man page.) Christopher Brown's `macos-pasteboard` project
works well for me: https://github.com/chbrown/macos-pasteboard (Thanks,
Christopher!) (Linux probably has similar tools available.)
Suggested usage with `macos-pasteboard` and the built-in `pbcopy`:
pbv public.html | print-slack-clipboard | pbcopy
"""
import sys
from html.parser import HTMLParser
class SlackClipboardPrinter(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'br':
print()
elif tag == 'span':
for attr in attrs:
if attr == ('data-stringify-type', 'paragraph-break'):
print('\n')
def handle_data(self, data):
print(data, end='')
SlackClipboardPrinter().feed(str(sys.stdin.read()))
@quantophred
Copy link

NOTE: Looks like this won't convert charrefs (e.g., &lt;) on Python < 3.5: change SlackClipboardPrinter() to SlackClipboardPrinter(convert_charrefs=True) in Python 3.4 (or upgrade your Python 😉)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment