Debian Codegraph @

docs/extensions/api.md

raw
1 title: Extensions API
2
3 # Writing Extensions for Python-Markdown
4
5 Python-Markdown includes an API for extension writers to plug their own custom functionality and syntax into the
6 parser. An extension will patch into one or more stages of the parser:
7
8 * [*Preprocessors*](#preprocessors) alter the source before it is passed to the parser.
9 * [*Block Processors*](#blockprocessors) work with blocks of text separated by blank lines.
10 * [*Tree Processors*](#treeprocessors) modify the constructed ElementTree
11 * [*Inline Processors*](#inlineprocessors) are common tree processors for inline elements, such as `*strong*`.
12 * [*Postprocessors*](#postprocessors) munge of the output of the parser just before it is returned.
13
14 The parser loads text, applies the preprocessors, creates and builds an [ElementTree][ElementTree] object from the
15 block processors and inline processors, renders the ElementTree object as Unicode text, and then then applies the
16 postprocessors.
17
18 There are classes and helpers provided to ease writing your extension. Each part of the API is discussed in its
19 respective section below. Additionally, you can walk through the [Tutorial on Writing Extensions][tutorial]; browse the
20 [API Reference][markdown] which was generated from the source code; look at some of the [Available Extensions][] and
21 their [source code][extension source]. As always, you may report bugs, ask for help, and discuss various other issues
22 on the [bug tracker].
23
24 ## Phases of processing {: #stages }
25
26 ### Preprocessors {: #preprocessors }
27
28 Preprocessors munge the source text before it is passed to the Markdown parser. This is an excellent place to clean up
29 bad characters or to extract portions for later processing that the parser may otherwise choke on.
30
31 Preprocessors inherit from [`markdown.preprocessors.Preprocessor`][markdown.preprocessors.Preprocessor]
32 and implement a [`run`][markdown.preprocessors.Preprocessor.run] method, which takes a single parameter
33 `lines`. This parameter is the entire source text stored as a list of Unicode strings, one per line.
34 `run` should return its processed list of Unicode strings, one per line.
35
36 #### Example
37
38 This simple example removes any lines with 'NO RENDER' before processing:
39
40 ```python
41 from markdown.preprocessors import Preprocessor
42 import re
43
44 class NoRender(Preprocessor):
45 """ Skip any line with words 'NO RENDER' in it. """
46 def run(self, lines):
47 new_lines = []
48 for line in lines:
49 m = re.search("NO RENDER", line)
50 if not m:
51 # any line without NO RENDER is passed through
52 new_lines.append(line)
53 return new_lines
54 ```
55
56 #### Usages
57
58 Some preprocessors in the Markdown source tree include:
59
60 | Class | Kind | Description |
61 | ------------------------------------------------------------------------|-----------|------------------------------------------------- |
62 | [`NormalizeWhiteSpace`][markdown.preprocessors.NormalizeWhitespace] | built-in | Normalizes whitespace by expanding tabs, fixing `\r` line endings, etc. |
63 | [`HtmlBlockPreprocessor`][markdown.preprocessors.HtmlBlockPreprocessor] | built-in | Removes html blocks from the text and stores them in [`htmlStash`][markdown.util.HtmlStash] for later processing |
64 | [`MetaPreprocessor`][markdown.extensions.meta.MetaPreprocessor] | extension | Strips and records meta data at top of documents |
65
66 ### Block Processors {: #blockprocessors }
67
68 A block processor parses blocks of text and adds new elements to the `ElementTree`. Blocks of text, separated from
69 other text by blank lines, may have a different syntax and produce a differently structured tree than other Markdown.
70 Block processors excel at code formatting, equation layouts, and tables.
71
72 Block processors inherit from [`markdown.blockprocessors.BlockProcessor`][markdown.blockprocessors.BlockProcessor],
73 are passed `md.parser` on initialization, and implement both the [`test`][markdown.blockprocessors.BlockProcessor.test]
74 and [`run`][markdown.blockprocessors.BlockProcessor.run] methods:
75
76 * [`test`][markdown.blockprocessors.BlockProcessor.test]
77 * [`run`][markdown.blockprocessors.BlockProcessor.run]
78
79 Crafting block processors is more involved and flexible than the other processors, involving controlling recursive
80 parsing of the block's contents and managing state across invocations. For example, a blank line is allowed in
81 indented code, so the second invocation of the inline code processor appends to the element tree generated by the
82 previous call. Other block processors may insert new text into the `blocks` list, signal to future calls of itself,
83 and more.
84
85 To make writing these complex beasts more tractable, three convenience functions have been provided by the
86 `BlockProcessor` parent class:
87
88 * [`lastChild`][markdown.blockprocessors.BlockProcessor.lastChild]
89 * [`detab`][markdown.blockprocessors.BlockProcessor.detab]
90 * [`looseDetab`][markdown.blockprocessors.BlockProcessor.looseDetab]
91
92 Also, `BlockProcessor` provides the fields `self.tab_length`, the tab length (default 4), and `self.parser`, the
93 current [`BlockParser`][markdown.blockparser.BlockParser] instance.
94
95 #### BlockParser
96
97 [`BlockParser`][markdown.blockparser.BlockParser], not to be confused with
98 [`BlockProcessor`][markdown.blockprocessors.BlockProcessor], is the class used by Markdown to cycle through all the
99 registered block processors. You should never need to create your own instance; use `self.parser` instead.
100
101 The `BlockParser` instance provides a stack of strings for its current state, which your processor can push with
102 `self.parser.set(state)`, pop with `self.parser.reset()`, or check the the top state with
103 `self.parser.isstate(state)`. Be sure your code pops the states it pushes.
104
105 The `BlockParser` instance can also be called recursively, that is, to process blocks from within your block
106 processor. There are three methods:
107
108 * [`parseDocument`][markdown.blockparser.BlockParser.parseDocument]
109 * [`parseChunk`][markdown.blockparser.BlockParser.parseChunk]
110 * [`parseBlocks`][markdown.blockparser.BlockParser.parseBlocks]
111
112 For perspective, Markdown calls `parseDocument` which calls `parseChunk` which calls `parseBlocks` which calls your
113 block processor, which, in turn, might call one of these routines.
114
115 #### Example
116
117 This example calls out important paragraphs by giving them a border. It looks for a fence line of exclamation points
118 before and after and renders the fenced blocks into a new, styled `div`. If it does not find the ending fence line,
119 it does nothing.
120
121 Our code, like most block processors, is longer than other examples:
122
123 ```python
124 def test_block_processor():
125 class BoxBlockProcessor(BlockProcessor):
126 RE_FENCE_START = r'^ *!{3,} *\n' # start line, e.g., ` !!!! `
127 RE_FENCE_END = r'\n *!{3,}\s*$' # last non-blank line, e.g, '!!!\n \n\n'
128
129 def test(self, parent, block):
130 return re.match(self.RE_FENCE_START, block)
131
132 def run(self, parent, blocks):
133 original_block = blocks[0]
134 blocks[0] = re.sub(self.RE_FENCE_START, '', blocks[0])
135
136 # Find block with ending fence
137 for block_num, block in enumerate(blocks):
138 if re.search(self.RE_FENCE_END, block):
139 # remove fence
140 blocks[block_num] = re.sub(self.RE_FENCE_END, '', block)
141 # render fenced area inside a new div
142 e = etree.SubElement(parent, 'div')
143 e.set('style', 'display: inline-block; border: 1px solid red;')
144 self.parser.parseBlocks(e, blocks[0:block_num + 1])
145 # remove used blocks
146 for i in range(0, block_num + 1):
147 blocks.pop(0)
148 return True # or could have had no return statement
149 # No closing marker! Restore and do nothing
150 blocks[0] = original_block
151 return False # equivalent to our test() routine returning False
152
153 class BoxExtension(Extension):
154 def extendMarkdown(self, md):
155 md.parser.blockprocessors.register(BoxBlockProcessor(md.parser), 'box', 175)
156 ```
157
158 Start with this example input:
159
160 ``` text
161 A regular paragraph of text.
162
163 !!!!!
164 First paragraph of wrapped text.
165
166 Second Paragraph of **wrapped** text.
167 !!!!!
168
169 Another regular paragraph of text.
170 ```
171
172 The fenced text adds one node with two children to the tree:
173
174 * `div`, with a `style` attribute. It renders as
175 `<div style="display: inline-block; border: 1px solid red;">...</div>`
176 * `p` with text `First paragraph of wrapped text.`
177 * `p` with text `Second Paragraph of **wrapped** text`. The conversion to a `<strong>` tag will happen when
178 running the inline processors, which will happen after all of the block processors have completed.
179
180 The example output might display as follows:
181
182 !!! note ""
183 <p>A regular paragraph of text.</p>
184 <div style="display: inline-block; border: 1px solid red;">
185 <p>First paragraph of wrapped text.</p>
186 <p>Second Paragraph of **wrapped** text.</p>
187 </div>
188 <p>Another regular paragraph of text.</p>
189
190 #### Usages
191
192 Some block processors in the Markdown source tree include:
193
194 | Class | Kind | Description |
195 | ---------------------------------------------------------------------------------|-----------|---------------------------------------------|
196 | [`HashHeaderProcessor`][markdown.blockprocessors.HashHeaderProcessor] | built-in | Title hashes (`#`), which may split blocks |
197 | [`HRProcessor`][markdown.blockprocessors.HRProcessor] | built-in | Horizontal lines, e.g., `---` |
198 | [`OListProcessor`][markdown.blockprocessors.OListProcessor] | built-in | Ordered lists; complex and using `state` |
199 | [`AdmonitionProcessor`][markdown.extensions.admonition.AdmonitionProcessor] | extension | Render each [Admonition][] in a new `div` |
200 | [`FootnoteBlockProcessor`][markdown.extensions.footnotes.FootnoteBlockProcessor] | extension | Find footnote definitions and store for later use. |
201
202 [Admonition]: https://python-markdown.github.io/extensions/admonition/
203
204 ### Tree processors {: #treeprocessors }
205
206 Tree processors manipulate the tree created by block processors. They can even create an entirely new ElementTree
207 object. This is an excellent place for creating summaries, adding collected references, or last minute adjustments.
208
209 A tree processor must inherit from [`markdown.treeprocessors.Treeprocessor`][markdown.treeprocessors.Treeprocessor]
210 (note the capitalization). A tree processor must implement a [`run`][markdown.treeprocessors.Treeprocessor.run] method
211 which takes a single argument `root`. In most cases `root` would be an `xml.etree.ElementTree.Element` instance;
212 however, in rare cases it could be some other type of ElementTree object. The `run` method may return `None`, in which
213 case the (possibly modified) original `root` object is used, or it may return an entirely new `Element` object, which
214 will replace the existing `root` object and all of its children. It is generally preferred to modify `root` in place
215 and return `None`, which avoids creating multiple copies of the entire document tree in memory.
216
217 For specifics on manipulating the ElementTree, see [Working with the ElementTree][workingwithetree] below.
218
219 #### Example
220
221 A pseudo example:
222
223 ```python
224 from markdown.treeprocessors import Treeprocessor
225
226 class MyTreeprocessor(Treeprocessor):
227 def run(self, root):
228 root.text = 'modified content'
229 # No return statement is same as `return None`
230 ```
231
232 #### Usages
233
234 The core [`InlineProcessor`][markdown.treeprocessors.InlineProcessor] class is a tree processor. It walks the tree,
235 matches patterns, and splits and creates nodes on matches.
236
237 Additional tree processors in the Markdown source tree include:
238
239 | Class | Kind | Description |
240 | ---------------------------------------------------------------------------------------|-----------|---------------------------------------------------------------|
241 | [`PrettifyTreeprocessor`][markdown.treeprocessors.PrettifyTreeprocessor] | built-in | Add line breaks to the html document |
242 | [`TocTreeprocessor`][markdown.extensions.toc.TocTreeprocessor] | extension | Builds a [table of contents][] from the finished tree |
243 | [`FootnoteTreeprocessor`][markdown.extensions.footnotes.FootnoteTreeprocessor] | extension | Create [footnote][] div at end of document |
244 | [`FootnotePostTreeprocessor`][markdown.extensions.footnotes.FootnotePostTreeprocessor] | extension | Amend div created by `FootnoteTreeprocessor` with duplicates |
245
246 [table of contents]: https://python-markdown.github.io/extensions/toc/
247 [footnote]: https://python-markdown.github.io/extensions/footnotes/
248
249 ### Inline Processors {: #inlineprocessors }
250
251 Inline processors, previously called inline patterns, are used to add formatting, such as `**emphasis**`, by replacing
252 a matched pattern with a new element tree node. It is an excellent place for adding new syntax for inline tags. Inline
253 processor code is often quite short.
254
255 Inline processors inherit from [`InlineProcessor`][markdown.inlinepatterns.InlineProcessor], are initialized, and implement
256 [`handleMatch`][markdown.inlinepatterns.InlineProcessor.handleMatch].
257
258 Inline Processors can define the property `ANCESTOR_EXCLUDES` which is either a list or tuple of undesirable ancestors.
259 The processor will be skipped if it would cause the content to be a descendant of one of the listed tag names.
260
261 ##### Convenience Classes
262
263 Convenience subclasses of `InlineProcessor` are provided for common operations:
264
265 * [`SimpleTextInlineProcessor`][markdown.inlinepatterns.SimpleTextInlineProcessor] returns the text of `group(1)` of the match.
266 * [`SubstituteTagInlineProcessor`][markdown.inlinepatterns.SubstituteTagInlineProcessor] is initialized as
267 `SubstituteTagInlineProcessor(pattern, tag)`. It returns a new element `tag` whenever `pattern` is matched.
268 * [`SimpleTagInlineProcessor`][markdown.inlinepatterns.SimpleTagInlineProcessor] is initialized as
269 `SimpleTagInlineProcessor(pattern, tag)`. It returns an element `tag` with a text field of `group(2)` of the match.
270
271 ##### Example
272
273 This example changes `--strike--` to `<del>strike</del>`.
274
275 ```python
276 from markdown.inlinepatterns import InlineProcessor
277 from markdown.extensions import Extension
278 import xml.etree.ElementTree as etree
279
280
281 class DelInlineProcessor(InlineProcessor):
282 def handleMatch(self, m, data):
283 el = etree.Element('del')
284 el.text = m.group(1)
285 return el, m.start(0), m.end(0)
286
287 class DelExtension(Extension):
288 def extendMarkdown(self, md):
289 DEL_PATTERN = r'--(.*?)--' # like --del--
290 md.inlinePatterns.register(DelInlineProcessor(DEL_PATTERN, md), 'del', 175)
291 ```
292
293 Use this input example:
294
295 ``` text
296 First line of the block.
297 This is --strike one--.
298 This is --strike two--.
299 End of the block.
300 ```
301
302 The example output might display as follows:
303
304 !!! note ""
305 <p>First line of the block.
306 This is <del>strike one</del>.
307 This is <del>strike two</del>.
308 End of the block.</p>
309
310 * On the first call to `handleMatch`
311 * `m` will be the match for `--strike one--`
312 * `data` will be the string:
313 `First line of the block.\nThis is --strike one--.\nThis is --strike two--.\nEnd of the block.`
314
315 Because the match was successful, the region between the returned `start` and `end` are replaced with a
316 placeholder token and the new element is added to the tree.
317
318 * On the second call to `handleMatch`
319 * `m` will be the match for `--strike two--`
320 * `data` will be the string
321 `First line of the block.\nThis is klzzwxh:0000.\nThis is --strike two--.\nEnd of the block.`
322
323 Note the [placeholder][markdown.util.INLINE_PLACEHOLDER_PREFIX] token `klzzwxh:0000`. This allows the
324 regular expression to be run against the entire block, not just the the text contained in an individual element.
325 The placeholders will later be swapped back out for the actual elements by the parser.
326
327 Actually it would not be necessary to create the above inline processor. The fact is, that example is not very DRY
328 (Don't Repeat Yourself). A pattern for `**strong**` text would be almost identical, with the exception that it would
329 create a `strong` element. Therefore, Markdown provides a number of generic `InlineProcessor` subclasses that can
330 provide some common functionality. For example, strike could be implemented with an instance of the
331 [`SimpleTagInlineProcessor`][markdown.inlinepatterns.SimpleTagInlineProcessor] class as demonstrated below. Feel
332 free to use or extend any of the `InlineProcessor` subclasses found at `markdown.inlinepatterns`.
333
334 ```python
335 from markdown.inlinepatterns import SimpleTagInlineProcessor
336 from markdown.extensions import Extension
337
338 class DelExtension(Extension):
339 def extendMarkdown(self, md):
340 md.inlinePatterns.register(SimpleTagInlineProcessor(r'()--(.*?)--', 'del'), 'del', 175)
341 ```
342
343
344 ##### Usages
345
346 Here are some convenience functions and other examples:
347
348 | Class | Kind | Description |
349 | -------------------------------------------------------------------------------------|-----------|---------------------------------------------------------------|
350 | [`AsteriskProcessor`][markdown.inlinepatterns.AsteriskProcessor] | built-in | Emphasis processor for handling strong and em matches inside asterisks |
351 | [`WikiLinksInlineProcessor`][markdown.extensions.wikilinks.WikiLinksInlineProcessor] | extension | Link `[[article names]]` to wiki given in metadata |
352 | [`FootnoteInlineProcessor`][markdown.extensions.footnotes.FootnoteInlineProcessor] | extension | Replaces footnote in text with link to footnote div at bottom |
353
354 ### Patterns
355
356 In version 3.0, a new, more flexible inline processor was added,
357 [`markdown.inlinepatterns.InlineProcessor`][markdown.inlinepatterns.InlineProcessor]. The original inline patterns,
358 which inherit from [`markdown.inlinepatterns.Pattern`][markdown.inlinepatterns.Pattern] or one of its children are still
359 supported, though users are encouraged to migrate.
360
361 #### Comparison with new `InlineProcessor`
362
363 The new `InlineProcessor` provides two major enhancements to `Patterns`:
364
365 1. Inline Processors no longer need to match the entire block, so regular expressions no longer need to start with
366 `r'^(.*?)'` and end with `r'(.*?)%'`. This runs faster. The returned [match object][] will only contain what is
367 explicitly matched in the pattern, and extension pattern groups now start with `m.group(1)`.
368
369 2. The `handleMatch` method now takes an additional input called `data`, which is the entire block under analysis,
370 not just what is matched with the specified pattern. The method now returns the element *and* the indexes relative
371 to `data` that the return element is replacing (usually `m.start(0)` and `m.end(0)`). If the boundaries are
372 returned as `None`, it is assumed that the match did not take place, and nothing will be altered in `data`.
373
374 This allows handling of more complex constructs than regular expressions can handle, e.g., matching nested
375 brackets, and explicit control of the span "consumed" by the processor.
376
377 #### Inline Patterns
378
379 Inline Patterns can implement inline HTML element syntax for Markdown such as `*emphasis*` or
380 `[links](http://example.com)`. Pattern objects should be instances of classes that inherit from
381 `markdown.inlinepatterns.Pattern` or one of its children. Each pattern object uses a single regular expression and
382 must have the following methods:
383
384 * [`getCompiledRegExp`][markdown.inlinepatterns.Pattern.getCompiledRegExp]
385 * [`handleMatch`][markdown.inlinepatterns.Pattern.handleMatch]
386
387 Inline Patterns can define the property `ANCESTOR_EXCLUDES` with is either a list or tuple of undesirable ancestors.
388 The pattern will be skipped if it would cause the content to be a descendant of one of the listed tag names.
389
390 Note that any regular expression returned by `getCompiledRegExp` must capture the whole block. Therefore, they should
391 all start with `r'^(.*?)'` and end with `r'(.*?)!'`. When using the default `getCompiledRegExp()` method provided in
392 the `Pattern` you can pass in a regular expression without that and `getCompiledRegExp` will wrap your expression for
393 you and set the `re.DOTALL` and `re.UNICODE` flags. This means that the first group of your match will be `m.group(2)`
394 as `m.group(1)` will match everything before the pattern.
395
396 For an example, consider this simplified emphasis pattern:
397
398 ```python
399 from markdown.inlinepatterns import Pattern
400 import xml.etree.ElementTree as etree
401
402 class EmphasisPattern(Pattern):
403 def handleMatch(self, m):
404 el = etree.Element('em')
405 el.text = m.group(2)
406 return el
407 ```
408
409 As discussed in [Integrating Your Code Into Markdown][], an instance of this class will need to be provided to
410 Markdown. That instance would be created like so:
411
412 ```python
413 # an oversimplified regex
414 MYPATTERN = r'\*([^*]+)\*'
415 # pass in pattern and create instance
416 emphasis = EmphasisPattern(MYPATTERN)
417 ```
418
419 ### Postprocessors {: #postprocessors }
420
421 Postprocessors munge the document after the ElementTree has been serialized into a string. Postprocessors should be
422 used to work with the text just before output. Usually, they are used to add back sections that were extracted in a
423 preprocessor, fix up outgoing encodings, or wrap the whole document.
424
425 Postprocessors inherit from [`markdown.postprocessors.Postprocessor`][markdown.postprocessors.Postprocessor] and
426 implement a [`run`][markdown.postprocessors.Postprocessor.run] method which takes a single parameter `text`, the
427 entire HTML document as a single Unicode string. `run` should return a single Unicode string ready for output.
428 Note that preprocessors use a list of lines while postprocessors use a single multi-line string.
429
430 #### Example
431
432 Here is a simple example that changes the output to one big page showing the raw html.
433
434 ```python
435 from markdown.postprocessors import Postprocessor
436 import re
437
438 class ShowActualHtmlPostprocesor(Postprocessor):
439 """ Wrap entire output in <pre> tags as a diagnostic. """
440 def run(self, text):
441 return '<pre>\n' + re.sub('<', '&lt;', text) + '</pre>\n'
442 ```
443
444 #### Usages
445
446 Some postprocessors in the Markdown source tree include:
447
448 | Class | Kind | Description |
449 | -----------------------------------------------------------------------------------|-----------|----------------------------------------------------|
450 | [`RawHtmlPostprocessor`][markdown.postprocessors.RawHtmlPostprocessor] | built-in | Restore raw html from [`htmlStash`][markdown.util.HtmlStash], stored by [`HTMLBlockPreprocessor`][markdown.preprocessors.HtmlBlockPreprocessor], and code highlighters |
451 | [`AndSubstitutePostprocessor`][markdown.postprocessors.AndSubstitutePostprocessor] | built-in | Convert ampersand substitutes to `&`; used in links |
452 | [`FootnotePostProcessor`][markdown.extensions.footnotes.FootnotePostprocessor] | extension | Replace footnote placeholders with html entities; as set by other stages |
453
454 ## Working with the ElementTree {: #working_with_et }
455
456 As mentioned, the Markdown parser converts a source document to an [ElementTree][ElementTree] object before
457 serializing that back to Unicode text. Markdown has provided some helpers to ease that manipulation within the context
458 of the Markdown module.
459
460 First, import the ElementTree module:
461
462 ```python
463 import xml.etree.ElementTree as etree
464 ```
465 Sometimes you may want text inserted into an element to be parsed by [Inline Patterns][]. In such a situation, simply
466 insert the text as you normally would and the text will be automatically run through the Inline Patterns. However, if
467 you do *not* want some text to be parsed by Inline Patterns, then insert the text as an `AtomicString`.
468
469 ```python
470 from markdown.util import AtomicString
471 some_element.text = AtomicString(some_text)
472 ```
473
474 Here's a basic example which creates an HTML table (note that the contents of the second cell (`td2`) will be run
475 through Inline Patterns latter):
476
477 ```python
478 table = etree.Element("table")
479 table.set("cellpadding", "2") # Set cellpadding to 2
480 tr = etree.SubElement(table, "tr") # Add child tr to table
481 td1 = etree.SubElement(tr, "td") # Add child td1 to tr
482 td1.text = markdown.util.AtomicString("Cell content") # Add plain text content
483 td2 = etree.SubElement(tr, "td") # Add second td to tr
484 td2.text = "*text* with **inline** formatting." # Add markup text
485 table.tail = "Text after table" # Add text after table
486 ```
487
488 You can also manipulate an existing tree. Consider the following example which adds a `class` attribute to `<a>`
489 elements:
490
491 ```python
492 def set_link_class(self, element):
493 for child in element:
494 if child.tag == "a":
495 child.set("class", "myclass") #set the class attribute
496 set_link_class(child) # run recursively on children
497 ```
498
499 For more information about working with ElementTree see the [ElementTree
500 Documentation][ElementTree].
501
502 ## Working with Raw HTML {: #working_with_raw_html }
503
504 Occasionally an extension may need to call out to a third party library which returns a pre-made string
505 of raw HTML that needs to be inserted into the document unmodified. Raw strings can be stashed for later
506 retrieval using an [`htmlStash`][markdown.util.HtmlStash] instance, rather than converting them into
507 `ElementTree` objects. A raw string (which may or may not be raw HTML) passed to
508 [`self.md.htmlStash.store()`][markdown.util.HtmlStash.store] will be saved to the stash and a
509 placeholder string will be returned which should be inserted into the tree instead. After the tree is
510 serialized, a postprocessor will replace the placeholder with the raw string. This prevents subsequent
511 processing steps from modifying the HTML data. For example,
512
513 ```python
514 html = "<p>This is some <em>raw</em> HTML data</p>"
515 el = etree.Element("div")
516 el.text = self.md.htmlStash.store(html)
517 ```
518
519 For the global `htmlStash` instance to be available from a processor, the [`markdown.Markdown`][markdown.Markdown]
520 instance must be passed to the processor from [extendMarkdown](#extendmarkdown) and will be available as
521 `self.md.htmlStash`.
522
523 ## Integrating Your Code Into Markdown {: #integrating_into_markdown }
524
525 Once you have the various pieces of your extension built, you need to tell Markdown about them and ensure that they
526 are run in the proper sequence. Markdown accepts an `Extension` instance for each extension. Therefore, you will need
527 to define a class that extends [`markdown.extensions.Extension`][markdown.extensions.Extension] and overrides the
528 [`extendMarkdown`][markdown.extensions.Extension.extendMarkdown] method. Within this class you will manage
529 configuration options for your extension and attach the various processors and patterns to the Markdown instance.
530
531 It is important to note that the order of the various processors and patterns matters. For example, if we replace
532 `http://...` links with `<a>` elements, and *then* try to deal with inline HTML, we will end up with a mess.
533 Therefore, the various types of processors and patterns are stored within an instance of the
534 [`markdown.Markdown`][markdown.Markdown] class in a [Registry][]. Your `Extension` class will need to manipulate
535 those registries appropriately. You may `register` instances of your processors and patterns with an appropriate
536 priority, `deregister` built-in instances, or replace a built-in instance with your own.
537
538 ### `extendMarkdown` {: #extendmarkdown }
539
540 The [`extendMarkdown`][markdown.extensions.Extension.extendMarkdown] method of a
541 [`markdown.extensions.Extension`][markdown.extensions.Extension] class accepts one argument `md`, which is a
542 pointer to the instance of the [`markdown.Markdown`][markdown.Markdown] class. You should use this to access
543 the [Registries][Registry] of processors and patterns. They are found under the following attributes:
544
545 * `md.preprocessors`
546 * `md.inlinePatterns`
547 * `md.parser.blockprocessors`
548 * `md.treeprocessors`
549 * `md.postprocessors`
550
551 Some other things you may want to access on the [`markdown.Markdown`][markdown.Markdown] instance are:
552
553 * `md.htmlStash`
554 * [`md.output_formats`][markdown.Markdown.output_formats]
555 * [`md.set_output_format()`][markdown.Markdown.set_output_format]
556 * `md.output_format`
557 * `md.serializer`
558 * [`md.registerExtension()`][markdown.Markdown.registerExtension]
559 * `md.tab_length`
560 * [`md.block_level_elements`][markdown.util.BLOCK_LEVEL_ELEMENTS]
561 * [`md.is_block_level()`][markdown.Markdown.is_block_level]
562 * [`md.ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS]
563
564 !!! Warning
565 With access to the above items, theoretically you have the option to change anything through various
566 [monkey_patching][] techniques. However, you should be aware that the various undocumented parts of Markdown may
567 change without notice and your monkey_patches may break with a new release. Therefore, what you really should be
568 doing is inserting processors and patterns into the Markdown pipeline. Consider yourself warned!
569
570 [monkey_patching]: https://en.wikipedia.org/wiki/Monkey_patch
571
572 A simple example:
573
574 ```python
575 from markdown.extensions import Extension
576
577 class MyExtension(Extension):
578 def extendMarkdown(self, md):
579 # Register instance of 'mypattern' with a priority of 175
580 md.inlinePatterns.register(MyPattern(md), 'mypattern', 175)
581 ```
582
583 ### registerExtension {: #registerextension }
584
585 Some extensions may need to have their state reset between multiple runs of the [`markdown.Markdown`][markdown.Markdown] class. For
586 example, consider the following use of the [Footnotes][] extension:
587
588 ```python
589 md = markdown.Markdown(extensions=['footnotes'])
590 html1 = md.convert(text_with_footnote)
591 md.reset()
592 html2 = md.convert(text_without_footnote)
593 ```
594
595 Without calling [`reset`][markdown.Markdown.reset], the footnote definitions from the first document will be inserted
596 into the second document as they are still stored within the class instance. Therefore the
597 [`Extension`][markdown.extensions.Extension] class needs to define a `reset` method that
598 will reset the state of the extension (i.e.: `self.footnotes = {}`). However, as many extensions do not have a need
599 for `reset`, `reset` is only called on extensions that are registered.
600
601 To register an extension, call [`md.registerExtension`][markdown.Markdown.registerExtension] from within your
602 [`extendMarkdown`][markdown.extensions.Extension.extendMarkdown] method:
603
604 ```python
605 def extendMarkdown(self, md):
606 md.registerExtension(self)
607 # insert processors and patterns here
608 ```
609
610 Then, each time `reset` is called on the `markdown.Markdown` instance, the `reset` method of each registered extension
611 will be called as well. You should also note that `reset` will be called on each registered extension after it is
612 initialized the first time. Keep that in mind when over-riding the extension's `reset` method.
613
614 ### Configuration Settings {: #configsettings }
615
616 If an extension uses any parameters that the user may want to change, those parameters should be stored in
617 [`self.config`][markdown.extensions.Extension.config] of your [`markdown.extensions.Extension`][markdown.extensions.Extension]
618 class in the following format:
619
620 ```python
621 class MyExtension(markdown.extensions.Extension):
622 def __init__(self, **kwargs):
623 self.config = {
624 'option1' : ['value1', 'description1'],
625 'option2' : ['value2', 'description2']
626 }
627 super(MyExtension, self).__init__(**kwargs)
628 ```
629
630 When implemented this way the configuration parameters can be overridden at run time (thus the call to `super`). For
631 example:
632
633 ```python
634 markdown.Markdown(extensions=[MyExtension(option1='other value')])
635 ```
636
637 Note that if a keyword is passed in that is not already defined in `self.config`, then a `KeyError` is raised.
638
639 The [`markdown.extensions.Extension`][markdown.extensions.Extension] class and its subclasses have the following
640 methods available to assist in working with configuration settings:
641
642 * [`getConfig`][markdown.extensions.Extension.getConfig]
643 * [`getConfigs`][markdown.extensions.Extension.getConfigs]
644 * [`getConfigInfo`][markdown.extensions.Extension.getConfigInfo]
645 * [`setConfig`][markdown.extensions.Extension.setConfig]
646 * [`setConfigs`][markdown.extensions.Extension.setConfigs]
647
648 ### Naming an Extension { #naming_an_extension }
649
650 As noted in the [library reference] an instance of an extension can be passed directly to [`markdown.Markdown`][markdown.Markdown].
651 In fact, this is the preferred way to use third-party extensions.
652
653 For example:
654
655 ```python
656 import markdown
657 from path.to.module import MyExtension
658 md = markdown.Markdown(extensions=[MyExtension(option='value')])
659 ```
660
661 However, Markdown also accepts "named" third party extensions for those occasions when it is impractical to import an
662 extension directly (from the command line or from within templates). A "name" can either be a registered [entry
663 point](#entry_point) or a string using Python's [dot notation](#dot_notation).
664
665 #### Entry Point { #entry_point }
666
667 [Entry points] are defined in a Python package's `setup.py` script. The script must use [setuptools] to support entry
668 points. Python-Markdown extensions must be assigned to the `markdown.extensions` group. An entry point definition
669 might look like this:
670
671 ```python
672 from setuptools import setup
673
674 setup(
675 # ...
676 entry_points={
677 'markdown.extensions': ['myextension = path.to.module:MyExtension']
678 }
679 )
680 ```
681
682 After a user installs your extension using the above script, they could then call the extension using the
683 `myextension` string name like this:
684
685 ```python
686 markdown.markdown(text, extensions=['myextension'])
687 ```
688
689 Note that if two or more entry points within the same group are assigned the same name, Python-Markdown will only ever
690 use the first one found and ignore all others. Therefore, be sure to give your extension a unique name.
691
692 For more information on writing `setup.py` scripts, see the Python documentation on [Packaging and Distributing
693 Projects].
694
695 #### Dot Notation { #dot_notation }
696
697 If an extension does not have a registered entry point, Python's dot notation may be used instead. The extension must
698 be installed as a Python module on your PYTHONPATH. Generally, a class should be specified in the name. The class must
699 be at the end of the name and be separated by a colon from the module.
700
701 Therefore, if you were to import the class like this:
702
703 ```python
704 from path.to.module import MyExtension
705 ```
706
707 Then the extension can be loaded as follows:
708
709 ```python
710 markdown.markdown(text, extensions=['path.to.module:MyExtension'])
711 ```
712
713 You do not need to do anything special to support this feature. As long as your extension class is able to be
714 imported, a user can include it with the above syntax.
715
716 The above two methods are especially useful if you need to implement a large number of extensions with more than one
717 residing in a module. However, if you do not want to require that your users include the class name in their string,
718 you must define only one extension per module and that module must contain a module-level function called
719 `makeExtension` that accepts `**kwargs` and returns an extension instance.
720
721 For example:
722
723 ```python
724 class MyExtension(markdown.extensions.Extension)
725 # Define extension here...
726
727 def makeExtension(**kwargs):
728 return MyExtension(**kwargs)
729 ```
730
731 When [`markdown.Markdown`][markdown.Markdown] is passed the "name" of your extension as a dot notation string that
732 does not include a class (for example `path.to.module`), it will import the module and call the `makeExtension`
733 function to initiate your extension.
734
735 ## Registries { #registry }
736
737 The [`markdown.util.Registry`][markdown.util.Registry] class is a priority sorted registry which Markdown uses
738 internally to determine the processing order of its various processors and patterns.
739
740 A `Registry` instance provides two public methods to alter the data of the registry:
741 [`register`][markdown.util.Registry.register] and [`deregister`][markdown.util.Registry.deregister]. Use
742 `register` to add items and `deregister` to remove items. See each method for specifics.
743
744 When registering an item, a "name" and a "priority" must be provided. All items are automatically sorted by the value
745 of the "priority" parameter such that the item with the highest value will be processed first. The "name" is used to
746 remove (`deregister`) and get items.
747
748 A `Registry` instance is like a list (which maintains order) when reading data. You may iterate over the items, get an
749 item and get a count (length) of all items. You may also check that the registry contains an item.
750
751 When getting an item you may use either the index of the item or the string-based "name". For example:
752
753 ```python
754 registry = Registry()
755 registry.register(SomeItem(), 'itemname', 20)
756 # Get the item by index
757 item = registry[0]
758 # Get the item by name
759 item = registry['itemname']
760 ```
761
762 When checking that the registry contains an item, you may use either the string-based "name", or a reference to the
763 actual item. For example:
764
765 ```python
766 someitem = SomeItem()
767 registry.register(someitem, 'itemname', 20)
768 # Contains the name
769 assert 'itemname' in registry
770 # Contains the item instance
771 assert someitem in registry
772 ```
773
774 The method [`get_index_for_name`][markdown.util.Registry.get_index_for_name] is also available to obtain the index of
775 an item using that item’s assigned "name."
776
777 ```python
778 index = registry.get_index_for_name('itemname')
779 ```
780
781 The priorities of all built-in processors are documented in the API Reference for each type of processor as outlined below.
782
783 * [`preprocessors`][markdown.preprocessors.build_preprocessors]
784 * [`blockprocessors`][markdown.blockprocessors.build_block_parser]
785 * [`treeprocessors`][markdown.treeprocessors.build_treeprocessors]
786 * [`inlinepatterns`][markdown.inlinepatterns.build_inlinepatterns]
787 * [`postprocessors`][markdown.postprocessors.build_postprocessors]
788
789 The built-in extensions modify those collections of processors as documented in the API Reference for each extension.
790
791 * [Abbreviations][markdown.extensions.abbr.AbbrExtension.extendMarkdown]
792 * [Admonition][markdown.extensions.admonition.AdmonitionExtension.extendMarkdown]
793 * [Attribute Lists][markdown.extensions.attr_list.AttrListExtension.extendMarkdown]
794 * [CodeHilite][markdown.extensions.codehilite.CodeHiliteExtension.extendMarkdown]
795 * [Definition Lists][markdown.extensions.def_list.DefListExtension.extendMarkdown]
796 * [Fenced Code Blocks][markdown.extensions.fenced_code.FencedCodeExtension.extendMarkdown]
797 * [Footnotes][markdown.extensions.footnotes.FootnoteExtension.extendMarkdown]
798 * [Legacy Attributes][markdown.extensions.legacy_attrs.LegacyAttrExtension.extendMarkdown]
799 * [Legacy Emphasis][markdown.extensions.legacy_em.LegacyEmExtension.extendMarkdown]
800 * [Markdown in HTML][markdown.extensions.md_in_html.MarkdownInHtmlExtension.extendMarkdown]
801 * [Meta-Data][markdown.extensions.meta.MetaExtension.extendMarkdown]
802 * [New Line to Break][markdown.extensions.nl2br.Nl2BrExtension.extendMarkdown]
803 * [Sane Lists][markdown.extensions.sane_lists.SaneListExtension.extendMarkdown]
804 * [SmartyPants][markdown.extensions.smarty.SmartyExtension.extendMarkdown]
805 * [Tables][markdown.extensions.tables.TableExtension.extendMarkdown]
806 * [Table of Contents][markdown.extensions.toc.TocExtension.extendMarkdown]
807 * [WikiLinks][markdown.extensions.wikilinks.WikiLinkExtension.extendMarkdown]
808
809 A few things to note about the above linked collections.
810
811 * A higher number has a higher priority. Processors assigned a higher priority are run before processors with a lower
812 priority. In other words, processors assigned a higher number are run before those assigned a lower number.
813 * Large gaps have been left between the default processors. This leaves lots of room for multiple different extensions
814 to insert many additional processors. While integers have been used, floats may be used to get even more precision.
815 While negative numbers could be used, that would only be useful to ensure that a processor was the absolutely last
816 processor run.
817 * While it is preferred that the assigned priorities of the built-in processors remain stable, a bug fix has occasionally
818 required an adjustment to an assigned priority. Any such changes will always be documented as backward incompatible
819 changes.
820 * You will likely need to check the source code to determine assigned priorities of third-party extensions when resolving
821 conflicts.
822
823 [match object]: https://docs.python.org/3/library/re.html#match-objects
824 [bug tracker]: https://github.com/Python-Markdown/markdown/issues
825 [extension source]: https://github.com/Python-Markdown/markdown/tree/master/markdown/extensions
826 [tutorial]: https://github.com/Python-Markdown/markdown/wiki/Tutorial-1---Writing-Extensions-for-Python-Markdown
827 [workingwithetree]: #working_with_et
828 [Integrating your code into Markdown]: #integrating_into_markdown
829 [extendMarkdown]: #extendmarkdown
830 [Registry]: #registry
831 [registerExtension]: #registerextension
832 [Config Settings]: #configsettings
833 [makeExtension]: #makeextension
834 [ElementTree]: https://docs.python.org/3/library/xml.etree.elementtree.html
835 [Available Extensions]: index.md
836 [Footnotes]: https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/footnotes.py
837 [Definition Lists]: https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/definition_lists
838 [library reference]: ../reference.md
839 [setuptools]: https://packaging.python.org/key_projects/#setuptools
840 [Entry points]: https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins
841 [Packaging and Distributing Projects]: https://packaging.python.org/tutorials/distributing-packages/
842 [Inline Patterns]: #inline-patterns