Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
support for markdown in a FormattedString
import AppKit
def appendHTML(self, html):
htmlString = AppKit.NSString.stringWithString_(html)
txt, _, _ = AppKit.NSAttributedString.alloc().initWithData_options_documentAttributes_error_(
htmlString.dataUsingEncoding_(AppKit.NSUTF8StringEncoding),
{AppKit.NSDocumentTypeDocumentAttribute: AppKit.NSHTMLTextDocumentType, AppKit.NSCharacterEncodingDocumentAttribute: AppKit.NSUTF8StringEncoding},
None, None)
self._attributedString.appendAttributedString_(txt)
self._attributedString.appendAttributedString_(AppKit.NSAttributedString.alloc().initWithString_("\n"))
def appendMarkdown(self, md, style=None):
import markdown
from markdown.extensions.toc import TocExtension as markdownTocExtension
from markdown.extensions.tables import TableExtension as markdownTableExtension
from markdown.extensions.fenced_code import FencedCodeExtension as markdownFencedCodeExtension
from markdown.extensions.codehilite import CodeHiliteExtension as markdownCodeHiliteExtension
convertedMarkdown = markdown.markdown(md, extensions=[
markdownTableExtension(),
markdownTocExtension(permalink=False, toc_depth='2-3'),
markdownFencedCodeExtension(),
markdownCodeHiliteExtension()
])
if style is None:
style = ""
html = f"""<html>
<head>
<meta charset="UTF-8">
<style>
{style}
</style>
</head>
<body>
{convertedMarkdown}
</body>
</html>
"""
self.appendHTML(html)
FormattedString().__class__.appendHTML = appendHTML
FormattedString().__class__.appendMarkdown = appendMarkdown
html = """<html>
<style>
body {
font-family:"Helvetica";
color: red;
}
h1 {
color: blue;
}
</style>
<body>
<h1>foo bar</h1>
hello world
<h2>foo bar</h2>
more
</body>
</html>"""
t = FormattedString()
t.appendHTML(html)
md = """# title
more info
## subtitle
foo bar
"""
t.appendMarkdown(md, style="body {font-family:Helvetica} h1 {color:yellow}")
textBox(t, (10, 10, 900, 900))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.