Created
April 6, 2020 08:20
-
-
Save typemytype/61976b9fde748807ec7fcd620788f0d5 to your computer and use it in GitHub Desktop.
support for markdown in a FormattedString
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
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