Skip to content

Ensure that explicitly provided heading conversion functions are used (#212) #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,16 +363,20 @@ def get_conv_fn(self, tag_name):
if not self.should_convert_tag(tag_name):
return None

# Handle headings with convert_hN() function
# Look for an explicitly defined conversion function by tag name first
convert_fn_name = "convert_%s" % re_make_convert_fn_name.sub("_", tag_name)
convert_fn = getattr(self, convert_fn_name, None)
if convert_fn:
return convert_fn

# If tag is any heading, handle with convert_hN() function
match = re_html_heading.match(tag_name)
if match:
n = int(match.group(1))
n = int(match.group(1)) # get value of N from <hN>
return lambda el, text, parent_tags: self.convert_hN(n, el, text, parent_tags)

# For other tags, look up their conversion function by tag name
convert_fn_name = "convert_%s" % re_make_convert_fn_name.sub('_', tag_name)
convert_fn = getattr(self, convert_fn_name, None)
return convert_fn
# No conversion function was found
return None

def should_convert_tag(self, tag):
"""Given a tag name, return whether to convert based on strip/convert options."""
Expand Down
8 changes: 7 additions & 1 deletion tests/test_custom_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ def convert_custom_tag(self, el, text, parent_tags):
"""Ensure conversion function is found for tags with special characters in name"""
return "convert_custom_tag(): %s" % text

def convert_h1(self, el, text, parent_tags):
"""Ensure explicit heading conversion function is used"""
return "convert_h1: %s" % (text)

def convert_hN(self, n, el, text, parent_tags):
"""Ensure conversion function is found for headings"""
"""Ensure general heading conversion function is used"""
return "convert_hN(%d): %s" % (n, text)


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

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

assert md("<h1>text</h1>") == "convert_h1: text"

assert md("<h3>text</h3>") == "convert_hN(3): text"


Expand Down