From 8ad19ef23bbf6024d68308641432c0f345795b33 Mon Sep 17 00:00:00 2001 From: chrispy Date: Sun, 29 Jun 2025 08:25:35 -0400 Subject: [PATCH] support backticks in spans (#226) Signed-off-by: chrispy --- markdownify/__init__.py | 23 ++++++++++++++++++++--- tests/test_conversions.py | 3 +++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 72c5214..e901d10 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -41,6 +41,9 @@ # confused with a list item re_escape_misc_list_items = re.compile(r'((?:\s|^)[0-9]{1,9})([.)](?:\s|$))') +# Find consecutive backtick sequences in a string +re_backtick_runs = re.compile(r'`+') + # Heading styles ATX = 'atx' ATX_CLOSED = 'atx_closed' @@ -480,10 +483,24 @@ def convert_br(self, el, text, parent_tags): return ' \n' def convert_code(self, el, text, parent_tags): - if 'pre' in parent_tags: + if '_noformat' in parent_tags: return text - converter = abstract_inline_conversion(lambda self: '`') - return converter(self, el, text, parent_tags) + + prefix, suffix, text = chomp(text) + if not text: + return '' + + # Find the maximum number of consecutive backticks in the text, then + # delimit the code span with one more backtick than that + max_backticks = max((len(match) for match in re.findall(re_backtick_runs, text)), default=0) + markup_delimiter = '`' * (max_backticks + 1) + + # If the maximum number of backticks is greater than zero, add a space + # to avoid interpretation of inside backticks as literals + if max_backticks > 0: + text = " " + text + " " + + return '%s%s%s%s%s' % (prefix, markup_delimiter, text, markup_delimiter, suffix) convert_del = abstract_inline_conversion(lambda self: '~~') diff --git a/tests/test_conversions.py b/tests/test_conversions.py index 825559b..dd99dfb 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -101,6 +101,9 @@ def test_code(): assert md('foo bar baz') == '`foo bar baz`' assert md('foobarbaz', sup_symbol='^') == '`foobarbaz`' assert md('foobarbaz', sub_symbol='^') == '`foobarbaz`' + assert md('foo`bar`baz') == 'foo`` `bar` ``baz' + assert md('foo``bar``baz') == 'foo``` ``bar`` ```baz' + assert md('foo `bar` baz') == 'foo `` `bar` `` baz' def test_dl():