Last active
April 8, 2022 23:38
-
-
Save doctaphred/a66ae9d142f21ff59f42b5e26d1d1af2 to your computer and use it in GitHub Desktop.
Workaround for copy/pasting Slack's broken multiline code blocks
This file contains 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
#!/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())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: Looks like this won't convert charrefs (e.g.,
<
) on Python < 3.5: changeSlackClipboardPrinter()
toSlackClipboardPrinter(convert_charrefs=True)
in Python 3.4 (or upgrade your Python 😉)