| 1 |
--- |
| 2 |
icon: lucide/square-scissors |
| 3 |
--- |
| 4 |
[:octicons-file-code-24:][_snippets]{: .source-link } |
| 5 |
|
| 6 |
# Snippets |
| 7 |
|
| 8 |
## Overview |
| 9 |
|
| 10 |
/// warning | Not Meant for User Facing Sites |
| 11 |
Snippets is intended for documentation/static content workflows and **must not** be used to render untrusted/user-supplied |
| 12 |
content dynamically (public-facing sites, user comments, wikis, etc.). |
| 13 |
|
| 14 |
**Security note:** enabling features like **URL Snippets** (`url_download`) can cause the renderer to make outbound HTTP |
| 15 |
requests to arbitrary URLs (including localhost/internal networks), which can lead to SSRF-style risk in unsafe |
| 16 |
deployments. |
| 17 |
|
| 18 |
See [Security Considerations](#security-considerations) for details and concrete examples. |
| 19 |
/// |
| 20 |
|
| 21 |
Snippets is an extension to insert markdown or HTML snippets into another markdown file. Snippets is great for |
| 22 |
situations where you have content you need to insert into multiple documents. For instance, this document keeps all its |
| 23 |
hyperlinks in a separate file and then includes those hyperlinks at the bottom of a document via Snippets. If a link |
| 24 |
needs to be updated, it can be updated in one location instead of updating them in multiple files. |
| 25 |
|
| 26 |
Snippets is run as a preprocessor, so if a snippet is found in a fenced code block etc., it will still get processed. |
| 27 |
|
| 28 |
If a snippet declaration is processed, and the specified file cannot be found, then the markup will be removed. |
| 29 |
|
| 30 |
Snippets can handle recursive file inclusion. And if Snippets encounters the same file in the current stack, it will |
| 31 |
avoid re-processing it in order to avoid an infinite loop (or crash on hitting max recursion depth). |
| 32 |
|
| 33 |
This is meant for simple file inclusion, it has no intention to implement features from complex template systems. If you |
| 34 |
need something more complex, you may consider using a template environment to process your files **before** feeding them |
| 35 |
through Python Markdown. If you are using a document generation system, this can likely be performed via a plugin for |
| 36 |
that document system (assuming a plugin environment is available). |
| 37 |
|
| 38 |
The Snippets extension can be included in Python Markdown by using the following: |
| 39 |
|
| 40 |
```py3 |
| 41 |
import markdown |
| 42 |
md = markdown.Markdown(extensions=['pymdownx.snippets']) |
| 43 |
``` |
| 44 |
|
| 45 |
## Snippets Notation |
| 46 |
|
| 47 |
There are two modes of inserting snippets: single line and block. Single line mode accepts a single file name, and block |
| 48 |
accepts multiple files. Snippets does not require a specific extension, and as long as a valid file name is specified, |
| 49 |
it will attempt to process it. |
| 50 |
|
| 51 |
Snippets paths are relative to base location, by default the current working directory. You can specify a new base |
| 52 |
location by setting the `base_path`. You can even allow downloading snippets from external locations. To learn more, |
| 53 |
check out ["Specifying Snippet Locations"](#specifying-snippet-locations) and ["URL Snippets"](#url-snippets). |
| 54 |
|
| 55 |
### Single Line Format |
| 56 |
|
| 57 |
Single line format is done by placing the following markup for the single line notation: |
| 58 |
|
| 59 |
``` |
| 60 |
;--8<-- "filename.ext" |
| 61 |
``` |
| 62 |
|
| 63 |
As you can see, the notation is ASCII scissors cutting a line followed by the file name. In the case of the single line |
| 64 |
variant, the file name follows directly after the scissors and is quoted. In the case of the block format, the file |
| 65 |
names follow on separate lines and an additional scissor is added afterwards to signal the end of the block. |
| 66 |
|
| 67 |
The dashes can be as few as 1 (`-8<-`) or longer if desired (`---8<---------`); whatever your preference is. The |
| 68 |
important thing is that the notation must reside on a line(s) by itself, and the path, must be quoted in the case of the |
| 69 |
single line notation. If the file name is indented, the content will be indented to that level as well. |
| 70 |
|
| 71 |
/// note |
| 72 |
XML parsers are sensitive to dashes, so snippet syntax should use single dashes (`-8<-`) when placed within an XML. |
| 73 |
/// |
| 74 |
|
| 75 |
You can temporarily disable the snippet by placing a `;` before the file name: |
| 76 |
|
| 77 |
``` |
| 78 |
;--8<-- "; skip.md" |
| 79 |
``` |
| 80 |
|
| 81 |
### Block Format |
| 82 |
|
| 83 |
The second approach is known as the block format. Block format allows you to insert multiple files. |
| 84 |
|
| 85 |
``` |
| 86 |
;--8<-- |
| 87 |
filename.md |
| 88 |
filename.log |
| 89 |
;--8<-- |
| 90 |
``` |
| 91 |
The block format differs from the single format by requiring the content to be fenced between two `--8<--`. The start |
| 92 |
and end `--8<--` must be on a line by themselves. |
| 93 |
|
| 94 |
When using the block format empty lines are also preserved within the block. Consider the example below. |
| 95 |
|
| 96 |
``` |
| 97 |
;--8<-- |
| 98 |
fileA.md |
| 99 |
|
| 100 |
fileB.md |
| 101 |
;--8<-- |
| 102 |
``` |
| 103 |
|
| 104 |
This would yield: |
| 105 |
|
| 106 |
``` |
| 107 |
Content of file A. |
| 108 |
|
| 109 |
Content of file B. |
| 110 |
``` |
| 111 |
|
| 112 |
If you have a file you want to temporarily ignore, you can comment it out by placing a `;` at the start of the line. |
| 113 |
|
| 114 |
``` |
| 115 |
;--8<-- |
| 116 |
include.md |
| 117 |
; skip.md |
| 118 |
;--8<-- |
| 119 |
``` |
| 120 |
|
| 121 |
### Snippet Lines |
| 122 |
|
| 123 |
/// new | New 9.6 |
| 124 |
/// |
| 125 |
|
| 126 |
When specifying a snippet, you can specify which lines of the Snippet file that you wish to include. To specify line |
| 127 |
numbers, simply append the start and/or end to the end of the file name with each number separated with `:`. |
| 128 |
|
| 129 |
- To specify extraction of content to start at a specific line number, simply use `file.md:3`. |
| 130 |
- To extract all content up to a specific line, use `file.md::3`. This will extract lines 1 - 3. |
| 131 |
- To extract all content starting at a specific line up to another line, use `file.md:4:6`. This will extract lines |
| 132 |
4 - 6. |
| 133 |
- If you'd like to specify multiple blocks of extraction, separate each one with a `,`: `file.md:1:3,5:6`. |
| 134 |
|
| 135 |
Each line selection is evaluated independently of previous selections. Selections will be performed in the order |
| 136 |
they are specified. No additional separators (empty lines or otherwise) are inserted between selections, they are |
| 137 |
inserted exactly as specified. |
| 138 |
- Negative indexes can be used as well and will be converted to positive indexes based on the total number of lines |
| 139 |
in the snippet. If a snippet has 10 lines, then `-1` would correspond with line `10` and `-10` would correspond with |
| 140 |
line `1`. |
| 141 |
|
| 142 |
Be mindful of snippets with trailing, empty new lines at the end as those will be considered as well. |
| 143 |
|
| 144 |
/// note |
| 145 |
Lines are never specified with `0`. If `0` is used it will be clamped to `1`. |
| 146 |
/// |
| 147 |
|
| 148 |
``` |
| 149 |
;--8<-- "file.md:4:6" |
| 150 |
|
| 151 |
;--8<-- |
| 152 |
include.md::3 |
| 153 |
;--8<-- |
| 154 |
``` |
| 155 |
|
| 156 |
/// new | 10.13 |
| 157 |
Specifying multiple line selections separated with `,` and negative indexing was added in 10.13. |
| 158 |
/// |
| 159 |
|
| 160 |
### Snippet Sections |
| 161 |
|
| 162 |
/// new | New 9.7 |
| 163 |
/// |
| 164 |
|
| 165 |
Specifying snippet lines may not always be ideal. The source could change by moving, adding, and/or removing lines. A way |
| 166 |
around this is to partition a snippet into named sections and then targeting a specific section to be included instead |
| 167 |
of specific line numbers. |
| 168 |
|
| 169 |
Snippet sections can be specified by surrounding a block of text with `--8<-- [start:name]` and `--8<-- [end:name]`. |
| 170 |
Then a file can simply specify the snippet using the name instead of line numbers. |
| 171 |
|
| 172 |
``` |
| 173 |
;--8<-- "include.md:name" |
| 174 |
|
| 175 |
;--8<-- |
| 176 |
include.md:name |
| 177 |
;--8<-- |
| 178 |
``` |
| 179 |
|
| 180 |
Unlike other snippet syntax, the section start and end syntax do not have to be on a line by themselves. This allows |
| 181 |
you to embed them in comments depending on the file type. When a section is included, the line with the start and end |
| 182 |
are always omitted. |
| 183 |
|
| 184 |
If we wanted to include a function from a Python source, we could specify the snippet as follows: |
| 185 |
|
| 186 |
```python |
| 187 |
# ;--8<-- [start:func] |
| 188 |
def my_function(var): |
| 189 |
pass |
| 190 |
# ;--8<-- [end:func] |
| 191 |
``` |
| 192 |
|
| 193 |
And then just include it in our document: |
| 194 |
|
| 195 |
``` |
| 196 |
;--8<-- "example.py:func" |
| 197 |
``` |
| 198 |
|
| 199 |
### Escaping Snippets Notation |
| 200 |
|
| 201 |
/// new | New 9.6 |
| 202 |
/// |
| 203 |
|
| 204 |
If it is necessary to demonstrate the snippet syntax, an escaping method is required. If you need to escape snippets, |
| 205 |
just place a `;` right before `-8<-`. This will work for both single line and block format. An escaped snippet |
| 206 |
notation will be passed through the Markdown parser with the first `;` removed. |
| 207 |
|
| 208 |
|
| 209 |
````text title="Escaped Snippets" |
| 210 |
``` |
| 211 |
;;--8<-- "escaped.md" |
| 212 |
;;;--8<-- "escaped.md" |
| 213 |
``` |
| 214 |
```` |
| 215 |
|
| 216 |
/// html | div.result |
| 217 |
``` |
| 218 |
;--8<-- "escaped.md" |
| 219 |
;;--8<-- "escaped.md" |
| 220 |
``` |
| 221 |
/// |
| 222 |
|
| 223 |
/// warning | Legacy Escaping |
| 224 |
The legacy escape method required placing a space at the end of the line with `-8<-`, while this should still |
| 225 |
work, this behavior will be removed at sometime in the future and is discouraged. |
| 226 |
/// |
| 227 |
|
| 228 |
## Specifying Snippet Locations |
| 229 |
|
| 230 |
All snippets are specified relative to the base path(s) specified in the `base_path` option. `base_path` is a list of |
| 231 |
paths (though it will take a single string for legacy purposes). |
| 232 |
|
| 233 |
When evaluating paths, they are done in the order specified. The specified snippet will be evaluated against each base |
| 234 |
path and the first base path that yields a valid snippet will be returned. |
| 235 |
|
| 236 |
If a base path is a file, the specified snippet will be compared against the base name of that file. For instance, if |
| 237 |
we specified a snippet of `test.md` and we had a `base_path` of `#!py3 ["some/location/test.md"]`, this would match. |
| 238 |
A specified snippet of `location/test.md` would not match. This is great if you have a one off file outside of your |
| 239 |
base directory, but you'd like to directly include it. |
| 240 |
|
| 241 |
## URL Snippets |
| 242 |
|
| 243 |
URLs, if `url_download` is enabled, can also be used as snippets. Instead of using a file, simply specify a URL in |
| 244 |
its place. By default, a max size for content is specified with `url_max_size` and a default timeout via `url_timeout`. |
| 245 |
If either of these is set to zero, the limits will be ignored. |
| 246 |
|
| 247 |
To pass arbitrary HTTP headers in every HTTP request use `url_request_headers`. |
| 248 |
|
| 249 |
When a URL returns a 429 (Too Many Requests) status code, the extension will automatically retry the request with linear |
| 250 |
backoff. The retry behavior can be configured with: |
| 251 |
|
| 252 |
- `max_retries`: Maximum number of retry attempts (default: 3) |
| 253 |
- `backoff_factor`: Backoff factor for retry attempts (default: 2) |
| 254 |
|
| 255 |
For example, with default settings, the retry sequence would be: |
| 256 |
|
| 257 |
- First retry: 2 seconds |
| 258 |
- Second retry: 4 seconds |
| 259 |
- Third retry: 6 seconds |
| 260 |
|
| 261 |
/// warning | Nested Snippets |
| 262 |
One thing to note though, if a snippet is included via a URL, all nested snippets within it must also be URLs. URL |
| 263 |
snippets are not allowed to reference local snippet files. |
| 264 |
/// |
| 265 |
|
| 266 |
/// new | New 10.16 |
| 267 |
`max_retries` and `backoff_retries` was introduced in 10.16. |
| 268 |
/// |
| 269 |
|
| 270 |
/// new | New 9.5 |
| 271 |
URL snippet support was introduced in 9.5. |
| 272 |
/// |
| 273 |
|
| 274 |
## Dedent Subsections |
| 275 |
|
| 276 |
/// new | New 9.10 |
| 277 |
/// |
| 278 |
|
| 279 |
/// warning | Experimental |
| 280 |
/// |
| 281 |
|
| 282 |
By default, when a subsection is extracted from a file via the [section notation](#snippet-sections) or the |
| 283 |
[lines notation](#snippet-lines), the content is inserted exactly how it is extracted. Unfortunately, sometimes you are |
| 284 |
extracting an indented chunk, and you do not intend for that chunk to be indented. |
| 285 |
|
| 286 |
`dedent_subsections` is a recent option that has been added to see if it alleviates the issue. When specifying a |
| 287 |
subsection of a file to insert as a snippet, via "sections" or "lines", that content will have all common leading |
| 288 |
whitespace removed from every line in text. |
| 289 |
|
| 290 |
Depending on how the feature is received, it may be made the default in the future. |
| 291 |
|
| 292 |
## Auto-Append Snippets |
| 293 |
|
| 294 |
Snippets is designed as a general way to target a file and inject it into a given Markdown file, but some times, |
| 295 |
especially when building documentation via a library like [MkDocs][mkdocs], it may make sense to provide a way to append |
| 296 |
a given file to *every* Markdown document without having to manually include them via Snippet syntax in each page. This |
| 297 |
is especially useful for including a page of reference links or abbreviations on every page. |
| 298 |
|
| 299 |
Snippets provides an `auto_append` option that allows a user to specify a list of files that will be automatically |
| 300 |
appended to every Markdown content. Each entry in the list is searched for relative to the `base_path` entries. |
| 301 |
|
| 302 |
## Security Considerations |
| 303 |
|
| 304 |
Snippets is designed for documentation workflows and static content generation. It is **not** intended for use in |
| 305 |
public-facing services that render untrusted/user-supplied Markdown dynamically. |
| 306 |
|
| 307 |
### Why This Matters |
| 308 |
|
| 309 |
When Snippets processes a directive as shown below, it will attempt to include the referenced content into the rendered |
| 310 |
output. |
| 311 |
|
| 312 |
```text |
| 313 |
;--8<-- "some-target" |
| 314 |
``` |
| 315 |
|
| 316 |
If **URL Snippets** are enabled via `url_download`, the renderer may download content from arbitrary URLs. In unsafe |
| 317 |
deployments, this can cause the rendering environment to make outbound HTTP requests to attacker-chosen locations |
| 318 |
(including localhost and internal networks), which can resemble SSRF-style behavior. |
| 319 |
|
| 320 |
### Unsafe Example (Do Not Use With Untrusted Input) |
| 321 |
|
| 322 |
If an attacker can influence Markdown content and `url_download` is enabled, they may be able to trigger requests such |
| 323 |
as: |
| 324 |
|
| 325 |
```text |
| 326 |
;--8<-- "http://127.0.0.1:9999/" |
| 327 |
``` |
| 328 |
|
| 329 |
### Safe Usage Guidance |
| 330 |
|
| 331 |
If you use Snippets in public-facing CI, preview builds, or documentation pipelines: |
| 332 |
|
| 333 |
- Treat untrusted contributions with caution (e.g., PRs from external contributors). |
| 334 |
- Run builds in a sandbox/container with restrictive network/egress policies. |
| 335 |
- Avoid enabling `url_download` unless you fully understand the risk and have appropriate isolation in place. |
| 336 |
- Prefer static, trusted snippet sources whenever possible. |
| 337 |
|
| 338 |
## Options |
| 339 |
|
| 340 |
Option | Type | Default | Description |
| 341 |
---------------------- | --------------- | ---------------- |------------ |
| 342 |
`base_path` | \[string\] | `#!py3 ['.']` | A list of strings indicating base paths to be used resolve snippet locations. For legacy purposes, a single string will also be accepted as well. Base paths will be resolved in the order they are specified. When resolving a file name, the first match wins. If a file name is specified, the base name will be matched. |
| 343 |
`encoding` | string | `#!py3 'utf-8'` | Encoding to use when reading in the snippets. |
| 344 |
`check_paths` | bool | `#!py3 False` | Make the build fail if a snippet can't be found. |
| 345 |
`auto_append` | \[string\] | `#!py3 []` | A list of snippets (relative to the `base_path`) to auto append to the Markdown content. |
| 346 |
`url_download` | bool | `#!py3 False` | Allows URLs to be specified as file snippets. URLs will be downloaded and inserted accordingly. |
| 347 |
`url_max_size` | int | `#!py3 33554432` | Sets an arbitrary max content size. If content length is reported to be larger, and exception will be thrown. Default is ~32 MiB. |
| 348 |
`url_timeout` | float | `#!py3 10.0` | Passes an arbitrary timeout in seconds to URL requestor. By default this is set to 10 seconds. |
| 349 |
`url_request_headers` | {string:string} | `#!py3 {}` | Passes arbitrary headers to URL requestor. By default this is set to empty map. |
| 350 |
`dedent_subsections` | bool | `#!py3 False` | Remove any common leading whitespace from every line in text of a subsection that is inserted via "sections" or by "lines". |
| 351 |
`restrict_base_path` | bool | `#!py True` | Ensure that the specified snippets are children of the specified base path(s). This prevents a path relative to the base path, but not explicitly a child of the base path. |