| 1 |
--- |
| 2 |
icon: lucide/fence |
| 3 |
--- |
| 4 |
[:octicons-file-code-24:][_superfences]{: .source-link } |
| 5 |
|
| 6 |
# SuperFences |
| 7 |
|
| 8 |
## Overview |
| 9 |
|
| 10 |
SuperFences provides a number of features: |
| 11 |
|
| 12 |
1. Allowing the [nesting of fences](#nested-fence-format) under blockquotes, lists, or other block elements (see |
| 13 |
[Limitations](#limitations) for more info). |
| 14 |
2. Ability to specify [custom fences](#custom-fences) to provide features like flowcharts, sequence diagrams, or other |
| 15 |
custom blocks. |
| 16 |
3. Allow disabling of indented code blocks in favor of only using the fenced variant (off by default). |
| 17 |
4. Experimental feature that preserves tabs within a code block instead of converting them to spaces which is Python |
| 18 |
Markdown's default behavior. |
| 19 |
|
| 20 |
/// danger | Reminder |
| 21 |
Remember to read the [Usage Notes](../usage_notes.md) for information that may be relevant when using this |
| 22 |
extension! |
| 23 |
/// |
| 24 |
|
| 25 |
The SuperFences extension can be included in Python Markdown by using the following: |
| 26 |
|
| 27 |
```py3 |
| 28 |
import markdown |
| 29 |
md = markdown.Markdown(extensions=['pymdownx.superfences']) |
| 30 |
``` |
| 31 |
|
| 32 |
## Nested Fence Format |
| 33 |
|
| 34 |
1. Start and end fence boundaries are specified with either 3 or more backticks or tildes. |
| 35 |
|
| 36 |
2. Start and end fence boundaries must both use matching symbols (backticks or tildes) and must be of the same number |
| 37 |
of symbols. If start is 3 backticks, the fence will end with 3 backticks. |
| 38 |
|
| 39 |
3. Start and end fence boundaries must be aligned to the same indentation level. |
| 40 |
|
| 41 |
4. Content between fences must be indented at least the same amount as the start and end boundaries. Empty lines are |
| 42 |
exempted. |
| 43 |
|
| 44 |
5. If you are using a fenced block inside a blockquote, at the very least, the first line of the fenced block needs to |
| 45 |
have the appropriate number of `>` characters signifying the quote depth. This i |
| 46 |
|
| 47 |
```` |
| 48 |
> ``` |
| 49 |
a fenced block |
| 50 |
``` |
| 51 |
```` |
| 52 |
|
| 53 |
Too many blank lines will cause a blockquote to terminate, so remember to use `>` markers accordingly if not marking |
| 54 |
every line. |
| 55 |
|
| 56 |
```` |
| 57 |
> ``` |
| 58 |
a fenced block |
| 59 |
|
| 60 |
> with blank lines |
| 61 |
``` |
| 62 |
```` |
| 63 |
|
| 64 |
If you are using the [Quotes](./quotes.md) extension, you must include the entire fenced code block within the |
| 65 |
blockquote as Quotes purposely does not use lazy blockquote logic. |
| 66 |
|
| 67 |
```` |
| 68 |
> ``` |
| 69 |
> a fenced block |
| 70 |
> ``` |
| 71 |
```` |
| 72 |
|
| 73 |
/// tip |
| 74 |
If you always include the entire code block within the blockquote, you will always get good results and is generally |
| 75 |
the recommended approach regardless if you are using the default lazy blockquote logic that comes stock with Python |
| 76 |
Markdown or using the [Quotes](./quotes.md) extension. |
| 77 |
/// |
| 78 |
|
| 79 |
6. If using a fenced block as the first line of a list, you will have to leave the first line blank, but remember that |
| 80 |
the list marker must be immediately followed by at least one space. To avoid accidentally deleting the space and to |
| 81 |
make your intentions clear, you might want to also add an explicit unicode space (` `) as shown here: |
| 82 |
|
| 83 |
```` |
| 84 |
-   |
| 85 |
``` |
| 86 |
a fenced block |
| 87 |
``` |
| 88 |
|
| 89 |
Definition |
| 90 |
:   |
| 91 |
``` |
| 92 |
a fenced block |
| 93 |
``` |
| 94 |
```` |
| 95 |
|
| 96 |
7. Fenced blocks should be separated from other blocks by an empty line. |
| 97 |
|
| 98 |
```` |
| 99 |
Paragraph. |
| 100 |
|
| 101 |
``` |
| 102 |
a fenced block |
| 103 |
``` |
| 104 |
|
| 105 |
Another paragraph. |
| 106 |
```` |
| 107 |
|
| 108 |
## Injecting Classes, IDs, and Attributes |
| 109 |
|
| 110 |
You can use the brace format to specify classes and IDs where IDs use the form `#id` and classes use the form `.class`. |
| 111 |
Arbitrary attributes in the form `key="value"` can be inserted as well if the [`attr_list`][attr-list] extension is |
| 112 |
enabled, but when using Pygments, only `key="value"` attributes that start with the `data-` prefix will be recognized, |
| 113 |
all others will be treated as options for Pygments and will be rejected if not valid. |
| 114 |
|
| 115 |
````text title="Injecting Classes" |
| 116 |
```python {.extra-class #id linenums="1"} |
| 117 |
import hello_world |
| 118 |
``` |
| 119 |
```` |
| 120 |
|
| 121 |
/// html | div.result |
| 122 |
```html |
| 123 |
<div id="id" class="extra-class highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal">1</span></pre></div></td><td class="code"><div><pre><span></span><code><span class="kn">import</span> <span class="nn">hello_world</span> |
| 124 |
</code></pre></div></td></tr></table></div> |
| 125 |
``` |
| 126 |
/// |
| 127 |
|
| 128 |
Alternatively, if a language is not provided, the first class is assumed to specify the language. |
| 129 |
|
| 130 |
````text title="Injecting Classes" |
| 131 |
```{.python .extra-class #id linenums="1"} |
| 132 |
import hello_world |
| 133 |
``` |
| 134 |
```` |
| 135 |
|
| 136 |
/// html | div.result |
| 137 |
```html |
| 138 |
<div id="id" class="extra-class highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal">1</span></pre></div></td><td class="code"><div><pre><span></span><code><span class="kn">import</span> <span class="nn">hello_world</span> |
| 139 |
</code></pre></div></td></tr></table></div> |
| 140 |
``` |
| 141 |
/// |
| 142 |
|
| 143 |
When generating additional classes on a JavaScript style code block (non-Pygments code blocks), classes are injected in |
| 144 |
the `#!html code` block. |
| 145 |
|
| 146 |
````text title="Non-Pygments Injecting Classes" |
| 147 |
```python {.extra-class #id linenums="1"} |
| 148 |
import hello_world |
| 149 |
``` |
| 150 |
```` |
| 151 |
|
| 152 |
/// html | div.result |
| 153 |
```html |
| 154 |
<pre class="highlight"><code id="id" class="language-python extra-class" linenums="1">import hello_world</code></pre> |
| 155 |
``` |
| 156 |
/// |
| 157 |
|
| 158 |
When using Pygments, all extra classes and attributes will be attached to the Pygments' wrapper `#!html <div>`. |
| 159 |
|
| 160 |
When using a built in [custom formatter](#custom-fences), all classes and IDs are injected on to the first element |
| 161 |
`#!html <div>` or `#!html <pre>`. This preserves previous behavior, but you can write your own and inject them in the |
| 162 |
way that suites your needs. |
| 163 |
|
| 164 |
/// new | New 9.0 |
| 165 |
Added support for `#id` in Pygments brace headers. Also added support for arbitrary `data-` attributes if the |
| 166 |
[`attr_list`][attr-list] extension is enabled. |
| 167 |
/// |
| 168 |
|
| 169 |
## Preserve Tabs |
| 170 |
|
| 171 |
Python Markdown has an approach where it normalizes whitespace. This means `\r\n` is converted to `\n` and `\t` is |
| 172 |
converted to spaces. In 99% of Markdown, this is never really an issue, but with code blocks it can be. Tabs can |
| 173 |
sometimes be very useful for aligning certain kinds of data, especially when dealing with characters of varying width. |
| 174 |
|
| 175 |
````text title="Tabs in Content" |
| 176 |
``` |
| 177 |
============================================================ |
| 178 |
T Tp Sp D Dp S D7 T |
| 179 |
------------------------------------------------------------ |
| 180 |
A F#m Bm E C#m D E7 A |
| 181 |
A# Gm Cm F Dm D# F7 A# |
| 182 |
B♭ Gm Cm F Dm E♭m F7 B♭ |
| 183 |
``` |
| 184 |
```` |
| 185 |
|
| 186 |
/// html | div.result |
| 187 |
``` |
| 188 |
============================================================ |
| 189 |
T Tp Sp D Dp S D7 T |
| 190 |
------------------------------------------------------------ |
| 191 |
A F#m Bm E C#m D E7 A |
| 192 |
A# Gm Cm F Dm D# F7 A# |
| 193 |
B♭ Gm Cm F Dm E♭m F7 B♭ |
| 194 |
``` |
| 195 |
/// |
| 196 |
|
| 197 |
If you have a scenario where preserving tabs is a requirement, you can use SuperFences `preserve_tabs` option to prevent |
| 198 |
converting tabs to spaces inside fenced code blocks. This *only* applies to fenced code blocks. Indented code blocks and |
| 199 |
inline code blocks will still be treated with Python Markdown's default behavior. |
| 200 |
|
| 201 |
This feature is experimental and actually applies the fences before whitespace normalization and bypasses the |
| 202 |
normalization for the code content. |
| 203 |
|
| 204 |
## Code Highlighting |
| 205 |
|
| 206 |
Assuming Pygments is installed, code highlighting will be handled by [Pygments][pygments] by default. If Pygments is not |
| 207 |
installed, or disabled, code blocks will be created using HTML5 style tags for a JavaScript syntax highlighter: |
| 208 |
`#!html <pre class="highlight"><code class="language-mylanguage"></code></pre>`. If you disable `highlight_code`, |
| 209 |
specified languages will be ignored, and the content will be wrapped in a simple `pre` and `code` tags with no classes. |
| 210 |
|
| 211 |
Highlighting can be further controlled via the [`pymdownx.highlight`](./highlight.md) extension. You must include |
| 212 |
`pymdownx.highlight` in the extensions list in order to be able to configure it. |
| 213 |
|
| 214 |
When using fenced code blocks, you can specify a specific syntax language to highlight with by specifying the language |
| 215 |
name directly after the opening tokens (either ` ``` ` or `~~~`). Whether using Pygments or some other JavaScript |
| 216 |
highlighter, the syntax is the same, but please consult your highlighter's documentation for recognized language syntax |
| 217 |
specifiers. |
| 218 |
|
| 219 |
````text title="Highlighting" |
| 220 |
```python |
| 221 |
import foo.bar |
| 222 |
``` |
| 223 |
```` |
| 224 |
|
| 225 |
/// html | div.result |
| 226 |
```python |
| 227 |
import foo.bar |
| 228 |
``` |
| 229 |
/// |
| 230 |
|
| 231 |
## Showing Line Numbers |
| 232 |
|
| 233 |
Line numbers are provided via Pygments and can either be shown per code block or globally for all. To show globally via |
| 234 |
[`pymdownx.highlight`](./highlight.md), you must set `linenums` to `#!py3 True` in the respective extension. |
| 235 |
|
| 236 |
To set line numbers per code block, you can specify a special setting directly after the opening tokens (and language if |
| 237 |
present). Simply specify the starting line number with option `linenums="1"`. The setting is followed by the equal |
| 238 |
sign and the value must be quoted. Valid line numbers are n > 0. If `linenums` is enabled globally, this will just |
| 239 |
control the starting line shown in the block. |
| 240 |
|
| 241 |
````text title="Line Numbers" |
| 242 |
```python {linenums="1"} |
| 243 |
import foo.bar |
| 244 |
``` |
| 245 |
```` |
| 246 |
|
| 247 |
/// html | div.result |
| 248 |
```python {linenums="1"} |
| 249 |
import foo.bar |
| 250 |
``` |
| 251 |
/// |
| 252 |
|
| 253 |
|
| 254 |
And, if we wanted to start with a different starting line number, we would just specify something other than `1`. |
| 255 |
|
| 256 |
````text title="Custom Line Number Start" |
| 257 |
```python {linenums="2"} |
| 258 |
import foo.bar |
| 259 |
``` |
| 260 |
```` |
| 261 |
|
| 262 |
/// html | div.result |
| 263 |
```python {linenums="2"} |
| 264 |
import foo.bar |
| 265 |
``` |
| 266 |
/// |
| 267 |
|
| 268 |
Pygments also has a few additional options in regards to line numbers. One is "line step" which, if set to a number n > |
| 269 |
1, will print only every n^th^ line number. The other option is a setting that can mark line numbers as "special" with a |
| 270 |
span and class `special`. If the special parameter is set to a number n > 0, every n^th^ line number is given the CSS |
| 271 |
class `special`. |
| 272 |
|
| 273 |
So to set showing only every other line number, we could do the following. Line options are separated by a space, and |
| 274 |
"line step" is always the second option, so you must specify line start before line step. |
| 275 |
|
| 276 |
````text title="N<sup>th</sup> Line" |
| 277 |
```python {linenums="1 2"} |
| 278 |
"""Some file.""" |
| 279 |
import foo.bar |
| 280 |
import boo.baz |
| 281 |
import foo.bar.baz |
| 282 |
``` |
| 283 |
```` |
| 284 |
|
| 285 |
/// html | div.result |
| 286 |
```python {linenums="1 2"} |
| 287 |
"""Some file.""" |
| 288 |
import foo.bar |
| 289 |
import boo.baz |
| 290 |
import foo.bar.baz |
| 291 |
``` |
| 292 |
/// |
| 293 |
|
| 294 |
To set every other line as special, you must set the third `linenums` option (specify line start and step before it). |
| 295 |
Special must be a value of n > 0. Additionally, you can set this globally with `linenums_special` in the |
| 296 |
[Highlight extension](./highlight.md). |
| 297 |
|
| 298 |
````text title="Special Lines" |
| 299 |
``` {linenums="1 1 2"} |
| 300 |
"""Some file.""" |
| 301 |
import foo.bar |
| 302 |
import boo.baz |
| 303 |
import foo.bar.baz |
| 304 |
``` |
| 305 |
```` |
| 306 |
|
| 307 |
/// html | div.result |
| 308 |
``` {linenums="1 1 2"} |
| 309 |
"""Some file.""" |
| 310 |
import foo.bar |
| 311 |
import boo.baz |
| 312 |
import foo.bar.baz |
| 313 |
``` |
| 314 |
/// |
| 315 |
|
| 316 |
For JavaScript libraries, a class of `linenums` is written to the block. This may or may not be leveraged by your |
| 317 |
chosen highlighter. It is uncertain at this time whether line number support for JavaScript highlighters will be |
| 318 |
enhanced beyond this.w what to inject. |
| 319 |
|
| 320 |
## Highlighting Lines |
| 321 |
|
| 322 |
Via Pygments, certain lines can be specified for highlighting. This is done by specifying a special setting directly |
| 323 |
after the opening tokens (and language if present). The setting is named `hl_lines` and the value should be the |
| 324 |
targeted line numbers separated by spaces. |
| 325 |
|
| 326 |
````text title="Highlight Lines" |
| 327 |
```python {hl_lines="1 3"} |
| 328 |
"""Some file.""" |
| 329 |
import foo.bar |
| 330 |
import boo.baz |
| 331 |
import foo.bar.baz |
| 332 |
``` |
| 333 |
```` |
| 334 |
|
| 335 |
/// html | div.result |
| 336 |
```python {hl_lines="1 3"} |
| 337 |
"""Some file.""" |
| 338 |
import foo.bar |
| 339 |
import boo.baz |
| 340 |
import foo.bar.baz |
| 341 |
``` |
| 342 |
/// |
| 343 |
|
| 344 |
|
| 345 |
Line numbers are always referenced starting at 1 ignoring what the line number is labeled as when showing line numbers. |
| 346 |
|
| 347 |
````text title="Highlight Lines with Line Numbers" |
| 348 |
```python {hl_lines="1 3" linenums="2"} |
| 349 |
"""Some file.""" |
| 350 |
import foo.bar |
| 351 |
import boo.baz |
| 352 |
import foo.bar.baz |
| 353 |
``` |
| 354 |
```` |
| 355 |
|
| 356 |
/// html | div.result |
| 357 |
```python {hl_lines="1 3" linenums="2"} |
| 358 |
"""Some file.""" |
| 359 |
import foo.bar |
| 360 |
import boo.baz |
| 361 |
import foo.bar.baz |
| 362 |
``` |
| 363 |
/// |
| 364 |
|
| 365 |
If you'd like to do a range of lines, you can use the notation `x-y` where `x` is the starting line and `y` is the |
| 366 |
ending line. You can do multiple ranges and even mix them with non ranges. |
| 367 |
|
| 368 |
````text title="Highlight Ranges" |
| 369 |
```python {hl_lines="1-2 5 7-8"} |
| 370 |
import foo |
| 371 |
import boo.baz |
| 372 |
import foo.bar.baz |
| 373 |
|
| 374 |
class Foo: |
| 375 |
def __init__(self): |
| 376 |
self.foo = None |
| 377 |
self.bar = None |
| 378 |
self.baz = None |
| 379 |
``` |
| 380 |
```` |
| 381 |
|
| 382 |
/// html | div.result |
| 383 |
```python {hl_lines="1-2 5 7-8"} |
| 384 |
import foo |
| 385 |
import boo.baz |
| 386 |
import foo.bar.baz |
| 387 |
|
| 388 |
class Foo: |
| 389 |
def __init__(self): |
| 390 |
self.foo = None |
| 391 |
self.bar = None |
| 392 |
self.baz = None |
| 393 |
``` |
| 394 |
/// |
| 395 |
|
| 396 |
## Code Block Title Headers |
| 397 |
|
| 398 |
/// new | New 9.0 |
| 399 |
Title headers are new in version `9.0`. |
| 400 |
/// |
| 401 |
|
| 402 |
When Pygments is enabled, a header with a title can be applied with the `title` option. This essentially controls the |
| 403 |
Pygments' `filename` option under the hood. It made more sense to use the term `title` as people can really set any |
| 404 |
arbitrary title, not just filenames. |
| 405 |
|
| 406 |
Pygments will simply output the HTML below. The user is responsible for provided CSS to style the header. Pygments uses |
| 407 |
the class name of `filename` as that is the feature being used under the hood. |
| 408 |
|
| 409 |
```html |
| 410 |
<div class="highlight"> |
| 411 |
<span class="filename">Some Title</span> |
| 412 |
<pre><code></code></pre> |
| 413 |
</div> |
| 414 |
``` |
| 415 |
|
| 416 |
If using line numbers and the `linenums_style` set to `table` (the default), the title will be inserted in `#!html <th>` |
| 417 |
element at the start of the table set to span both the line number column and the line column. |
| 418 |
|
| 419 |
```html |
| 420 |
<div class="highlight"> |
| 421 |
<table class="highlighttable"> |
| 422 |
<tr> |
| 423 |
<th colspan="2" class="filename"><span class="filename">My title</span></th> |
| 424 |
</tr> |
| 425 |
<tr> |
| 426 |
<td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal">1</span></pre></div></td> |
| 427 |
<td class="code"><div class="highlight"><pre><code></code></pre></div></td> |
| 428 |
</tr> |
| 429 |
</table> |
| 430 |
</div> |
| 431 |
``` |
| 432 |
|
| 433 |
````text title="Adding Titles" |
| 434 |
```python {title="My Cool Header"} |
| 435 |
import foo.bar |
| 436 |
import boo.baz |
| 437 |
import foo.bar.baz |
| 438 |
``` |
| 439 |
```` |
| 440 |
|
| 441 |
/// html | div.result |
| 442 |
```python {title="My Cool Header"} |
| 443 |
import foo.bar |
| 444 |
import boo.baz |
| 445 |
import foo.bar.baz |
| 446 |
``` |
| 447 |
/// |
| 448 |
|
| 449 |
If the `auto_title` option is enabled in the [Highlight extension](./highlight.md), the title will be auto populated |
| 450 |
with the name of the lexer used to highlight the code (unless `title` is manually specified). In the example below, |
| 451 |
no `title` is specified, but the title is extracted from the Python lexer. |
| 452 |
|
| 453 |
````text title="Automatic Titles" |
| 454 |
```python |
| 455 |
import foo.bar |
| 456 |
import boo.baz |
| 457 |
import foo.bar.baz |
| 458 |
``` |
| 459 |
```` |
| 460 |
|
| 461 |
/// html | div.result |
| 462 |
````md-render |
| 463 |
--- |
| 464 |
extensions: |
| 465 |
- pymdownx.highlight |
| 466 |
- pymdownx.superfences |
| 467 |
|
| 468 |
extension_configs: |
| 469 |
pymdownx.highlight: |
| 470 |
auto_title: true |
| 471 |
line_spans: __codeline_a |
| 472 |
line_anchors: __codelineno_a |
| 473 |
anchor_linenums: True |
| 474 |
--- |
| 475 |
```python |
| 476 |
import foo.bar |
| 477 |
import boo.baz |
| 478 |
import foo.bar.baz |
| 479 |
``` |
| 480 |
```` |
| 481 |
/// |
| 482 |
|
| 483 |
There may be some cases where a Lexer returns a result that is undesired. For example, when a user specifies the `pycon` |
| 484 |
lexer, the title that is returned is quite verbose. |
| 485 |
|
| 486 |
````text title="Undesired Automatic Title" |
| 487 |
```pycon |
| 488 |
>>> 3 + 3 |
| 489 |
6 |
| 490 |
``` |
| 491 |
```` |
| 492 |
|
| 493 |
/// html | div.result |
| 494 |
````md-render |
| 495 |
--- |
| 496 |
extensions: |
| 497 |
- pymdownx.highlight |
| 498 |
- pymdownx.superfences |
| 499 |
|
| 500 |
extension_configs: |
| 501 |
pymdownx.highlight: |
| 502 |
auto_title: true |
| 503 |
line_spans: __codeline_b |
| 504 |
line_anchors: __codelineno_b |
| 505 |
anchor_linenums: True |
| 506 |
--- |
| 507 |
```pycon |
| 508 |
>>> 3 + 3 |
| 509 |
6 |
| 510 |
``` |
| 511 |
```` |
| 512 |
/// |
| 513 |
|
| 514 |
In a case like above, it may be desired to simply use the title `Python`. We can configure the [Highlight extension](./highlight.md) |
| 515 |
to override any auto returned title. Simply create mapping via the `auto_title_map` specifying the title you wish to |
| 516 |
override as the key, and the desired title as the value. |
| 517 |
|
| 518 |
```py3 |
| 519 |
extension_configs = { |
| 520 |
"pymdownx.highlight": { |
| 521 |
"auto_title": True, |
| 522 |
"auto_title_map": { |
| 523 |
"Python Console Session": "Python" |
| 524 |
} |
| 525 |
} |
| 526 |
} |
| 527 |
``` |
| 528 |
|
| 529 |
Now whenever we use `pycon`, we get "Python" instead of "Python Console Session". |
| 530 |
|
| 531 |
````md-render |
| 532 |
--- |
| 533 |
extensions: |
| 534 |
- pymdownx.highlight |
| 535 |
- pymdownx.superfences |
| 536 |
|
| 537 |
extension_configs: |
| 538 |
pymdownx.highlight: |
| 539 |
auto_title: true |
| 540 |
auto_title_map: {"Python Console Session": "Python"} |
| 541 |
line_spans: __codeline_c |
| 542 |
line_anchors: __codelineno_c |
| 543 |
anchor_linenums: True |
| 544 |
--- |
| 545 |
```pycon |
| 546 |
>>> 3 + 3 |
| 547 |
6 |
| 548 |
``` |
| 549 |
```` |
| 550 |
|
| 551 |
## Pygments Line Anchors and Spans |
| 552 |
|
| 553 |
/// new | New 9.0 |
| 554 |
The various line wrapping options are new to version `9.0`. |
| 555 |
/// |
| 556 |
|
| 557 |
Pygments offers a couple of options that will wrap lines, line numbers even create anchor links for line numbers. |
| 558 |
SuperFences, when using Pygments, exposes these options under similar names. |
| 559 |
|
| 560 |
In this example, we will wrap each line of code in a span. Pygments will create an ID for each span using the prefix |
| 561 |
that we provide. We simply set the global config option `line_spans` and specify the desired "prefix" (`_codeline`), and |
| 562 |
then every line will be wrapped in a span with the ID `prefix-x-y` where `prefix` is the user specified prefix, `x` is a |
| 563 |
unique number for the code block, and `y` is the line number. After that, it is up to the user to do as they with to |
| 564 |
target the ID with either JavaScript and/or CSS. |
| 565 |
|
| 566 |
/// tab | Config |
| 567 |
|
| 568 |
```py3 |
| 569 |
extension_configs = { |
| 570 |
"pymdownx.highlight": { |
| 571 |
'linenums_style': 'inline', |
| 572 |
'line_spans': '__codeline' |
| 573 |
} |
| 574 |
} |
| 575 |
``` |
| 576 |
/// |
| 577 |
|
| 578 |
/// tab | Markdown |
| 579 |
```` |
| 580 |
```python {linenums="1 1" } |
| 581 |
import foo |
| 582 |
``` |
| 583 |
```` |
| 584 |
/// |
| 585 |
|
| 586 |
/// tab | HTML |
| 587 |
```html |
| 588 |
<div class="highlight"> |
| 589 |
<pre> |
| 590 |
<span></span> |
| 591 |
<code> |
| 592 |
<span id="__codeline-0-1"><span class="linenos">1</span><span class="kn">import</span> <span class="nn">foo</span> |
| 593 |
</span> |
| 594 |
</code> |
| 595 |
</pre> |
| 596 |
</div> |
| 597 |
``` |
| 598 |
/// |
| 599 |
|
| 600 |
We can also wrap line numbers with a link and inject anchors so you can click line numbers and be taken to said line. To |
| 601 |
do this, `anchor_linenums` must be enabled and then a prefix should be provided via `line_anchors`, just like |
| 602 |
`line_spans`, `line_anchors` will produce an ID in the form `prefix-x-y` where `x` is a unique number for the code block |
| 603 |
and `y` is the line number. If you wish to not have the line numbers clickable, and just have the anchors inserted, |
| 604 |
you can omit enabling `anchor_linenums`. |
| 605 |
|
| 606 |
/// tab | Config |
| 607 |
```py3 |
| 608 |
extension_configs = { |
| 609 |
"pymdownx.highlight": { |
| 610 |
'linenums_style': 'inline', |
| 611 |
'line_spans': '__codeline', |
| 612 |
'line_anchors': '__codelineno', |
| 613 |
'anchor_linenums': True |
| 614 |
} |
| 615 |
} |
| 616 |
``` |
| 617 |
/// |
| 618 |
|
| 619 |
/// tab | Markdown |
| 620 |
```` |
| 621 |
```python {linenums="1 1" } |
| 622 |
import foo |
| 623 |
``` |
| 624 |
```` |
| 625 |
/// |
| 626 |
|
| 627 |
/// tab | HTML |
| 628 |
```html |
| 629 |
<div class="highlight"> |
| 630 |
<pre> |
| 631 |
<span></span> |
| 632 |
<code> |
| 633 |
<span id="__codeline-0-1"><a id="__codelineno-0-1" name="__codelineno-0-1"></a><a href="#__codelineno-0-1"><span class="linenos">1</span></a><span class="kn">import</span> <span class="nn">foo</span> |
| 634 |
</span> |
| 635 |
</code> |
| 636 |
</pre> |
| 637 |
</div> |
| 638 |
``` |
| 639 |
/// |
| 640 |
|
| 641 |
## Relaxed Headers |
| 642 |
|
| 643 |
/// new | New in 10.15 |
| 644 |
/// |
| 645 |
|
| 646 |
The `relaxed_headers` [option][#options] is a feature that can be enabled which will cause SuperFences to treat fenced |
| 647 |
code headers in a more relaxed manner. |
| 648 |
|
| 649 |
The default approach of SuperFences is to bail on processing a fenced code if the there is invalid content in a fenced |
| 650 |
header. This may be because you are processing fenced code blocks from other, incompatible Markdown parsers. Having a |
| 651 |
way to treat incompatible code blocks as code blocks, even if they have invalid syntax may be desirable. |
| 652 |
|
| 653 |
As an example, some Markdown parsers may allow for specifying line highlights with `[number]`. This is not supported in |
| 654 |
SuperFences, but if we were processing such a block, with `relaxed_headers` enabled, we would treat it as an actual |
| 655 |
code block ignoring the invalid syntax instead of assuming the entire code block was invalid. |
| 656 |
|
| 657 |
````text title="Bad Code Header Syntax" |
| 658 |
```python [3] |
| 659 |
import code |
| 660 |
|
| 661 |
code.do_stuff() |
| 662 |
``` |
| 663 |
```` |
| 664 |
|
| 665 |
/// html | div.result |
| 666 |
````md-render |
| 667 |
--- |
| 668 |
extensions: |
| 669 |
- pymdownx.highlight |
| 670 |
- pymdownx.superfences |
| 671 |
|
| 672 |
extension_configs: |
| 673 |
pymdownx.superfences: |
| 674 |
relaxed_headers: true |
| 675 |
pymdownx.highlight: |
| 676 |
line_spans: __codeline_d |
| 677 |
line_anchors: __codelineno_d |
| 678 |
anchor_linenums: True |
| 679 |
--- |
| 680 |
```python [3] |
| 681 |
import code |
| 682 |
|
| 683 |
code.do_stuff() |
| 684 |
``` |
| 685 |
```` |
| 686 |
/// |
| 687 |
|
| 688 |
It should be noted that this mode does not always guarantee that your code language will be picked up or that relevant |
| 689 |
classes, IDs, attributes, or options will be recognized if invalid content is present, only that it will try and process |
| 690 |
the block as a code block. Additionally, a custom block that explicitly throws a `SuperFencesException` will still have |
| 691 |
that exception raised which will terminate Markdown processing. |
| 692 |
|
| 693 |
## Custom Fences |
| 694 |
|
| 695 |
SuperFences allows defining custom fences for special purposes. For instance, we could create special fences for |
| 696 |
diagrams that we could later run Mermaid on. |
| 697 |
|
| 698 |
````text title="Flow Chart" |
| 699 |
```diagram |
| 700 |
graph TD |
| 701 |
A[Hard] -->|Text| B(Round) |
| 702 |
B --> C{Decision} |
| 703 |
C -->|One| D[Result 1] |
| 704 |
C -->|Two| E[Result 2] |
| 705 |
``` |
| 706 |
```` |
| 707 |
|
| 708 |
/// html | div.result |
| 709 |
```diagram |
| 710 |
graph TD |
| 711 |
A[Hard] -->|Text| B(Round) |
| 712 |
B --> C{Decision} |
| 713 |
C -->|One| D[Result 1] |
| 714 |
C -->|Two| E[Result 2] |
| 715 |
``` |
| 716 |
/// |
| 717 |
|
| 718 |
This would allow us access to all the diagrams Mermaid offers. Some Mermaid diagrams are less practical to use as they |
| 719 |
don't scale well, but many work great. |
| 720 |
|
| 721 |
In the above example, we have set up a custom fence called `diagram` which allows us to process special charts with |
| 722 |
[Mermaid][mermaid]. In this case, our special fence preserves the content and sends them to a an element so that |
| 723 |
[Mermaid][mermaid] can then find them and convert them when the document is loaded. To learn more see [UML Diagram |
| 724 |
Example](#uml-diagram-example). |
| 725 |
|
| 726 |
Custom fences are created via the `custom_fences` option. `custom_fences` takes an array of dictionaries where each |
| 727 |
dictionary defines a custom fence. The dictionaries require the following keys: |
| 728 |
|
| 729 |
Keys | Description |
| 730 |
----------- | ----------- |
| 731 |
`name` | The language name that is specified when using the fence in Markdown. If given `*`, it will override the base fence logic, the default for all fence names not handled by other custom fences. |
| 732 |
`class` | The class name assigned to the HTML element when converting from Markdown to HTML. |
| 733 |
`format` | A function that formats the HTML output. The function should return a string as HTML. |
| 734 |
`validator` | An optional parameter that is used to provide a function to validate custom fence parameters. |
| 735 |
|
| 736 |
/// warning | Logging |
| 737 |
When a custom fence fails, the error will be swallowed up and the error will be handled gracefully. If logging is |
| 738 |
desired, custom logging should be added into the custom function. SuperFences will not provide any. |
| 739 |
/// |
| 740 |
|
| 741 |
/// new | New in 7.0 |
| 742 |
Starting in 7.0, you can override the base fence logic (the syntax highlighter) by specifying the custom fence |
| 743 |
with a name of `*`. This means that if a fence does not match any other custom fences, the default, fallback fence |
| 744 |
would be handled by your custom `*` fence. This can be useful for tailoring a fence output with custom parameters |
| 745 |
for a specific, favorite JavaScript highlighter. |
| 746 |
/// |
| 747 |
|
| 748 |
### Formatters |
| 749 |
|
| 750 |
SuperFences provides two format functions by default, but you can always write your own: |
| 751 |
|
| 752 |
Format\ Function | Description |
| 753 |
------------------------------- | ----------- |
| 754 |
`superfences.fence_code_format` | Places the HTML escaped content of the fence under a `#!html <pre><code>` block. |
| 755 |
`superfences.fence_div_format` | Places the HTML escaped content of the fence under a `#!html <div>` block. |
| 756 |
|
| 757 |
In general, formatters take five parameters: the source found between the fences, the specified language, the class name |
| 758 |
originally defined via the `class` option in the `custom_fence` entry, custom options, additional classes defined in |
| 759 |
brace style headers, an optional ID, any attributes defined in the brace style header, and the Markdown object (in case |
| 760 |
you want access to meta data etc.). |
| 761 |
|
| 762 |
```py3 |
| 763 |
def custom_formatter(source, language, css_class, options, md, classes=None, id_value='', attrs=None, **kwargs): |
| 764 |
return string |
| 765 |
``` |
| 766 |
|
| 767 |
or |
| 768 |
|
| 769 |
```py3 |
| 770 |
def custom_formatter(source, language, css_class, options, md, **kwargs): |
| 771 |
return string |
| 772 |
``` |
| 773 |
|
| 774 |
All formatters should return a string as HTML. |
| 775 |
|
| 776 |
/// tip | YAML Configuration Format |
| 777 |
If you are attempting to configure these options in a YAML based configuration (like in [MkDocs][mkdocs]), please |
| 778 |
see the [FAQ](../faq.md#function-references-in-yaml) to see how to specify function references in YAML. |
| 779 |
/// |
| 780 |
|
| 781 |
/// new | New 7.0 |
| 782 |
The addition of the parameters `classes` and `id_value` is new in 7.0. If injecting additional classes or ids via |
| 783 |
[brace headers](#injecting-classes-ids-and-attributes), only then will `classes` and `id_value` be passed in to preserve |
| 784 |
backwards compatibility with old custom formatters. Users, moving forward, should at the very least update their |
| 785 |
formatters with `**kwargs` to future proof their custom formatters in case additional parameters are added in the |
| 786 |
future. |
| 787 |
/// |
| 788 |
|
| 789 |
/// new | Changes 8.0 |
| 790 |
Formatters now take the keyword parameter `attrs`. |
| 791 |
/// |
| 792 |
|
| 793 |
### Validators |
| 794 |
|
| 795 |
The `validator` is used to provide a function that allows the validation of inputs. Inputs are then sorted to either |
| 796 |
`attrs` or `options`. While a `formatter` can treat `attrs` and `options` however they like, the intention is that key |
| 797 |
value pairs assigned to `attrs` are assigned directly to the fenced block's element, while `options` are used to |
| 798 |
conditionally control logic within the formatter. If no validator is defined, the default is used which assigns all |
| 799 |
inputs to `attrs`. |
| 800 |
|
| 801 |
SuperFences will only pass `attrs` to a formatter if an attribute style header is used for a fenced block |
| 802 |
(` ```lang {attr="value"}`) and the [`attr_list`][attr-list] extension is enabled. Attribute are not supported in the |
| 803 |
form (` ```lang attr=value`) and will cause the parsing of the fenced block to abort. |
| 804 |
|
| 805 |
Custom options can be used as keys with quoted values (`key="value"`), or as keys with no value (`key`). If a key is |
| 806 |
given with no value, the value will be the key value. SuperFences will parse the options in the fence and then pass them |
| 807 |
to the validator. If the validator returns true, the options will be accepted and later passed to the formatter. `attrs` |
| 808 |
will only be passed to the formatter if the [`attr_list`][attr-list] extension is enabled. `attrs` will also be ignored |
| 809 |
during Pygments highlighting. |
| 810 |
|
| 811 |
Assuming a validator fails, the next `validator`/`formatter` defined will be tried. |
| 812 |
|
| 813 |
For a contrived example: if we wanted to define a custom fence named `test` that accepts an option `opt` that can only |
| 814 |
be assigned a value of `A`, we could define the validator below. Notice that if we get an input that matches `opt`, but |
| 815 |
doesn't validate with the appropriate value, we abort handling the fenced block for this `validator`/`formatter` by |
| 816 |
returning `False`. All other inputs are assigned as `attrs` which will be passed to the formatter if the |
| 817 |
[`attr_list`][attr-list] extension is enabled. |
| 818 |
|
| 819 |
```py3 |
| 820 |
def custom_validator(language, inputs, options, attrs, md): |
| 821 |
"""Custom validator.""" |
| 822 |
|
| 823 |
okay = True |
| 824 |
for k, v in inputs.items(): |
| 825 |
if k == 'opt': |
| 826 |
if v != "A": |
| 827 |
okay = False |
| 828 |
break |
| 829 |
else: |
| 830 |
options[k] = v |
| 831 |
else: |
| 832 |
attrs[k] = v |
| 833 |
|
| 834 |
return okay |
| 835 |
``` |
| 836 |
|
| 837 |
Assuming validation passed, the formatter would be given the option and any attributes (though the formatter below |
| 838 |
doesn't use the attributes). |
| 839 |
|
| 840 |
```py3 |
| 841 |
def custom_format(source, language, class_name, options, md, **kwargs): |
| 842 |
"""Custom format.""" |
| 843 |
|
| 844 |
return '<div class_name="%s %s", data-option="%s">%s</div>' % (language, class_name, options['opt'], html_escape(source)) |
| 845 |
``` |
| 846 |
|
| 847 |
This would allow us to use the following custom fence: |
| 848 |
|
| 849 |
```` |
| 850 |
```test {opt="A"} |
| 851 |
test |
| 852 |
``` |
| 853 |
```` |
| 854 |
|
| 855 |
/// tip | YAML Configuration Format |
| 856 |
If you are attempting to configure these options in a YAML based configuration (like in [MkDocs][mkdocs]), please |
| 857 |
see the [FAQ](../faq.md#function-references-in-yaml) to see how to specify function references in YAML. |
| 858 |
/// |
| 859 |
|
| 860 |
/// new | Changes 8.0 |
| 861 |
- `validator` now accepts the following variables: |
| 862 |
- `inputs`: with all the parsed options/attributes (validator should not modify this structure). |
| 863 |
- `options`: a dictionary to which all valid options should be assigned to. |
| 864 |
- `attrs`: a dictionary to which all valid attributes should be assigned to. |
| 865 |
- `md`: the `Markdown` object. |
| 866 |
- If the [`attr_list`][attr-list] extension is enabled and the brace style header is used, any key/value pairs that |
| 867 |
were assigned as attributes by the `validator` will be passed to the `formatter`'s `attrs` parameter. |
| 868 |
- Options in the form of `key=` (which have no value) will are no longer be allowed. A `key` with no value will |
| 869 |
assume the `value` to be the `key` name. This brings consistency as options are now parsed with |
| 870 |
[`attr_list`][attr-list]. |
| 871 |
- If a `validator` fails, the next `validator`/`formatter` pair will be tired. |
| 872 |
/// |
| 873 |
|
| 874 |
### Exception Handling |
| 875 |
|
| 876 |
In general, if an exception occurs in either a validator or a formatter, SuperFences will gracefully ignore the |
| 877 |
validator or formatter. In the case of validators, this usually means it will try the next validator in the line. In the |
| 878 |
case of a formatter, the fenced content will just be abandoned as we are already past the point of "validating" and will |
| 879 |
not go back to validate the use of a different formatter. |
| 880 |
|
| 881 |
Some users may want such failures to not silently go by. SuperFences exposes a special exception called |
| 882 |
`SuperFencesException` which, if raised, will not gracefully be handled. If `SuperFencesException` is raised, this will |
| 883 |
likely bubble all the way up and cause Markdown parsing to halt. `SuperFencesException` can be used to raise other |
| 884 |
exceptions if desired. |
| 885 |
|
| 886 |
Here we have a contrived example. When no options are provided in this validator, we will try and access a non-existent |
| 887 |
key in the validator which will throw a `KeyError`. In this case, we capture the `KeyError` and raise it with |
| 888 |
`SuperFencesException`. This will display the `SuperFencesException` **and** the original `KeyError` when the failure |
| 889 |
occurs: |
| 890 |
|
| 891 |
```py |
| 892 |
def custom_validator_except(language, inputs, options, attrs, md): |
| 893 |
"""Custom validator.""" |
| 894 |
|
| 895 |
okay = True |
| 896 |
try: |
| 897 |
for k in inputs.keys(): |
| 898 |
if k != 'opt': |
| 899 |
okay = False |
| 900 |
break |
| 901 |
if okay: |
| 902 |
if inputs['opt'] != "A": |
| 903 |
okay = False |
| 904 |
else: |
| 905 |
options['opt'] = inputs['opt'] |
| 906 |
except KeyError as e: |
| 907 |
raise SuperFencesException from e |
| 908 |
|
| 909 |
return okay |
| 910 |
``` |
| 911 |
|
| 912 |
/// new | New 9.2 |
| 913 |
`SuperFencesException` added in 9.2 |
| 914 |
/// |
| 915 |
|
| 916 |
### UML Diagram Example |
| 917 |
|
| 918 |
/// warning | Support |
| 919 |
This example is mainly used to illustrate how custom fences work. While Mermaid is used in the example, it is the |
| 920 |
bare minimum needed to get diagrams working. |
| 921 |
|
| 922 |
Please reference [Mermaid's][mermaid] documents for more information on configuring features. PyMdown Extensions |
| 923 |
does not offer direct support for issues you may have in using [Mermaid][mermaid], feel free to use their issue |
| 924 |
tracker to report problems with their library. |
| 925 |
|
| 926 |
We do provide some [advanced notes on Mermaid](../extras/mermaid.md) if you are interested in learning how we use |
| 927 |
and configure it in our own documentation. |
| 928 |
/// |
| 929 |
|
| 930 |
This example illustrates how you can use the `custom_fences` option to do UML diagrams with [Mermaid][mermaid]. The |
| 931 |
settings below show us creating a new custom fence called `mermaid`. The special fence is set under the `custom_fences` |
| 932 |
[option](#options). |
| 933 |
|
| 934 |
The `mermaid` fences will pass the content through the `superfences.fence_div_format` format function which will wrap |
| 935 |
the content in `#!html <div>` blocks and attach the class `mermaid` to the `#!html <div>` block. |
| 936 |
|
| 937 |
```py3 |
| 938 |
extension_configs = { |
| 939 |
"pymdownx.superfences": { |
| 940 |
"custom_fences": [ |
| 941 |
{ |
| 942 |
'name': 'mermaid', |
| 943 |
'class': 'mermaid', |
| 944 |
'format': pymdownx.superfences.fence_div_format |
| 945 |
} |
| 946 |
] |
| 947 |
} |
| 948 |
} |
| 949 |
``` |
| 950 |
|
| 951 |
This would allow a user to create fenced blocks with the `mermaid` specifier: |
| 952 |
|
| 953 |
```` |
| 954 |
```mermaid |
| 955 |
...content here |
| 956 |
``` |
| 957 |
```` |
| 958 |
|
| 959 |
The format function we used in this example only escapes the content to be included in HTML. We will rely on the |
| 960 |
[Mermaid][mermaid] JavaScript library to render our flowcharts/diagrams in the browser. [Mermaid][mermaid], on load, |
| 961 |
will automatically find the `#!html <div>` elements with the `mermaid` class and render them. We can include |
| 962 |
[Mermaid][mermaid] via its CDN. |
| 963 |
|
| 964 |
```html |
| 965 |
<script src="https://unpkg.com/[email protected]/dist/mermaid.min.js"></script> |
| 966 |
``` |
| 967 |
|
| 968 |
## Limitations |
| 969 |
|
| 970 |
This extension suffers from some of the same quirks that the original fenced block extension suffers from. Normally |
| 971 |
Python Markdown does not parse content inside HTML tags unless they are marked with the attribute `markdown='1'`. But |
| 972 |
since this is run as a preprocessor, it is not aware of the HTML blocks. |
| 973 |
|
| 974 |
SuperFences is made to work with the default extensions out of the box. It will probably not work with other extensions |
| 975 |
such as Grid Tables, since that extension allows for characters to obscure the blocks like the blockquote syntax does |
| 976 |
(though this has been designed to work with blockquotes). Ideally fenced blocks need to be handled by a block parser, |
| 977 |
but there is much work to be done on Python Markdown's internal block handlers before this is possible. |
| 978 |
|
| 979 |
SuperFences works best when following the guidelines. If the guidelines are not followed, odd results may be |
| 980 |
encountered. |
| 981 |
|
| 982 |
For the reasons above, the nested fences feature really is just a workaround. But for a lot of people, this |
| 983 |
functionality is more than sufficient. |
| 984 |
|
| 985 |
## Options |
| 986 |
|
| 987 |
Option | Type | Default | Description |
| 988 |
------------------------------ | ------------ | ------------- | ----------- |
| 989 |
`css_class` | string | `#!py3 ''` | Class name is applied to the wrapper element of the code. If configured, this setting will override the `css_class` option of Highlight. If nothing is configured here or in Highlight, the class `highlight` will be used. |
| 990 |
`disable_indented_code_blocks` | bool | `#!py3 False` | Disables Python Markdown's indented code block parsing. This is nice if you only ever use fenced blocks. |
| 991 |
`custom_fences` | [dictionary] | `#!py3 []` | Custom fences. |
| 992 |
`preserve_tabs` | bool | `#!py3 False` | Experimental feature that preserves tabs in fenced code blocks. |
| 993 |
`relaxed_headers` | bool | `#!py3 False` | Enable relaxed fenced code headers that are more forgiving of invalid content in the fenced header. |