MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / FootnoteBlockProcessor

Class FootnoteBlockProcessor

markdown/extensions/footnotes.py:246–343  ·  view source on GitHub ↗

Find footnote definitions and store for later use.

Source from the content-addressed store, hash-verified

244
245
246class FootnoteBlockProcessor(BlockProcessor):
247 """ Find footnote definitions and store for later use. """
248
249 RE = re.compile(r'^[ ]{0,3}\[\^([^\]]*)\]:[ ]*(.*)$', re.MULTILINE)
250
251 def __init__(self, footnotes: FootnoteExtension):
252 super().__init__(footnotes.parser)
253 self.footnotes = footnotes
254
255 def test(self, parent: etree.Element, block: str) -> bool:
256 return True
257
258 def run(self, parent: etree.Element, blocks: list[str]) -> bool:
259 """ Find, set, and remove footnote definitions. """
260 block = blocks.pop(0)
261
262 m = self.RE.search(block)
263 if m:
264 preceding = block[:m.start()]
265 # Record the definitions which are directly followed by another
266 # definition in this pass rather than one per pass through the block
267 # processors.
268 for m2 in self.RE.finditer(block, m.end()):
269 if block[m.end():m2.start()].strip('\n'):
270 break
271 self.footnotes.setFootnote(m.group(1), m.group(2).rstrip())
272 m = m2
273
274 id = m.group(1)
275 fn_blocks = [m.group(2)]
276
277 # Handle rest of block
278 therest = block[m.end():].lstrip('\n')
279 m2 = self.RE.search(therest)
280 if m2:
281 # Another footnote exists in the rest of this block.
282 # Any content before match is continuation of this footnote, which may be lazily indented.
283 before = therest[:m2.start()].rstrip('\n')
284 fn_blocks[0] = '\n'.join([fn_blocks[0], self.detab(before)]).lstrip('\n')
285 # Add back to blocks everything from beginning of match forward for next iteration.
286 blocks.insert(0, therest[m2.start():])
287 else:
288 # All remaining lines of block are continuation of this footnote, which may be lazily indented.
289 fn_blocks[0] = '\n'.join([fn_blocks[0], self.detab(therest)]).strip('\n')
290
291 # Check for child elements in remaining blocks.
292 fn_blocks.extend(self.detectTabbed(blocks))
293
294 footnote = "\n\n".join(fn_blocks)
295 self.footnotes.setFootnote(id, footnote.rstrip())
296
297 if preceding.strip():
298 # Add any content before match back to blocks as separate block
299 blocks.insert(0, preceding.rstrip('\n'))
300 return True
301 # No match. Restore block.
302 blocks.insert(0, block)
303 return False

Callers 1

extendMarkdownMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected