0
# Configuration Management
1
2
Comprehensive configuration system for MyST-Parser through the `MdParserConfig` dataclass, providing fine-grained control over parsing behavior, syntax extensions, cross-references, and output formatting.
3
4
## Capabilities
5
6
### Main Configuration Class
7
8
The `MdParserConfig` dataclass provides comprehensive control over MyST parsing behavior with over 20 configuration options for syntax, extensions, formatting, and output generation.
9
10
```python { .api }
11
class MdParserConfig:
12
"""
13
Main configuration dataclass for MyST parser settings.
14
15
Attributes:
16
commonmark_only (bool): Use strict CommonMark parser only
17
gfm_only (bool): Use strict GitHub Flavored Markdown parser only
18
enable_extensions (set[str]): Enable syntax extensions
19
disable_syntax (Iterable[str]): Disable CommonMark syntax elements
20
all_links_external (bool): Parse all links as simple hyperlinks
21
links_external_new_tab (bool): Open external links in new tab
22
url_schemes (dict): URI schemes converted to external links
23
ref_domains (Iterable[str] | None): Sphinx domain names for link references
24
fence_as_directive (set[str]): Interpret code fences as directives
25
number_code_blocks (Sequence[str]): Add line numbers to code blocks
26
title_to_header (bool): Convert title field to H1 header
27
heading_anchors (int): Heading level depth for HTML anchors
28
heading_slug_func (Callable[[str], str] | None): Function for creating heading anchors
29
html_meta (dict[str, str]): HTML meta tags
30
footnote_sort (bool): Move footnotes to document end
31
footnote_transition (bool): Place transition before footnotes
32
words_per_minute (int): Reading speed calculations
33
"""
34
commonmark_only: bool = False
35
gfm_only: bool = False
36
enable_extensions: set[str] = field(default_factory=set)
37
disable_syntax: Iterable[str] = field(default_factory=list)
38
all_links_external: bool = False
39
links_external_new_tab: bool = False
40
url_schemes: dict = field(default_factory=dict)
41
ref_domains: Iterable[str] | None = None
42
fence_as_directive: set[str] = field(default_factory=set)
43
number_code_blocks: Sequence[str] = field(default_factory=list)
44
title_to_header: bool = False
45
heading_anchors: int = 0
46
heading_slug_func: Callable[[str], str] | None = None
47
html_meta: dict[str, str] = field(default_factory=dict)
48
footnote_sort: bool = False
49
footnote_transition: bool = False
50
words_per_minute: int = 200
51
```
52
53
Usage example:
54
55
```python
56
from myst_parser.config.main import MdParserConfig
57
58
# Create configuration with common settings
59
config = MdParserConfig(
60
enable_extensions={"tasklist", "deflist", "substitution", "colon_fence"},
61
heading_anchors=3,
62
footnote_sort=True,
63
footnote_transition=True,
64
html_meta={"author": "Documentation Team"},
65
words_per_minute=250
66
)
67
68
# Configuration for strict CommonMark parsing
69
strict_config = MdParserConfig(
70
commonmark_only=True,
71
enable_extensions=set() # No extensions in strict mode
72
)
73
74
# Configuration for external link handling
75
external_config = MdParserConfig(
76
all_links_external=True,
77
links_external_new_tab=True,
78
url_schemes={"http": ["external"], "https": ["external"]}
79
)
80
```
81
82
### File-Level Configuration
83
84
Merge file-level configuration from YAML frontmatter with global configuration settings, allowing per-document customization of parsing behavior.
85
86
```python { .api }
87
def merge_file_level(
88
config: MdParserConfig,
89
topmatter: dict,
90
warning: Callable
91
) -> MdParserConfig:
92
"""
93
Merge file-level configuration with global config.
94
95
Args:
96
config: Global MdParserConfig instance
97
topmatter: YAML frontmatter dictionary from document
98
warning: Warning callback function
99
100
Returns:
101
New MdParserConfig with merged settings
102
103
Raises:
104
TopmatterReadError: When frontmatter contains invalid configuration
105
"""
106
```
107
108
Usage example:
109
110
```python
111
from myst_parser.config.main import MdParserConfig, merge_file_level, read_topmatter
112
113
# Global configuration
114
global_config = MdParserConfig(
115
enable_extensions={"tasklist", "deflist"},
116
heading_anchors=2
117
)
118
119
# Document with YAML frontmatter
120
document_content = """---
121
myst:
122
enable_extensions: ["substitution", "colon_fence"]
123
heading_anchors: 4
124
footnote_sort: true
125
---
126
# Document Content
127
"""
128
129
# Read and merge configuration
130
topmatter = read_topmatter(document_content)
131
merged_config = merge_file_level(
132
global_config,
133
topmatter.get('myst', {}),
134
lambda msg: print(f"Warning: {msg}")
135
)
136
137
print(merged_config.enable_extensions) # {"substitution", "colon_fence"}
138
print(merged_config.heading_anchors) # 4
139
print(merged_config.footnote_sort) # True
140
```
141
142
### Frontmatter Processing
143
144
Read and parse YAML frontmatter from MyST document strings, extracting metadata and configuration overrides.
145
146
```python { .api }
147
def read_topmatter(text: str) -> dict:
148
"""
149
Read YAML frontmatter from source string.
150
151
Args:
152
text: Source text potentially containing YAML frontmatter
153
154
Returns:
155
Dictionary containing parsed YAML data
156
157
Raises:
158
TopmatterReadError: When YAML parsing fails
159
"""
160
```
161
162
Usage example:
163
164
```python
165
from myst_parser.config.main import read_topmatter
166
167
# Document with frontmatter
168
source = """---
169
title: "MyST Document"
170
author: "John Doe"
171
myst:
172
enable_extensions: ["tasklist"]
173
heading_anchors: 3
174
---
175
# Document Title
176
177
Content here...
178
"""
179
180
# Parse frontmatter
181
metadata = read_topmatter(source)
182
print(metadata['title']) # "MyST Document"
183
print(metadata['author']) # "John Doe"
184
print(metadata['myst']['enable_extensions']) # ["tasklist"]
185
```
186
187
### Configuration Validation
188
189
Comprehensive validation system for configuration options using dataclass validators, ensuring type safety and value constraints.
190
191
```python { .api }
192
def validate_field(inst, field, value) -> None:
193
"""
194
Validate single dataclass field.
195
196
Args:
197
inst: Dataclass instance
198
field: Field being validated
199
value: Value to validate
200
201
Raises:
202
ValueError: When validation fails
203
"""
204
205
def validate_fields(inst) -> None:
206
"""
207
Validate all dataclass fields.
208
209
Args:
210
inst: Dataclass instance to validate
211
212
Raises:
213
ValueError: When any field validation fails
214
"""
215
216
def instance_of(type_: type) -> ValidatorType:
217
"""
218
Create type validator.
219
220
Args:
221
type_: Expected type
222
223
Returns:
224
Validator function
225
"""
226
227
def optional(validator: ValidatorType) -> ValidatorType:
228
"""
229
Make attribute optional.
230
231
Args:
232
validator: Base validator
233
234
Returns:
235
Optional validator function
236
"""
237
238
def in_(options: Iterable) -> ValidatorType:
239
"""
240
Create value-in-options validator.
241
242
Args:
243
options: Allowed values
244
245
Returns:
246
Validator function
247
"""
248
249
def deep_iterable(
250
member_validator: ValidatorType,
251
iterable_validator: ValidatorType
252
) -> ValidatorType:
253
"""
254
Create deep iterable validator.
255
256
Args:
257
member_validator: Validator for iterable members
258
iterable_validator: Validator for iterable itself
259
260
Returns:
261
Deep iterable validator function
262
"""
263
```
264
265
Usage example:
266
267
```python
268
from myst_parser.config.dc_validators import validate_fields, instance_of, in_
269
from myst_parser.config.main import MdParserConfig
270
271
# Create configuration
272
config = MdParserConfig(
273
enable_extensions={"tasklist", "deflist"},
274
heading_anchors=3,
275
footnote_sort=True
276
)
277
278
# Validate all fields
279
try:
280
validate_fields(config)
281
print("Configuration is valid")
282
except ValueError as e:
283
print(f"Validation error: {e}")
284
285
# Custom validation example
286
from dataclasses import dataclass, field
287
288
@dataclass
289
class CustomConfig:
290
mode: str = field(validator=in_(["strict", "loose"]))
291
count: int = field(validator=instance_of(int))
292
```
293
294
## Types
295
296
Configuration-related type definitions:
297
298
```python { .api }
299
class TopmatterReadError(Exception):
300
"""Exception raised when reading YAML frontmatter fails."""
301
302
class UrlSchemeType(TypedDict):
303
"""Configuration for external URL schemes."""
304
allowed_schemes: tuple[str, ...]
305
classes: list[str]
306
307
ValidatorType = Callable[[object, object, object], None]
308
```