| 1 |
# Python-Markdown Markdown in HTML Extension |
| 2 |
# =============================== |
| 3 |
|
| 4 |
# An implementation of [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/)'s |
| 5 |
# parsing of Markdown syntax in raw HTML. |
| 6 |
|
| 7 |
# See https://Python-Markdown.github.io/extensions/raw_html |
| 8 |
# for documentation. |
| 9 |
|
| 10 |
# Copyright The Python Markdown Project |
| 11 |
|
| 12 |
# License: [BSD](https://opensource.org/licenses/bsd-license.php) |
| 13 |
|
| 14 |
""" |
| 15 |
Parse Markdown syntax within raw HTML. |
| 16 |
Based on the implementation in [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/). |
| 17 |
|
| 18 |
See the [documentation](https://Python-Markdown.github.io/extensions/raw_html) |
| 19 |
for details. |
| 20 |
""" |
| 21 |
|
| 22 |
from __future__ import annotations |
| 23 |
|
| 24 |
from . import Extension |
| 25 |
from ..blockprocessors import BlockProcessor |
| 26 |
from ..preprocessors import Preprocessor |
| 27 |
from ..postprocessors import RawHtmlPostprocessor |
| 28 |
from .. import util |
| 29 |
from ..htmlparser import HTMLExtractor, blank_line_re |
| 30 |
import xml.etree.ElementTree as etree |
| 31 |
from typing import TYPE_CHECKING, Literal, Mapping |
| 32 |
|
| 33 |
if TYPE_CHECKING: # pragma: no cover |
| 34 |
from markdown import Markdown |
| 35 |
|
| 36 |
|
| 37 |
class HTMLExtractorExtra(HTMLExtractor): |
| 38 |
""" |
| 39 |
Override `HTMLExtractor` and create `etree` `Elements` for any elements which should have content parsed as |
| 40 |
Markdown. |
| 41 |
""" |
| 42 |
|
| 43 |
def __init__(self, md: Markdown, *args, **kwargs): |
| 44 |
# All block-level tags. |
| 45 |
self.block_level_tags = set(md.block_level_elements.copy()) |
| 46 |
# Block-level tags in which the content only gets span level parsing |
| 47 |
self.span_tags = set( |
| 48 |
['address', 'dd', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'legend', 'li', 'p', 'summary', 'td', 'th'] |
| 49 |
) |
| 50 |
# Block-level tags which never get their content parsed. |
| 51 |
self.raw_tags = set(['canvas', 'math', 'option', 'pre', 'script', 'style', 'textarea']) |
| 52 |
|
| 53 |
super().__init__(md, *args, **kwargs) |
| 54 |
|
| 55 |
# Block-level tags in which the content gets parsed as blocks |
| 56 |
self.block_tags = set(self.block_level_tags) - (self.span_tags | self.raw_tags | self.empty_tags) |
| 57 |
self.span_and_blocks_tags = self.block_tags | self.span_tags |
| 58 |
|
| 59 |
def reset(self): |
| 60 |
"""Reset this instance. Loses all unprocessed data.""" |
| 61 |
self.mdstack: list[str] = [] # When markdown=1, stack contains a list of tags |
| 62 |
self.treebuilder = etree.TreeBuilder() |
| 63 |
self.mdstate: list[Literal['block', 'span', 'off', None]] = [] |
| 64 |
self.mdstarted: list[bool] = [] |
| 65 |
super().reset() |
| 66 |
|
| 67 |
def close(self): |
| 68 |
"""Handle any buffered data.""" |
| 69 |
super().close() |
| 70 |
# Handle any unclosed tags. |
| 71 |
if self.mdstack: |
| 72 |
# Close the outermost parent. `handle_endtag` will close all unclosed children. |
| 73 |
self.handle_endtag(self.mdstack[0]) |
| 74 |
|
| 75 |
def get_element(self) -> etree.Element: |
| 76 |
""" Return element from `treebuilder` and reset `treebuilder` for later use. """ |
| 77 |
element = self.treebuilder.close() |
| 78 |
self.treebuilder = etree.TreeBuilder() |
| 79 |
return element |
| 80 |
|
| 81 |
def get_state(self, tag, attrs: Mapping[str, str]) -> Literal['block', 'span', 'off', None]: |
| 82 |
""" Return state from tag and `markdown` attribute. One of 'block', 'span', or 'off'. """ |
| 83 |
md_attr = attrs.get('markdown', '0') |
| 84 |
if md_attr == 'markdown': |
| 85 |
# `<tag markdown>` is the same as `<tag markdown='1'>`. |
| 86 |
md_attr = '1' |
| 87 |
parent_state = self.mdstate[-1] if self.mdstate else None |
| 88 |
if parent_state == 'off' or (parent_state == 'span' and md_attr != '0'): |
| 89 |
# Only use the parent state if it is more restrictive than the markdown attribute. |
| 90 |
md_attr = parent_state |
| 91 |
if ((md_attr == '1' and tag in self.block_tags) or |
| 92 |
(md_attr == 'block' and tag in self.span_and_blocks_tags)): |
| 93 |
return 'block' |
| 94 |
elif ((md_attr == '1' and tag in self.span_tags) or |
| 95 |
(md_attr == 'span' and tag in self.span_and_blocks_tags)): |
| 96 |
return 'span' |
| 97 |
elif tag in self.block_level_tags: |
| 98 |
return 'off' |
| 99 |
else: # pragma: no cover |
| 100 |
return None |
| 101 |
|
| 102 |
def handle_starttag(self, tag, attrs): |
| 103 |
# Handle tags that should always be empty and do not specify a closing tag |
| 104 |
if tag in self.empty_tags and (self.at_line_start() or self.intail): |
| 105 |
attrs = {key: value if value is not None else key for key, value in attrs} |
| 106 |
if "markdown" in attrs: |
| 107 |
attrs.pop('markdown') |
| 108 |
element = etree.Element(tag, attrs) |
| 109 |
data = etree.tostring(element, encoding='unicode', method='html') |
| 110 |
else: |
| 111 |
data = self.get_starttag_text() |
| 112 |
self.handle_empty_tag(data, True) |
| 113 |
return |
| 114 |
|
| 115 |
if ( |
| 116 |
tag in self.block_level_tags and |
| 117 |
(self.at_line_start() or self.intail or self.mdstarted and self.mdstarted[-1]) |
| 118 |
): |
| 119 |
# Valueless attribute (ex: `<tag checked>`) results in `[('checked', None)]`. |
| 120 |
# Convert to `{'checked': 'checked'}`. |
| 121 |
attrs = {key: value if value is not None else key for key, value in attrs} |
| 122 |
state = self.get_state(tag, attrs) |
| 123 |
if self.inraw or (state in [None, 'off'] and not self.mdstack): |
| 124 |
# fall back to default behavior |
| 125 |
attrs.pop('markdown', None) |
| 126 |
super().handle_starttag(tag, attrs) |
| 127 |
else: |
| 128 |
if 'p' in self.mdstack and tag in self.block_level_tags: |
| 129 |
# Close unclosed 'p' tag |
| 130 |
self.handle_endtag('p') |
| 131 |
self.mdstate.append(state) |
| 132 |
self.mdstack.append(tag) |
| 133 |
self.mdstarted.append(True) |
| 134 |
attrs['markdown'] = state |
| 135 |
self.treebuilder.start(tag, attrs) |
| 136 |
|
| 137 |
else: |
| 138 |
# Span level tag |
| 139 |
if self.inraw: |
| 140 |
super().handle_starttag(tag, attrs) |
| 141 |
else: |
| 142 |
text = self.get_starttag_text() |
| 143 |
if self.mdstate and self.mdstate[-1] == "off": |
| 144 |
self.handle_data(self.md.htmlStash.store(text)) |
| 145 |
else: |
| 146 |
self.handle_data(text) |
| 147 |
if tag in self.CDATA_CONTENT_ELEMENTS: |
| 148 |
# This is presumably a standalone tag in a code span (see #1036). |
| 149 |
self.clear_cdata_mode() |
| 150 |
|
| 151 |
def handle_endtag(self, tag): |
| 152 |
if tag in self.block_level_tags: |
| 153 |
if self.inraw: |
| 154 |
super().handle_endtag(tag) |
| 155 |
elif tag in self.mdstack: |
| 156 |
# Close element and any unclosed children |
| 157 |
while self.mdstack: |
| 158 |
item = self.mdstack.pop() |
| 159 |
self.mdstate.pop() |
| 160 |
self.mdstarted.pop() |
| 161 |
self.treebuilder.end(item) |
| 162 |
if item == tag: |
| 163 |
break |
| 164 |
if not self.mdstack: |
| 165 |
# Last item in stack is closed. Stash it |
| 166 |
element = self.get_element() |
| 167 |
# Get last entry to see if it ends in newlines |
| 168 |
# If it is an element, assume there is no newlines |
| 169 |
item = self.cleandoc[-1] if self.cleandoc else '' |
| 170 |
# If we only have one newline before block element, add another |
| 171 |
if not item.endswith('\n\n') and item.endswith('\n'): |
| 172 |
self.cleandoc.append('\n') |
| 173 |
|
| 174 |
# Flatten the HTML structure of "markdown" blocks such that when they |
| 175 |
# get parsed, content will be parsed similar inside the blocks as it |
| 176 |
# does outside the block. Having real HTML elements in the tree before |
| 177 |
# the content adjacent content is processed can cause unpredictable |
| 178 |
# issues for extensions. |
| 179 |
current = element |
| 180 |
last = [] |
| 181 |
while current is not None: |
| 182 |
for child in list(current): |
| 183 |
current.remove(child) |
| 184 |
text = current.text if current.text is not None else '' |
| 185 |
tail = child.tail if child.tail is not None else '' |
| 186 |
child.tail = None |
| 187 |
state = child.attrib.get('markdown', 'off') |
| 188 |
|
| 189 |
# Add a newline to tail if it is not just a trailing newline |
| 190 |
if tail != '\n': |
| 191 |
tail = '\n' + tail.rstrip('\n') |
| 192 |
|
| 193 |
# Ensure there is an empty new line between blocks |
| 194 |
if not text.endswith('\n\n'): |
| 195 |
text = text.rstrip('\n') + '\n\n' |
| 196 |
|
| 197 |
# Process the block nested under the span appropriately |
| 198 |
if state in ('span', 'block'): |
| 199 |
current.text = f'{text}{self.md.htmlStash.store(child)}{tail}' |
| 200 |
last.append(child) |
| 201 |
else: |
| 202 |
# Non-Markdown HTML will not be recursively parsed for Markdown, |
| 203 |
# so we can just remove markers and leave them unflattened. |
| 204 |
# Additionally, we don't need to append to our list for further |
| 205 |
# processing. |
| 206 |
child.attrib.pop('markdown') |
| 207 |
[c.attrib.pop('markdown', None) for c in child.iter()] |
| 208 |
current.text = f'{text}{self.md.htmlStash.store(child)}{tail}' |
| 209 |
# Target the child elements that have been expanded. |
| 210 |
current = last.pop(0) if last else None |
| 211 |
|
| 212 |
self.cleandoc.append(self.md.htmlStash.store(element)) |
| 213 |
self.cleandoc.append('\n\n') |
| 214 |
self.state = [] |
| 215 |
# Check if element has a tail |
| 216 |
if not blank_line_re.match( |
| 217 |
self.rawdata[self.line_offset + self.offset + len(self.get_endtag_text(tag)):]): |
| 218 |
# More content exists after `endtag`. |
| 219 |
self.intail = True |
| 220 |
else: |
| 221 |
# Treat orphan closing tag as a span level tag. |
| 222 |
text = self.get_endtag_text(tag) |
| 223 |
if self.mdstate and self.mdstate[-1] == "off": |
| 224 |
self.handle_data(self.md.htmlStash.store(text)) |
| 225 |
else: |
| 226 |
self.handle_data(text) |
| 227 |
else: |
| 228 |
# Span level tag |
| 229 |
if self.inraw: |
| 230 |
super().handle_endtag(tag) |
| 231 |
else: |
| 232 |
text = self.get_endtag_text(tag) |
| 233 |
if self.mdstate and self.mdstate[-1] == "off": |
| 234 |
self.handle_data(self.md.htmlStash.store(text)) |
| 235 |
else: |
| 236 |
self.handle_data(text) |
| 237 |
|
| 238 |
def handle_startendtag(self, tag, attrs): |
| 239 |
if tag in self.empty_tags: |
| 240 |
attrs = {key: value if value is not None else key for key, value in attrs} |
| 241 |
if "markdown" in attrs: |
| 242 |
attrs.pop('markdown') |
| 243 |
element = etree.Element(tag, attrs) |
| 244 |
data = etree.tostring(element, encoding='unicode', method='html') |
| 245 |
else: |
| 246 |
data = self.get_starttag_text() |
| 247 |
else: |
| 248 |
data = self.get_starttag_text() |
| 249 |
self.handle_empty_tag(data, is_block=self.md.is_block_level(tag)) |
| 250 |
|
| 251 |
def handle_data(self, data): |
| 252 |
if self.intail and '\n' in data: |
| 253 |
self.intail = False |
| 254 |
if self.inraw or not self.mdstack: |
| 255 |
super().handle_data(data) |
| 256 |
else: |
| 257 |
self.mdstarted[-1] = False |
| 258 |
self.treebuilder.data(data) |
| 259 |
|
| 260 |
def handle_empty_tag(self, data, is_block): |
| 261 |
if self.inraw or not self.mdstack: |
| 262 |
super().handle_empty_tag(data, is_block) |
| 263 |
else: |
| 264 |
if self.at_line_start() and is_block: |
| 265 |
self.handle_data('\n' + self.md.htmlStash.store(data) + '\n\n') |
| 266 |
elif self.mdstate and self.mdstate[-1] == "off": |
| 267 |
self.handle_data(self.md.htmlStash.store(data)) |
| 268 |
else: |
| 269 |
self.handle_data(data) |
| 270 |
|
| 271 |
def parse_pi(self, i: int) -> int: |
| 272 |
if self.at_line_start() or self.intail or self.mdstack: |
| 273 |
# The same override exists in `HTMLExtractor` without the check |
| 274 |
# for `mdstack`. Therefore, use parent of `HTMLExtractor` instead. |
| 275 |
return super(HTMLExtractor, self).parse_pi(i) |
| 276 |
# This is not the beginning of a raw block so treat as plain data |
| 277 |
# and avoid consuming any tags which may follow (see #1066). |
| 278 |
self.handle_data('<?') |
| 279 |
return i + 2 |
| 280 |
|
| 281 |
def parse_html_declaration(self, i: int) -> int: |
| 282 |
if self.at_line_start() or self.intail or self.mdstack: |
| 283 |
if self.rawdata[i:i+3] == '<![' and not self.rawdata[i:i+9] == '<![CDATA[': |
| 284 |
# We have encountered the bug in #1534 (Python bug `gh-77057`). |
| 285 |
# Provide an override until we drop support for Python < 3.13. |
| 286 |
result = self.parse_bogus_comment(i) |
| 287 |
if result == -1: |
| 288 |
self.handle_data(self.rawdata[i:i + 1]) |
| 289 |
return i + 1 |
| 290 |
return result |
| 291 |
# The same override exists in `HTMLExtractor` without the check |
| 292 |
# for `mdstack`. Therefore, use parent of `HTMLExtractor` instead. |
| 293 |
return super(HTMLExtractor, self).parse_html_declaration(i) |
| 294 |
# This is not the beginning of a raw block so treat as plain data |
| 295 |
# and avoid consuming any tags which may follow (see #1066). |
| 296 |
self.handle_data('<!') |
| 297 |
return i + 2 |
| 298 |
|
| 299 |
|
| 300 |
class HtmlBlockPreprocessor(Preprocessor): |
| 301 |
"""Remove html blocks from the text and store them for later retrieval.""" |
| 302 |
|
| 303 |
def run(self, lines: list[str]) -> list[str]: |
| 304 |
source = '\n'.join(lines) |
| 305 |
parser = HTMLExtractorExtra(self.md) |
| 306 |
parser.feed(source) |
| 307 |
parser.close() |
| 308 |
return ''.join(parser.cleandoc).split('\n') |
| 309 |
|
| 310 |
|
| 311 |
class MarkdownInHtmlProcessor(BlockProcessor): |
| 312 |
"""Process Markdown Inside HTML Blocks which have been stored in the `HtmlStash`.""" |
| 313 |
|
| 314 |
def test(self, parent: etree.Element, block: str) -> bool: |
| 315 |
# Always return True. `run` will return `False` it not a valid match. |
| 316 |
return True |
| 317 |
|
| 318 |
def parse_element_content(self, element: etree.Element) -> None: |
| 319 |
""" |
| 320 |
Recursively parse the text content of an `etree` Element as Markdown. |
| 321 |
|
| 322 |
Any block level elements generated from the Markdown will be inserted as children of the element in place |
| 323 |
of the text content. All `markdown` attributes are removed. For any elements in which Markdown parsing has |
| 324 |
been disabled, the text content of it and its children are wrapped in an `AtomicString`. |
| 325 |
""" |
| 326 |
|
| 327 |
md_attr = element.attrib.pop('markdown', 'off') |
| 328 |
|
| 329 |
if md_attr == 'block': |
| 330 |
# Parse the block elements content as Markdown |
| 331 |
if element.text: |
| 332 |
block = element.text.rstrip('\n') |
| 333 |
element.text = '' |
| 334 |
self.parser.parseBlocks(element, block.split('\n\n')) |
| 335 |
|
| 336 |
elif md_attr == 'span': |
| 337 |
# Span elements need to be recursively processed for block elements and raw HTML |
| 338 |
# as their content is not normally accessed by block processors, so expand stashed |
| 339 |
# HTML under the span. Span content itself will not be parsed here, but will await |
| 340 |
# the inline parser. |
| 341 |
block = element.text if element.text is not None else '' |
| 342 |
element.text = '' |
| 343 |
child = None |
| 344 |
start = 0 |
| 345 |
|
| 346 |
# Search the content for HTML placeholders and process the elements |
| 347 |
for m in util.HTML_PLACEHOLDER_RE.finditer(block): |
| 348 |
index = int(m.group(1)) |
| 349 |
el = self.parser.md.htmlStash.rawHtmlBlocks[index] |
| 350 |
end = m.start() |
| 351 |
|
| 352 |
if isinstance(el, etree.Element): |
| 353 |
# Replace the placeholder with the element and process it. |
| 354 |
# Content after the placeholder should be attached to the tail. |
| 355 |
if child is None: |
| 356 |
element.text += block[start:end] |
| 357 |
else: |
| 358 |
child.tail += block[start:end] |
| 359 |
element.append(el) |
| 360 |
self.parse_element_content(el) |
| 361 |
child = el |
| 362 |
if child.tail is None: |
| 363 |
child.tail = '' |
| 364 |
self.parser.md.htmlStash.rawHtmlBlocks.pop(index) |
| 365 |
self.parser.md.htmlStash.rawHtmlBlocks.insert(index, '') |
| 366 |
|
| 367 |
else: |
| 368 |
# Not an element object, so insert content back into the element |
| 369 |
if child is None: |
| 370 |
element.text += block[start:end] |
| 371 |
else: |
| 372 |
child.tail += block[start:end] |
| 373 |
start = end |
| 374 |
|
| 375 |
# Insert anything left after last element |
| 376 |
if child is None: |
| 377 |
element.text += block[start:] |
| 378 |
else: |
| 379 |
child.tail += block[start:] |
| 380 |
|
| 381 |
else: |
| 382 |
# Disable inline parsing for everything else |
| 383 |
if element.text is None: |
| 384 |
element.text = '' |
| 385 |
element.text = util.AtomicString(element.text) |
| 386 |
for child in list(element): |
| 387 |
self.parse_element_content(child) |
| 388 |
if child.tail: |
| 389 |
child.tail = util.AtomicString(child.tail) |
| 390 |
|
| 391 |
def run(self, parent: etree.Element, blocks: list[str]) -> bool: |
| 392 |
m = util.HTML_PLACEHOLDER_RE.match(blocks[0]) |
| 393 |
if m: |
| 394 |
index = int(m.group(1)) |
| 395 |
element = self.parser.md.htmlStash.rawHtmlBlocks[index] |
| 396 |
if isinstance(element, etree.Element): |
| 397 |
# We have a matched element. Process it. |
| 398 |
block = blocks.pop(0) |
| 399 |
parent.append(element) |
| 400 |
self.parse_element_content(element) |
| 401 |
# Cleanup stash. Replace element with empty string to avoid confusing postprocessor. |
| 402 |
self.parser.md.htmlStash.rawHtmlBlocks.pop(index) |
| 403 |
self.parser.md.htmlStash.rawHtmlBlocks.insert(index, '') |
| 404 |
content = block[m.end(0):] |
| 405 |
# Ensure the rest of the content gets handled |
| 406 |
if content: |
| 407 |
blocks.insert(0, content) |
| 408 |
# Confirm the match to the `blockparser`. |
| 409 |
return True |
| 410 |
# No match found. |
| 411 |
return False |
| 412 |
|
| 413 |
|
| 414 |
class MarkdownInHTMLPostprocessor(RawHtmlPostprocessor): |
| 415 |
def stash_to_string(self, text: str | etree.Element) -> str: |
| 416 |
""" Override default to handle any `etree` elements still in the stash. """ |
| 417 |
if isinstance(text, etree.Element): |
| 418 |
return self.md.serializer(text) |
| 419 |
else: |
| 420 |
return str(text) |
| 421 |
|
| 422 |
|
| 423 |
class MarkdownInHtmlExtension(Extension): |
| 424 |
"""Add Markdown parsing in HTML to Markdown class.""" |
| 425 |
|
| 426 |
def extendMarkdown(self, md): |
| 427 |
""" Register the processors. |
| 428 |
|
| 429 |
| Class Instance | Registry | Name | Priority | |
| 430 |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------ | :------: | |
| 431 |
| [`HtmlBlockPreprocessor`][markdown.extensions.md_in_html.HtmlBlockPreprocessor] | [`preprocessors`][markdown.preprocessors.build_preprocessors] | `html_block` | `20` | |
| 432 |
| [`MarkdownInHtmlProcessor`][markdown.extensions.md_in_html.MarkdownInHtmlProcessor] | [`blockprocessors`][markdown.blockprocessors.build_block_parser] | `markdown_block` | `105` | |
| 433 |
| [`MarkdownInHTMLPostprocessor`][markdown.extensions.md_in_html.MarkdownInHTMLPostprocessor] | [`postprocessors`][markdown.postprocessors.build_postprocessors] | `raw_html` | `30` | |
| 434 |
|
| 435 |
""" |
| 436 |
# flake8: noqa: E501 429-433 |
| 437 |
# Replace raw HTML preprocessor |
| 438 |
md.preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20) |
| 439 |
# Add `blockprocessor` which handles the placeholders for `etree` elements |
| 440 |
md.parser.blockprocessors.register( |
| 441 |
MarkdownInHtmlProcessor(md.parser), 'markdown_block', 105 |
| 442 |
) |
| 443 |
# Replace raw HTML postprocessor |
| 444 |
md.postprocessors.register(MarkdownInHTMLPostprocessor(md), 'raw_html', 30) |
| 445 |
|
| 446 |
|
| 447 |
def makeExtension(**kwargs): # pragma: no cover |
| 448 |
return MarkdownInHtmlExtension(**kwargs) |