Skip to content

Commit 48724e7

Browse files
authored
support backticks in <code> spans (#226) (#230)
Signed-off-by: chrispy <chrispy@synopsys.com>
1 parent 9b1412a commit 48724e7

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

markdownify/__init__.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@
4141
# confused with a list item
4242
re_escape_misc_list_items = re.compile(r'((?:\s|^)[0-9]{1,9})([.)](?:\s|$))')
4343

44+
# Find consecutive backtick sequences in a string
45+
re_backtick_runs = re.compile(r'`+')
46+
4447
# Heading styles
4548
ATX = 'atx'
4649
ATX_CLOSED = 'atx_closed'
@@ -480,10 +483,24 @@ def convert_br(self, el, text, parent_tags):
480483
return ' \n'
481484

482485
def convert_code(self, el, text, parent_tags):
483-
if 'pre' in parent_tags:
486+
if '_noformat' in parent_tags:
484487
return text
485-
converter = abstract_inline_conversion(lambda self: '`')
486-
return converter(self, el, text, parent_tags)
488+
489+
prefix, suffix, text = chomp(text)
490+
if not text:
491+
return ''
492+
493+
# Find the maximum number of consecutive backticks in the text, then
494+
# delimit the code span with one more backtick than that
495+
max_backticks = max((len(match) for match in re.findall(re_backtick_runs, text)), default=0)
496+
markup_delimiter = '`' * (max_backticks + 1)
497+
498+
# If the maximum number of backticks is greater than zero, add a space
499+
# to avoid interpretation of inside backticks as literals
500+
if max_backticks > 0:
501+
text = " " + text + " "
502+
503+
return '%s%s%s%s%s' % (prefix, markup_delimiter, text, markup_delimiter, suffix)
487504

488505
convert_del = abstract_inline_conversion(lambda self: '~~')
489506

tests/test_conversions.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ def test_code():
101101
assert md('<code>foo<s> bar </s>baz</code>') == '`foo bar baz`'
102102
assert md('<code>foo<sup>bar</sup>baz</code>', sup_symbol='^') == '`foobarbaz`'
103103
assert md('<code>foo<sub>bar</sub>baz</code>', sub_symbol='^') == '`foobarbaz`'
104+
assert md('foo<code>`bar`</code>baz') == 'foo`` `bar` ``baz'
105+
assert md('foo<code>``bar``</code>baz') == 'foo``` ``bar`` ```baz'
106+
assert md('foo<code> `bar` </code>baz') == 'foo `` `bar` `` baz'
104107

105108

106109
def test_dl():

0 commit comments

Comments
 (0)