From 7dbaaa267acf51a1fbae79bfd30973053c3b7c0a Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Fri, 26 Feb 2021 15:20:43 +0000 Subject: [PATCH] Support for markdown images --- tests.py | 6 ++++-- webapp_utils.py | 44 +++++++++++++++++++++++++++++++------------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/tests.py b/tests.py index ddab940d4..9fee74c7d 100644 --- a/tests.py +++ b/tests.py @@ -3306,14 +3306,16 @@ def testMarkdownToHtml(): markdown = \ 'This is [a link](https://something.somewhere) to something.\n' + \ - 'And [something else](https://cat.pic).' + 'And [something else](https://cat.pic).\n' + \ + 'Or ![pounce](/cat.jpg).' assert markdownToHtml(markdown) == \ 'This is ' + \ 'a link to something.
' + \ 'And ' + \ - 'something else.' + 'something else.
' + \ + 'Or pounce.' def runAllTests(): diff --git a/webapp_utils.py b/webapp_utils.py index 5c3983bc2..b8519bb90 100644 --- a/webapp_utils.py +++ b/webapp_utils.py @@ -66,31 +66,49 @@ def _markdownEmphasisHtml(markdown: str) -> str: return markdown -def markdownToHtml(markdown: str) -> str: - """Converts markdown formatted text to html +def _markdownReplaceLinks(markdown: str, images=False) -> str: + """Replaces markdown links with html """ - markdown = _markdownEmphasisHtml(markdown) - # replace markdown style links with html links replaceLinks = {} text = markdown - while '[' in text: + startChars = '[' + if images: + startChars = '![' + while startChars in text: if ')' not in text: break - text = text.split('[', 1)[1] - markdownLink = '[' + text.split(')')[0] + ')' + 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 - replaceLinks[markdownLink] = \ - '' + \ - markdownLink.split('[')[1].split(']')[0] + \ - '' + if not images: + replaceLinks[markdownLink] = \ + '' + \ + markdownLink.split(startChars)[1].split(']')[0] + \ + '' + else: + replaceLinks[markdownLink] = \ + '' + \
+                markdownLink.split(startChars)[1].split(']')[0] + \
+                '' 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 = _markdownEmphasisHtml(markdown) + markdown = _markdownReplaceLinks(markdown, True) + markdown = _markdownReplaceLinks(markdown) # replace headers linesList = markdown.split('\n')