Debian Codegraph @

docs/src/markdown/extensions/blocks/api.md

raw
1 ---
2 icon: lucide/book-open
3 ---
4 # Blocks Extension API
5
6 ## Block Structure
7
8 The various different block types are created via the `Block` class. The `Block` class can define all the various parts
9 and handling of the various block parts. The basic structure of a block is shown below:
10
11 ```
12 /// name | argument
13 options: per block options
14
15 Markdown content.
16 ///
17 ```
18
19 ## Block Extension Anatomy
20
21 Normally with Python Markdown, you'd create a processor derived from the various processor types available in the
22 library. You'd then derive an extension from `markdown.Extension` that would register the processor. Block extensions
23 are very similar.
24
25 A Block extension is comprised of two parts: the `Block` object and the `BlocksExtension`. It should be noted that we do
26 not use `markdown.Extension`, but `BlocksExtension` which is derived from it. This is done so we can abstract away the
27 management of all the various registered `Block` extensions. It is important to note though that when using the
28 `BlocksExtension` that we do not override the `extendMarkdown` method, but instead override `extendMarkdownBlocks`. In
29 all other respects, `BlocksExtension` is just like `markdown.Extension` and you can register traditional processors via
30 the `md` object or register `Block` objects via the `block_mgr` object.
31
32 Below we have the very bare minimum required to create an extension.
33
34 ```py
35 from pymdownx.blocks import BlocksExtension
36 from pymdownx.blocks.block import Block
37 import xml.etree.ElementTree as etree
38
39 class MyBlock(Block):
40 NAME = 'my-block'
41
42 def on_create(self, parent):
43
44 return etree.SubElement(parent, 'div')
45
46
47 class MyBlockExtension(BlocksExtension):
48
49 def extendMarkdownBlocks(self, md, block_mgr):
50
51 block_mgr.register(MyBlock, self.getConfigs())
52
53
54 def makeExtension(*args, **kwargs):
55 """Return extension."""
56
57 return MyBlockExtension(*args, **kwargs)
58 ```
59
60 Then we can register and run it:
61
62 ```py
63 import markdown
64
65 MD = """
66 /// my-block
67 content
68 ///
69 """
70
71 print(markdown.markdown(MD, extensions=[MyBlockExtension()]))
72 ```
73
74 /// html | div.result
75 ```html
76 <div>
77 <p>content</p>
78 </div>
79 ```
80 ///
81
82 ## The Block Object
83
84 The block object allows us to define the name of a block, whether an argument and/or options are allowed, and how we
85 generally handle the content.
86
87 ## Global Options
88
89 Global options are often set in the `BlocksExtension` object like traditional extensions. They are meant to globally
90 control the behavior of a specific block type:
91
92 ```python
93 class AdmonitionExtension(BlocksExtension):
94 """Admonition Blocks Extension."""
95
96 def __init__(self, *args, **kwargs):
97 """Initialize."""
98
99 self.config = {
100 "types": [
101 ['note', 'attention', 'caution', 'danger', 'error', 'tip', 'hint', 'warning'],
102 "Generate Admonition block extensions for the given types."
103 ]
104 }
105
106 super().__init__(*args, **kwargs)
107 ```
108
109 These options are available in the instantiated `Block` object via the `self.config` attribute.
110
111 ## Tracking Data Across Blocks
112
113 There are times when it can be useful to store data across multiple blocks. Each block instance has access to a tracker
114 that is specific to a specific block type and persists across all blocks. It is only cleared when `reset` is called on
115 the `Markdown` object.
116
117 The tracker is accessed by a given `Block` extension via the `self.tracker` attribute. The attribute contains a
118 dictionary where various keys and values can be stored. This can be used to count blocks on a page or anything else you
119 can think of.
120
121 ## Accessing the Markdown Object
122
123 Some plugins occasionally need access to the current Markdown object. If this is needed, it can be accessed via the
124 class attribute `self.md`.
125
126 ## Argument
127
128 The argument is used to declare a common block specific input for a particular block type. This is often, but not
129 exclusively, used for things like titles. It is specified on the same line as the initial block deceleration.
130
131 Blocks are not required to use an argument and it is not required by default and must be declared as either optional or
132 required in order for the block to accept an argument. An argument is declared by setting `ARGUMENT` to `#!py True` if
133 it is required, `#!py None` if it is optionally allowed, or `#!py False` if it is not allowed.
134
135 The argument is always parsed as a single string, if it is desired to validate the format of the argument or even to
136 process it as multiple arguments, this can be done in the [`on_validate` event](#on_validate-event).
137
138 ```python
139 class MyBlock(Block):
140 # Name used for the block
141 NAME = 'my-block'
142 ARGUMENT = True
143 ```
144
145 ## Options
146
147 Options is how a block specifies any per block features via an indented YAML block immediately after the block
148 declaration. The YAML indented block is considered a part of the header and is great for options that don't make sense
149 as part of the first line declaration.
150
151 An option consists of a keyword to specify the option name, and then a list containing the default value and a validator
152 callback. The callback function should take the input and validate the type and/or coerce the value to an appropriate
153 value. If the input, for whatever reason, is deemed invalid, the callback function should raise an error.
154
155 After processing, all options will be available as a dictionary via the instance attribute `self.options`. Options
156 will be accessible via the keyword and will return the resolved value.
157
158 /// tip | Built-in validators
159 A number of Built-in validators are provided. Check out [Built-in Validators](#built-in-validators) to learn more,
160 or feel free to write your own.
161 ///
162
163 ```py
164 class MyBlock(Block):
165 # Name used for the block
166 NAME = 'my-block'
167 OPTIONS = {
168 'tag_name': ('default', type_html_indentifier)
169 }
170 ```
171
172 /// warning
173 `attrs` is a reserved option that is automatically applied to all `Block` extensions. This should not be overridden.
174 `attrs` takes a dictionary of `str` keys and `str` values describing the attributes to apply to the outer element of
175 the block as returned by the [`on_create`](#on_create-event).
176
177 The `attrs` input is sent through [`type_html_attribute_dict`](#type_html_attribute_dict) and is accessible to
178 developers via `self.options['attrs']`. The result is a dictionary of key/value pairs where the key is a `#!py3 str` and
179 the value is a `#!py3 str` (or `#!py3 list[str]` in the special case of `class`).
180 ///
181
182 ## `is_raw`
183
184 ```py
185 def is_raw(self, tag: Element) -> bool:
186 ...
187 ```
188
189 This method, given a tag will determine if the block should be considered a "raw" tag based on the Blocks extension's
190 internal logic.
191
192 ## `is_block`
193
194 ```py
195 def is_block(self, tag: Element) -> bool:
196 ...
197 ```
198
199 This method, given a tag will determine if the block should be considered a "block" tag based on the Blocks extension's
200 internal logic.
201
202
203 ## `html_escape`
204
205 ```py
206 def html_escape(self, text: str) -> str:
207 ...
208 ```
209
210 Takes a string intended for an HTML tag's content and returns it after applying HTML escaping on it. Escapes `&`, `<`,
211 and `>`.
212
213 ## `on_init` Event
214
215 ```py
216 def on_init(self) -> None:
217 ...
218 ```
219
220 The `on_init` event is run every time a new block class is instantiated. This is usually where a specific block type
221 would handle global options and initialize class variables that are needed. If the specified block name in Markdown
222 matches the name of a registered block, that block class will be instantiated, triggering the `on_init` event to
223 execute. Each block in a document that is encountered generates its own, new instance.
224
225 Only the global `config` is available at this time via `self.config`. The `Markdown` object is also available via
226 `self.md`.
227
228 The can be a good way to perform setup based on global or local options.
229
230 ## `on_validate` Event
231
232 ```py
233 def on_validate(self, parent: Element) -> bool:
234 ...
235 ```
236
237 Executed right after the per block argument and option parsing occurs. The argument and options are accessible via
238 `self.argument` and `self.options`. `parent` is the current parent element.
239
240 `on_validate` is a hook meant to allow the developer to invalidate a block if the options, argument, or even the parent
241 element do not meet some arbitrary criteria. This hook can also be used to make adjustments variables and even do some
242 initialization of class variables based on the results of specific options, arguments, or even the parent element.
243
244 If validation fails, `#!py3 False` should be returned and the block will not be parsed as a generic block.
245
246 ## `on_create` Event
247
248 ```py
249 def on_create(self, parent: Element) -> Element:
250 ...
251 ```
252
253 Called when a block is initially found and initialized. The `on_create` method should create the container for the block
254 under the parent element. Other child elements can be created on the root of the container, but outer element of the
255 created container should be returned.
256
257 ## `on_add` Event
258
259 ```py
260 def on_add(self, block: Element) -> Element:
261 ...
262 ```
263
264 When any calls occur to process new content, `on_add` is called. This gives the block a chance to return the element
265 where the content is desired.
266
267 This can be useful if the outer element is not the element where the content should go. Keep in mind that content can
268 also be rearranged if needed in the [`on_end` event](#on_end-event).
269
270 ## `on_markdown` Event
271
272 ```py
273 def on_markdown(self) -> str:
274 """Check how element should be treated by the Markdown parser."""
275 ...
276 ```
277
278 The `on_markdown` event is used to declare how the content of the block should be handled by the Markdown parser. A
279 string with one of the following values _must_ be returned. All content is treated as HTML content and is stored under
280 the [etree][etree] element returned via the [`on_add` event](#on_add-event).
281
282 Only during the [`on_end` event](#on_end-event) will all the content be fully accumulated and processed by relevant
283 block processors, and only during the [`on_inline_end` event](#on_inline_end-event) will both block and inline
284 processing be completed.
285
286 Result\ Value | Description
287 ------------- | -----------
288 `block` | Parsed block content will be handled by the Markdown parser as content under a block element.
289 `inline` | Parsed block content will be handled by the Markdown parser as content under an inline element.
290 `raw` | Parsed block content will be preserved as is. No additional Markdown parsing will be applied. Content is expected to be indented and should be documented as such.
291 `auto` | Depending on whether the wrapping parent is a block element, inline element, or something like a code element, Blocks will choose the best approach for the content. Decision is made based on the element returned by the [`on_add` event](#on_add-event).
292
293 When using `raw` mode, all text will be accumulated under the specified element as an [`AtomicString`][atomic]. If
294 nothing is done with the content during the [`on_end` event](#on_end-event), all the content will be HTML escaped by the
295 Python Markdown parser. If desired, the content can be placed into the Python Markdown [HTML stash][stash] which will
296 protect it from any other rouge Treeprocessors. Keep in mind, if the content is stashed, HTML escaping will not be
297 applied automatically, so HTML escape if it is required.
298
299 /// warning | Indent Raw Content
300 Because Python Markdown implements HTML processing as a preprocessor, content for a `raw` block must be indented 4
301 spaces to avoid the HTML processing step. The content will not be indented when it reaches the [`on_end` event](#on_end-event).
302 Failure to indent will still allow the code to be processed, but it may not process as expected. An extension that uses
303 `raw` should make clear that this is a requirement to avoid unexpected results.
304 ///
305
306 ## `on_end` Event
307
308 ```py
309 def on_end(self, block: Element) -> None:
310 ...
311 ```
312
313 When a block is parsed to completion, the `on_end` event is executed. This allows an extension to perform any post
314 processing on the elements. You could save the data as raw text and then parse it special at the end or you could walk
315 the HTML elements and move content around, add attributes, or whatever else is needed.
316
317 ## `on_inline_end` Event
318
319 ```py
320 def on_inline_end(self, block: Element) -> None:
321 ...
322 ```
323
324 When a block is parsed to completion and all inline parsing has been applied, the `on_inline_end` event is executed. It
325 is the very last event for a block. This allows an extension to perform any post processing on an element _after_ inline
326 processing.
327
328 ## Built-in Validators
329
330 A number of validators are provided via for the purpose of validating [YAML option inputs](#options). If what you need
331 is not present, feel free to write your own. All validators are imported from `pymdownx.blocks.block`.
332
333 ### `type_any`
334
335 ```py
336 def type_any(value: Any) -> Any:
337 ...
338 ```
339
340 This takes a YAML input and simply passes it through. If you do not want to validate the input because it does not need
341 to be checked, or if you just want to do it manually in the [`on_validate` event](#on_validate-event), then this is what
342 you'd want to use.
343
344 ```py
345 class Block:
346 OPTIONS = {'name': ({}, type_any)}
347 ```
348
349 ### `type_none`
350
351 ```py
352 def type_none(value: Any) -> None:
353 ...
354 ```
355
356 This takes a YAML input and ensures it is `None` (or `null`) in YAML. This is most useful paired with other types to
357 indicate the option is "unset". See [`type_multi`](#type_multi) to learn how to combine multiple existing types.
358
359 ```py
360 class Block:
361 OPTIONS = {'name': (none, type_multi(type_none, type_string))}
362 ```
363
364 ### `type_number`
365
366 ```py
367 def type_number(value: Any) -> int | float:
368 ...
369 ```
370
371 Takes a YAML input value and verifies that it is a `float` or `int`.
372
373 Returns the valid number (`float` or `int`) or raises a `ValueError`.
374
375 ```py
376 class Block:
377 OPTIONS = {'keyword': (0.0, type_number)}
378 ```
379
380 ### `type_integer`
381
382 ```py
383 def type_integer(value: Any) -> int:
384 ...
385 ```
386
387 Takes a YAML input value and verifies that it is an `int`.
388
389 Returns the valid `int` or raises a `ValueError`.
390
391 ```py
392 class Block:
393 OPTIONS = {'keyword': (0, type_integer)}
394 ```
395
396 ### `type_ranged_number`
397
398 ```py
399 def type_ranged_number(minimum: int | float = None, maximum: int | float = None) -> Callable[[Any], int | float]:
400 ```
401
402 Takes a `minimum` and/or `maximum` and returns a type function that accepts an input and validates that it is a number
403 (`float` or `int`) that is within the specified range. If `#!py None` is provided for either `minimum` or `maximum`,
404 they will be unbounded.
405
406 Returns the valid number (`float` or `int`) or raises a `ValueError`.
407
408 ```py
409 class Block:
410 OPTIONS = {'keyword': (0.0, type_ranged_number(0.0, 100.0))}
411 ```
412
413 ### `type_ranged_integer`
414
415 ```py
416 def type_ranged_integer(minimum: int = None, maximum: int = None) -> Callable[[Any], int]:
417 ...
418 ```
419
420 Takes a `minimum` and/or `maximum` and returns a type function that accepts an input and validates that it is an `int`
421 that is within the specified range. If `#!py None` is provided for either `minimum` or `maximum`, they will be
422 unbounded.
423
424 Returns the valid `int` or raises a `ValueError`.
425
426 ```py
427 class Block:
428 OPTIONS = {'keyword': (0, type_ranged_integer(0, 100))}
429 ```
430
431 ### `type_boolean`
432
433 ```py
434 def type_boolean(value: Any) -> bool:
435 ...
436 ```
437
438 Takes a YAML input and validates that it is a boolean value.
439
440 Returns the valid boolean or raises a `ValueError`.
441
442 ```py
443 class Block:
444 OPTIONS = {'keyword': (False, type_boolean)}
445 ```
446
447 ### `type_ternary`
448
449 ```py
450 def type_ternary(value: Any) -> bool | None:
451 ...
452 ```
453
454 Takes a YAML input and validates that it is a `bool` value or `#!py None`.
455
456 Returns the valid `bool` or `#!py3 None` or raises a `ValueError`.
457
458 ```py
459 class Block:
460 OPTIONS = {'keyword': (None, type_ternary)}
461 ```
462
463 ### `type_string`
464
465 ```py
466 def type_string(value: Any) -> str:
467 ...
468 ```
469
470 Takes a YAML input and validates that it is a `str` value.
471
472 Returns the valid `str` or raises a `ValueError`.
473
474 ```py
475 class Block:
476 OPTIONS = {'keyword': ('default', type_string)}
477 ```
478
479 ### `type_insensitive_string`
480
481 ```py
482 def type_insensitive_string(value: Any) -> str:
483 ...
484 ```
485
486 Takes a YAML input and validates that it is a `str` value and normalizes it by lower casing it.
487
488 Returns the valid, lowercase `str` or raises a `ValueError`.
489
490 ```py
491 class Block:
492 OPTIONS = {'keyword': ('default', type_insensitive_string)}
493 ```
494
495 ### `type_string_in`
496
497 ```py
498 def type_string_in(value: list[str], insensitive: bool = True) -> Callable[[Any], str]:
499 ...
500 ```
501
502 Takes a list of acceptable string inputs and a boolean indicating whether comparison should be case insensitive. Returns
503 a type function that takes an input and then validates that it is a `str` and that the `str` value is found in the
504 acceptable string list.
505
506 Returns the valid `str` or raises a `ValueError`.
507
508 ```py
509 class Block:
510 OPTIONS = {'keyword': ('this', type_string_in(['this', 'that'], type_insensitive_string))}
511 ```
512
513 ### `type_string_delimiter`
514
515 ```py
516 def type_string_delimiter(value: str, string_type: Callable[[Any], str] = type_string) -> str:
517 ...
518 ```
519
520 Takes a delimiter and string type callback and returns a function that takes an input, verifies that it is a `str`,
521 splits it by the delimiter, and ensures that each part validates with the given string type callback.
522
523 Returns a list of valid `str` values or raises a `ValueError`.
524
525 ```py
526 class Block:
527 OPTIONS = {'keyword': ('default', type_string_delimiter(',' type_insensitive_string))}
528 ```
529
530 ### `type_html_identifier`
531
532 ```py
533 def type_html_identifier(value: Any) -> str:
534 ...
535 ```
536
537 Tests that a string is an "identifier" as described in CSS. This would normally match tag names, IDs, classes, and
538 attribute names. This is useful if you'd like to validate such HTML constructs.
539
540 Returns a `str` that is a valid identifier or raises `ValueError`.
541
542 ```py
543 class Block:
544 OPTIONS = {'keyword': ('default', type_html_indentifier)}
545 ```
546
547 ### `type_html_classes`
548
549 ```py
550 def type_html_classes(value: Any) -> list[str]:
551 ...
552 ```
553
554 Takes a YAML input value and verifies that it is a `str` and treats it as a space delimited input. The input will
555 be split by spaces and each part will be run through `type_html_identifier`.
556
557 Returns a list of `str` that are valid CSS classes or raises `ValueError`.
558
559 ```py
560 class Block:
561 OPTIONS = {'keyword': ('default', type_html_classes)}
562 ```
563
564 ### `type_html_attribute_dict`
565
566 ```py
567 def type_html_classes(value: Any) -> dict[str, Any]:
568 ...
569 ```
570
571 /// note
572 The returned dictionary will have all values set to string except classes which will be a list of strings. The `class`
573 attribute is processed with `type_html_classes`.
574
575 The `id` attribute is also run through `type_html_identifier` to ensure a good ID that can be targeted with traditional
576 CSS selectors: `#!py3 #id`.
577 ///
578
579 Takes a YAML input value and verifies that it is a `dict`. Keys will be verified to be HTML identifiers and the values
580 to be strings.
581
582 Returns a `dict[str, Any]` where the values will either be `str` or `list[str]` as previously noted or raises
583 `ValueError`.
584
585 ```py
586 class Block:
587 OPTIONS = {'attributes': ({}, type_html_attribute_dict)}
588 ```
589
590 ## `type_multi`
591
592 ```py
593 def type_multi(*args: Any) -> Callable[[Any], Any]:
594 ...
595 ```
596
597 Takes a multiple type functions and returns a single type function that takes a YAML input and validates it with all the
598 provided type functions. If the input fails all the validation functions, a `ValueError` is raised.