__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 _markdownEmphasisHtml(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 _markdownReplaceLinks(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 markdownToHtml(markdown: str) -> str: """Converts markdown formatted text to html """ markdown = _markdownReplaceQuotes(markdown) markdown = _markdownEmphasisHtml(markdown) markdown = _markdownReplaceLinks(markdown, True) markdown = _markdownReplaceLinks(markdown) # replace headers linesList = markdown.split('\n') htmlStr = '' ctr = 0 titles = { "h5": '#####', "h4": '####', "h3": '###', "h2": '##', "h1": '#' } for line in linesList: if ctr > 0: htmlStr += '