From 75249cf554f7992ce56b986109ad90302ac4c3c3 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Thu, 25 Feb 2021 10:54:38 +0000 Subject: [PATCH] Markdown emphasis --- tests.py | 16 ++++++++++++++-- webapp_utils.py | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/tests.py b/tests.py index fcacfd4be..ddab940d4 100644 --- a/tests.py +++ b/tests.py @@ -3288,17 +3288,29 @@ def testMarkdownToHtml(): markdown = 'This is just plain text' assert markdownToHtml(markdown) == markdown + markdown = 'This is **bold**' + assert markdownToHtml(markdown) == 'This is bold' + + markdown = 'This is *italic*' + assert markdownToHtml(markdown) == 'This is italic' + + markdown = 'This is _underlined_' + assert markdownToHtml(markdown) == 'This is ' + + markdown = 'This is **just** plain text' + assert markdownToHtml(markdown) == 'This is just plain text' + markdown = '# Title1\n### Title3\n## Title2\n' assert markdownToHtml(markdown) == \ '

Title1

Title3

Title2

' markdown = \ - 'This is [a link](https://something.somewhere) to something\n' + \ + 'This is [a link](https://something.somewhere) to something.\n' + \ 'And [something else](https://cat.pic).' assert markdownToHtml(markdown) == \ 'This is ' + \ - 'a link to something
' + \ + 'a link to something.
' + \ 'And ' + \ 'something else.' diff --git a/webapp_utils.py b/webapp_utils.py index 9d144d3b3..4d7c25f8b 100644 --- a/webapp_utils.py +++ b/webapp_utils.py @@ -21,9 +21,34 @@ from content import addHtmlTags from content import replaceEmojiFromTags +def _markdownEmphasisHtml(markdown: str) -> str: + """Add italics and bold html markup to the given markdown + """ + punctuation = ('.', ';', ':') + noPunctuation = markdown + for ch in punctuation: + noPunctuation = noPunctuation.replace(ch, ' ') + wordList = noPunctuation.split(' ') + replacements = {} + for word in wordList: + if word.startswith('**') and word.endswith('**'): + replacements[word] = \ + '' + word.replace('*', '') + '' + elif word.startswith('*') and word.endswith('*'): + replacements[word] = \ + '' + word.replace('*', '') + '' + elif word.startswith('_') and word.endswith('_'): + replacements[word] = \ + '' + for md, html in replacements.items(): + markdown = markdown.replace(md, html) + return markdown + + def markdownToHtml(markdown: str) -> str: """Converts markdown formatted text to html """ + markdown = _markdownEmphasisHtml(markdown) # replace markdown style links with html links replaceLinks = {} text = markdown