diff --git a/markdownify/__init__.py b/markdownify/__init__.py index d946d2c..4f89c13 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -573,6 +573,8 @@ def convert_hN(self, n, el, text, parent_tags): hashes = '#' * n if style == ATX_CLOSED: return '\n\n%s %s %s\n\n' % (hashes, text, hashes) + # A final run of hashes after a space (or alone) would close the heading. + text = re.sub(r'(^| )(#+)$', r'\1\\\2', text) return '\n\n%s %s\n\n' % (hashes, text) def convert_hr(self, el, text, parent_tags): diff --git a/tests/test_conversions.py b/tests/test_conversions.py index c95483c..ff7dbfe 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -223,6 +223,13 @@ def test_hn_atx_headings(): assert md('

Hello

', heading_style=ATX) == '\n\n## Hello\n\n' +def test_hn_literal_trailing_hashes(): + assert md('

Issue #

', heading_style=ATX) == '\n\n# Issue \\#\n\n' + assert md('

###

') == '\n\n### \\###\n\n' + assert md('

C#

') == '\n\n### C#\n\n' + assert md('

Issue #

', heading_style=ATX_CLOSED) == '\n\n## Issue # ##\n\n' + + def test_hn_atx_closed_headings(): assert md('

Hello

', heading_style=ATX_CLOSED) == '\n\n# Hello #\n\n' assert md('

Hello

', heading_style=ATX_CLOSED) == '\n\n## Hello ##\n\n'