Skip to content

Commit 016251e

Browse files
authored
ensure that explicitly provided heading conversion functions are used (#212) (#214)
Signed-off-by: chrispy <chrispy@synopsys.com>
1 parent 0e1a849 commit 016251e

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

markdownify/__init__.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -363,16 +363,20 @@ def get_conv_fn(self, tag_name):
363363
if not self.should_convert_tag(tag_name):
364364
return None
365365

366-
# Handle headings with convert_hN() function
366+
# Look for an explicitly defined conversion function by tag name first
367+
convert_fn_name = "convert_%s" % re_make_convert_fn_name.sub("_", tag_name)
368+
convert_fn = getattr(self, convert_fn_name, None)
369+
if convert_fn:
370+
return convert_fn
371+
372+
# If tag is any heading, handle with convert_hN() function
367373
match = re_html_heading.match(tag_name)
368374
if match:
369-
n = int(match.group(1))
375+
n = int(match.group(1)) # get value of N from <hN>
370376
return lambda el, text, parent_tags: self.convert_hN(n, el, text, parent_tags)
371377

372-
# For other tags, look up their conversion function by tag name
373-
convert_fn_name = "convert_%s" % re_make_convert_fn_name.sub('_', tag_name)
374-
convert_fn = getattr(self, convert_fn_name, None)
375-
return convert_fn
378+
# No conversion function was found
379+
return None
376380

377381
def should_convert_tag(self, tag):
378382
"""Given a tag name, return whether to convert based on strip/convert options."""

tests/test_custom_converter.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ def convert_custom_tag(self, el, text, parent_tags):
1414
"""Ensure conversion function is found for tags with special characters in name"""
1515
return "convert_custom_tag(): %s" % text
1616

17+
def convert_h1(self, el, text, parent_tags):
18+
"""Ensure explicit heading conversion function is used"""
19+
return "convert_h1: %s" % (text)
20+
1721
def convert_hN(self, n, el, text, parent_tags):
18-
"""Ensure conversion function is found for headings"""
22+
"""Ensure general heading conversion function is used"""
1923
return "convert_hN(%d): %s" % (n, text)
2024

2125

@@ -29,6 +33,8 @@ def md(html, **options):
2933

3034
assert md("<custom-tag>text</custom-tag>") == "convert_custom_tag(): text"
3135

36+
assert md("<h1>text</h1>") == "convert_h1: text"
37+
3238
assert md("<h3>text</h3>") == "convert_hN(3): text"
3339

3440

0 commit comments

Comments
 (0)