I am looking for answers that may present alternative methods / modifications related to:
- My method of sending data to the clipboard
- The choice of Lexer
That may solve the following issue...
I aim to be able to send raw python
via some process to my clipboard such that I can paste it directly into a Microsoft application (such as Outlook) as formatted text as below
I can only achieve the following raw pygments
output. RtfFormatter
shown but same occurs with HtmlFormatter
Copy to Clipboard Method
I use the copy
func from the post https://stackoverflow.com/a/27291478/4013571
as
import ctypes
def copy(text):
"""Copies a string, ``text``, to Windows Clipboard (https://stackoverflow.com/a/27291478/4013571)"""
GMEM_DDESHARE = 0x2000
CF_UNICODETEXT = 13
d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
try: # Python 2
if not isinstance(text, unicode):
text = text.decode('mbcs')
except NameError:
if not isinstance(text, str):
text = text.decode('mbcs')
d.user32.OpenClipboard(0)
d.user32.EmptyClipboard()
hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
pchData = d.kernel32.GlobalLock(hCd)
ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
d.kernel32.GlobalUnlock(hCd)
d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
d.user32.CloseClipboard()
I have also tried pyperclip.copy
with no success
Syntax Highlighting Method
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import RtfFormatter # Same occurs using HtmlFormatter
raw_python = '''
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
'''
highlighted = highlight(raw_python, PythonLexer(), RtfFormatter())
copy(highlighted)
...
`. Link form your first comment looks promissing. – Daniel Sęk Oct 18 '17 at 18:57