diff --git a/CHANGES.md b/CHANGES.md index 10aabd33..e5c183e6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,7 @@ ## python-markdown2 2.5.6 (not yet released) +- [pull #777] Give each reference to a repeated footnote its own id instead of repeating `fnref-` - [pull #762] Speed up documents with many links by skipping the backslash-escape scan for text without a backslash - [pull #748] Speed up `_unescape_special_chars` by skipping text with no hashes and dropping the full-text comparison per pass (#635) - [pull #749] URL-encode destinations generated by the `link-patterns` extra (#55) diff --git a/lib/markdown2.py b/lib/markdown2.py index d6285404..84f1c92a 100755 --- a/lib/markdown2.py +++ b/lib/markdown2.py @@ -427,6 +427,7 @@ def _setup_extras(self): self.footnotes = OrderedDict() self.footnote_ids = [] self._footnote_numbers = {} + self._footnote_ref_counts = {} 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): @@ -598,6 +599,15 @@ def footnote_sub(match): ) return str(self._footnote_numbers[normed_id]) + def footnote_ref_id_sub(match): + # Every reference needs its own id. The first one in the document keeps `fnref-`, + # which the footnote's back link points to, and later ones get `fnref2-` and so on. + normed_id = match.group(1) + count = self._footnote_ref_counts.get(normed_id, 0) + 1 + self._footnote_ref_counts[normed_id] = count + return 'fnref-%s' % normed_id if count == 1 else 'fnref%d-%s' % (count, normed_id) + + text = re.sub(r'%s-ref-([^"]*)' % self._footnote_marker, footnote_ref_id_sub, text) return re.sub(r'%s-(.*?)(?=)' % self._footnote_marker, footnote_sub, text) @mark_stage(Stage.POSTPROCESS) @@ -3373,7 +3383,7 @@ def run(self, text: str): normed_id = re.sub(r'\W', '-', link_text[1:]) if normed_id in self.md.footnotes: result = ( - f'' + f'' # insert special footnote marker that's easy to find and match against later f'{self.md._footnote_marker}-{normed_id}' ) diff --git a/test/tm-cases/repeated_footnote_labels.html b/test/tm-cases/repeated_footnote_labels.html index 201708f0..0ceae2c0 100644 --- a/test/tm-cases/repeated_footnote_labels.html +++ b/test/tm-cases/repeated_footnote_labels.html @@ -1,16 +1,16 @@ -

First1, second2, and first again1.

+

First1, second2, and first again1.

    -
  • Second again2.
  • +
  • Second again2.
  • Third3.
  • -
  • First again1.
  • +
  • First again1.

  1. -

    Second note referencing first1. ↩

    +

    Second note referencing first1. ↩

  2. @@ -18,7 +18,7 @@
  3. -

    Third note referencing second2. ↩

    +

    Third note referencing second2. ↩