__filename__ = "markdown.py" __author__ = "Bob Mottram" __license__ = "AGPL3+" __version__ = "1.2.0" __maintainer__ = "Bob Mottram" __email__ = "bob@libreserver.org" __status__ = "Production" __module_group__ = "Web Interface" def _markdown_emphasis_html(markdown: str) -> str: """Add italics and bold html markup to the given markdown """ replacements = { ' **': ' ', '** ': ' ', '**.': '.', '**:': ':', '**;': ';', '**,': ',', '**\n': '\n', ' *': ' ', '* ': ' ', '*.': '.', '*:': ':', '*;': ';', '*,': ',', '*\n': '\n', ' _': '
' + lineStr + '\n' result += lineStr prevQuoteLine = lineStr if '\n' in result: result = result.replace('\n', '') if result.endswith('\n') and \ not markdown.endswith('\n'): result = result[:len(result) - 1] return result def _markdown_replace_links(markdown: str, images: bool = False) -> str: """Replaces markdown links with html Optionally replace image links """ replaceLinks = {} text = markdown startChars = '[' if images: startChars = '![' while startChars in text: if ')' not in text: break text = text.split(startChars, 1)[1] markdownLink = startChars + text.split(')')[0] + ')' if ']' not in markdownLink or \ '(' not in markdownLink: text = text.split(')', 1)[1] continue if not images: replaceLinks[markdownLink] = \ '' + \ markdownLink.split(startChars)[1].split(']')[0] + \ '' else: replaceLinks[markdownLink] = \ '' text = text.split(')', 1)[1] for mdLink, htmlLink in replaceLinks.items(): markdown = markdown.replace(mdLink, htmlLink) return markdown def markdown_to_html(markdown: str) -> str: """Converts markdown formatted text to html """ markdown = _markdown_replace_quotes(markdown) markdown = _markdown_emphasis_html(markdown) markdown = _markdown_replace_links(markdown, True) markdown = _markdown_replace_links(markdown) # replace headers linesList = markdown.split('\n') htmlStr = '' ctr = 0 titles = { "h5": '#####', "h4": '####', "h3": '###', "h2": '##', "h1": '#' } for line in linesList: if ctr > 0: htmlStr += '