diff --git a/CHANGES.md b/CHANGES.md index fca4b40f..d4cbf5ef 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -5,6 +5,7 @@ - [pull #605] Add support for Python 3.13, drop EOL 3.8 - [pull #607] Fix `middle-word-em` extra preventing strongs from being recognized (#606) - [pull #609] Add option to output to file in CLI (#608) +- [pull #612] Fix footnote labels appearing out-of-order (#536) ## python-markdown2 2.5.1 diff --git a/lib/markdown2.py b/lib/markdown2.py index aec13cb8..f2c6cc28 100755 --- a/lib/markdown2.py +++ b/lib/markdown2.py @@ -405,6 +405,7 @@ def _setup_extras(self): # https://docs.python.org/3/whatsnew/3.7.html#summary-release-highlights self.footnotes = OrderedDict() self.footnote_ids = [] + self._footnote_marker = _hash_text('<>') if "header-ids" in self.extras: if not hasattr(self, '_count_from_header_id') or self.extras['header-ids'].get('reset-count', False): self._count_from_header_id = defaultdict(int) @@ -510,6 +511,12 @@ def convert(self, text: str) -> 'UnicodeWithAttrs': text = self._run_block_gamut(text) if "footnotes" in self.extras: + def footnote_sub(match): + normed_id = match.group(1) + self.footnote_ids.append(normed_id) + return str(len(self.footnote_ids)) + + text = re.sub(r'%s-(.*?)(?=)' % self._footnote_marker, footnote_sub, text) text = self._add_footnotes(text) text = self.postprocess(text) @@ -1581,10 +1588,10 @@ def _do_links(self, text: str) -> str: if "footnotes" in self.extras and link_text.startswith("^"): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.footnotes: - self.footnote_ids.append(normed_id) result = ( f'' - f'{len(self.footnote_ids)}' + # insert special footnote marker that's easy to find and match against later + f'{self._footnote_marker}-{normed_id}' ) text = text[:start_idx] + result + text[p+1:] else: diff --git a/test/tm-cases/footnotes_order_of_appearance.html b/test/tm-cases/footnotes_order_of_appearance.html index fb983d3e..803a5821 100644 --- a/test/tm-cases/footnotes_order_of_appearance.html +++ b/test/tm-cases/footnotes_order_of_appearance.html @@ -2,12 +2,12 @@

title: testing the footnotes bug

-

Lorem ipsum dolor sit amet. Aliqua cillum, eu velit.3 Velit deserunt adipiscing adipiscing ullamco exercitation.

+

Lorem ipsum dolor sit amet. Aliqua cillum, eu velit.1 Velit deserunt adipiscing adipiscing ullamco exercitation.

Lorem ipsum dolor sit amet. Adipiscing4 adipiscing ullamco, exercitation sint. Exercitation sint, fugiat exercitation voluptate amet.