Skip to content
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
13 changes: 13 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ and this project adheres to the
[Python Version Specification](https://packaging.python.org/en/latest/specifications/version-specifiers/).
See the [Contributing Guide](contributing.md) for details.

## Unreleased

### Fixed

* Footnote definitions are no longer recognized within a footnote definition,
matching PHP Markdown Extra: an indented definition nested in another
footnote's content now remains as text in the parent footnote instead of
being silently dropped and leaving references pointing at a missing
`#fn:` anchor (#1681). When the `footnotes` extension is enabled, link
reference definitions can no longer use an identifier starting with `^`,
which is footnote definition syntax; without the extension the core
behavior is unchanged.

## [3.11.4] - 2026-11-25

### Fixed
Expand Down
48 changes: 46 additions & 2 deletions markdown/extensions/footnotes.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from __future__ import annotations

from . import Extension
from ..blockprocessors import BlockProcessor
from ..blockprocessors import BlockProcessor, ReferenceProcessor
from ..inlinepatterns import InlineProcessor
from ..treeprocessors import Treeprocessor
from ..postprocessors import Postprocessor
Expand Down Expand Up @@ -89,6 +89,7 @@ def extendMarkdown(self, md):
| Class Instance | Registry | Name | Priority |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------ | :------: |
| [`FootnoteBlockProcessor`][markdown.extensions.footnotes.FootnoteBlockProcessor] | [`blockprocessors`][markdown.blockprocessors.build_block_parser] | `footnote` | `17` |
| [`FootnoteReferenceProcessor`][markdown.extensions.footnotes.FootnoteReferenceProcessor] | [`blockprocessors`][markdown.blockprocessors.build_block_parser] | `reference` | `15` |
| [`FootnoteInlineProcessor`][markdown.extensions.footnotes.FootnoteInlineProcessor] | [`inlinepatterns`][markdown.inlinepatterns.build_inlinepatterns] | `footnote` | `175` |
| [`FootnoteTreeprocessor`][markdown.extensions.footnotes.FootnoteTreeprocessor] | [`treeprocessors`][markdown.treeprocessors.build_treeprocessors] | `footnote` | `50` |
| [`FootnoteReorderingProcessor`][markdown.extensions.footnotes.FootnoteReorderingProcessor] | [`treeprocessors`][markdown.treeprocessors.build_treeprocessors] | `footnote-reorder` | `19` |
Expand All @@ -103,6 +104,12 @@ def extendMarkdown(self, md):
# Insert a `blockprocessor` before `ReferencePreprocessor`
md.parser.blockprocessors.register(FootnoteBlockProcessor(self), 'footnote', 17)

# Replace the core `ReferenceProcessor` (same name and priority)
# while this extension is loaded, so a definition starting with
# `^` is never taken as a link reference. Without the extension
# the core processor -- and its behavior -- is untouched.
md.parser.blockprocessors.register(FootnoteReferenceProcessor(md.parser), 'reference', 15)

# Insert an inline pattern before `ImageReferencePattern`
FOOTNOTE_RE = r'\[\^([^\]]*)\]' # blah blah [^1] blah
md.inlinePatterns.register(FootnoteInlineProcessor(FOOTNOTE_RE, self), 'footnote', 175)
Expand Down Expand Up @@ -134,6 +141,10 @@ def reset(self) -> None:
self.found_refs = {}
self.used_refs = set()
self.last_refs = {}
# While footnote content is being rendered, definitions found in it
# are not recognized (matching PHP Markdown Extra): a definition
# nested in another footnote's content remains part of that content.
self.parsing_footnotes = False

def unique_ref(self, reference: str, found: bool = False) -> str:
""" Get a unique reference if there are duplicates. """
Expand Down Expand Up @@ -226,7 +237,11 @@ def makeFootnotesDiv(self, root: etree.Element) -> etree.Element | None:
# Parse footnote with surrogate parent as `li` cannot be used.
# List block handlers have special logic to deal with `li`.
# When we are done parsing, we will copy everything over to `li`.
self.parser.parseChunk(surrogate_parent, self.footnotes[id])
self.parsing_footnotes = True
try:
self.parser.parseChunk(surrogate_parent, self.footnotes[id])
finally:
self.parsing_footnotes = False
for el in list(surrogate_parent):
li.append(el)
surrogate_parent.remove(el)
Expand All @@ -250,6 +265,28 @@ def makeFootnotesDiv(self, root: etree.Element) -> etree.Element | None:
return div


class FootnoteReferenceProcessor(ReferenceProcessor):
""" Process link references, except footnote definitions.

The core knows nothing about extensions, so the core
`ReferenceProcessor` is replaced -- only while this extension is
loaded -- with one that does not treat a definition whose
identifier starts with `^` as a link reference: that is footnote
definition syntax. This matters inside footnote content, where
the `FootnoteBlockProcessor` is disabled: without this, a nested
definition would be swallowed as a link reference instead of
remaining as text in the parent footnote.

The pattern is `ReferenceProcessor.RE` with a negative look-ahead
for a leading `^` on the identifier; keep the two in sync.
"""

RE = re.compile(
r'^[ ]{0,3}\[((?!\^)[^\[\]]*)\]:[ ]*(?:\n[ ]*)?([^\s]+)[ ]*(?:\n[ ]*)?((["\'])(.*)\4[ ]*|\((.*)\)[ ]*)?$',
re.MULTILINE
)


class FootnoteBlockProcessor(BlockProcessor):
""" Find footnote definitions and store for later use. """

Expand All @@ -266,6 +303,13 @@ def run(self, parent: etree.Element, blocks: list[str]) -> bool:
""" Find, set, and remove footnote definitions. """
block = blocks.pop(0)

if self.footnotes.parsing_footnotes:
# Footnote definitions are not recognized within a footnote
# definition. Leave the block as content of the footnote
# currently being rendered.
blocks.insert(0, block)
return False

m = self.RE.search(block)
if m:
preceding = block[:m.start()]
Expand Down
12 changes: 12 additions & 0 deletions tests/test_syntax/blocks/test_reference_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ def test_reference_link(self):
'<p><a href="http://example.com">Text</a></p>'
)

def test_reference_link_with_caret_id(self):
"""A `^`-leading id is still a link reference without extensions.

The `footnotes` extension (see #1681) stops treating such ids as
link references while it is loaded, but the core must keep
working as normal on its own.
"""
self.assertMarkdownRenders(
'[Text][^a]\n\n[^a]: http://example.com',
'<p><a href="http://example.com">Text</a></p>'
)

def test_reference_link_split_across_lines(self):
self.assertMarkdownRenders(
'[Text][id]\n\n[id]:\nhttp://example.com',
Expand Down
61 changes: 61 additions & 0 deletions tests/test_syntax/extensions/test_footnotes.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,67 @@ def test_footnote_reference_within_footnote_definition(self):
'</div>'
)

def test_indented_footnote_definition_within_footnote_definition(self):
"""Test an indented footnote definition within a footnote definition.

Footnote definitions are not recognized within a footnote definition
(matching PHP Markdown Extra): the nested definition remains as text
in the parent footnote rather than being dropped or extracted.
"""

self.assertMarkdownRenders(
self.dedent(
"""
Main[^1].

[^1]: First

[^2]: Second
"""
),
'<p>Main<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup>.</p>\n'
'<div class="footnote">\n'
'<hr />\n'
'<ol>\n'
'<li id="fn:1">\n'
'<p>First</p>\n'
'<p>[^2]: Second&#160;<a class="footnote-backref" href="#fnref:1" '
'title="Jump back to footnote 1 in the text">&#8617;</a></p>\n'
'</li>\n'
'</ol>\n'
'</div>'
)

def test_referenced_indented_footnote_definition_within_footnote_definition(self):
"""Test a reference to an indented definition nested in a footnote.

As the nested definition is not recognized, the reference is not
resolved either and remains as text; no dead `#fn:2` anchor is made.
"""

self.assertMarkdownRenders(
self.dedent(
"""
Main[^1].

[^1]: First [^2]

[^2]: Second
"""
),
'<p>Main<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup>.</p>\n'
'<div class="footnote">\n'
'<hr />\n'
'<ol>\n'
'<li id="fn:1">\n'
'<p>First [^2]</p>\n'
'<p>[^2]: Second&#160;<a class="footnote-backref" href="#fnref:1" '
'title="Jump back to footnote 1 in the text">&#8617;</a></p>\n'
'</li>\n'
'</ol>\n'
'</div>'
)

def test_footnote_reference_within_blockquote(self):
"""Test footnote reference within a blockquote."""

Expand Down
Loading