0
# Markdown-Include
1
2
A Python-Markdown extension which provides an 'include' function, similar to that found in LaTeX (and also the C pre-processor and Fortran). This extension enables recursive file inclusion using the syntax `{!filename!}` and supports advanced features like line range selection, heading depth inheritance, configurable base paths, and custom file encoding.
3
4
## Package Information
5
6
- **Package Name**: markdown-include
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install markdown-include`
10
11
## Core Imports
12
13
```python
14
import markdown
15
from markdown_include.include import MarkdownInclude
16
```
17
18
For factory function usage:
19
20
```python
21
from markdown_include.include import makeExtension
22
```
23
24
## Basic Usage
25
26
### Extension Registration
27
28
```python
29
import markdown
30
31
# Simple usage with default settings
32
html = markdown.markdown(source, extensions=['markdown_include.include'])
33
```
34
35
### Programmatic Configuration
36
37
```python
38
import markdown
39
from markdown_include.include import MarkdownInclude
40
41
# Create extension with custom configuration
42
markdown_include = MarkdownInclude(
43
configs={
44
'base_path': '/srv/content/',
45
'encoding': 'iso-8859-1',
46
'inheritHeadingDepth': True,
47
'headingOffset': 1,
48
'throwException': False
49
}
50
)
51
52
html = markdown.markdown(source, extensions=[markdown_include])
53
```
54
55
### Factory Function Usage
56
57
```python
58
import markdown
59
from markdown_include.include import makeExtension
60
61
extension = makeExtension(base_path='/srv/content/', encoding='utf-8')
62
html = markdown.markdown(source, extensions=[extension])
63
```
64
65
### MkDocs Integration
66
67
```yaml
68
markdown_extensions:
69
- markdown_include.include:
70
base_path: docs
71
inheritHeadingDepth: true
72
```
73
74
## Include Syntax
75
76
### Basic File Inclusion
77
78
```markdown
79
{!filename.md!}
80
```
81
82
Includes the entire content of `filename.md`. The extension works recursively, so any include statements within the included file will also be processed.
83
84
### Line-Specific Inclusion
85
86
```markdown
87
{!filename.md!lines=1 3 8-10 2}
88
```
89
90
Includes specific lines and ranges from the file:
91
- Individual lines: `1`, `3`, `2`
92
- Line ranges: `8-10` (includes lines 8, 9, and 10)
93
- Order matters: lines are included in the specified order, not file order
94
95
## Capabilities
96
97
### Extension Class
98
99
The main extension class that integrates with Python-Markdown.
100
101
```python { .api }
102
class MarkdownInclude(Extension):
103
def __init__(self, configs={}):
104
"""
105
Initialize the markdown-include extension.
106
107
Parameters:
108
- configs (dict): Configuration dictionary with extension settings
109
"""
110
111
def extendMarkdown(self, md):
112
"""
113
Register the include preprocessor with the Markdown instance.
114
115
Parameters:
116
- md: Markdown instance to extend
117
"""
118
```
119
120
### Preprocessor Class
121
122
The core processor that handles file inclusion syntax.
123
124
```python { .api }
125
class IncludePreprocessor(Preprocessor):
126
def __init__(self, md, config):
127
"""
128
Initialize the include preprocessor.
129
130
Parameters:
131
- md: Markdown instance
132
- config (dict): Configuration dictionary from MarkdownInclude
133
"""
134
135
def run(self, lines):
136
"""
137
Process markdown lines to replace include statements with file contents.
138
139
Parameters:
140
- lines (list): List of markdown lines to process
141
142
Returns:
143
list: Processed lines with include statements replaced
144
"""
145
```
146
147
### Factory Function
148
149
Creates a MarkdownInclude extension instance.
150
151
```python { .api }
152
def makeExtension(*args, **kwargs):
153
"""
154
Factory function to create MarkdownInclude extension instance.
155
156
Parameters:
157
- *args: Variable arguments (unused)
158
- **kwargs: Keyword arguments passed as configs to MarkdownInclude
159
160
Returns:
161
MarkdownInclude: Extension instance ready for use with Python-Markdown
162
"""
163
```
164
165
## Configuration Options
166
167
All configuration options can be specified when initializing the extension:
168
169
```python { .api }
170
# Configuration parameters for MarkdownInclude
171
configs = {
172
'base_path': str, # Default: "." - Base directory for relative paths
173
'encoding': str, # Default: "utf-8" - File encoding for included files
174
'inheritHeadingDepth': bool, # Default: False - Inherit heading depth from context
175
'headingOffset': int, # Default: 0 - Additional heading depth offset
176
'throwException': bool # Default: False - Whether to throw exceptions on file not found
177
}
178
```
179
180
### Configuration Details
181
182
- **base_path**: Directory from which relative paths are evaluated. Defaults to the current working directory.
183
- **encoding**: Character encoding used when reading included files. Defaults to UTF-8.
184
- **inheritHeadingDepth**: When true, headings in included files are increased by the depth of the previous heading in the parent document.
185
- **headingOffset**: Additional heading levels to add to all headings in included files, combined with inheritHeadingDepth.
186
- **throwException**: When true, missing files raise exceptions that can be caught. When false (default), warnings are printed and processing continues.
187
188
## Advanced Features
189
190
### Heading Depth Management
191
192
```python
193
# Example with heading depth inheritance
194
markdown_include = MarkdownInclude(
195
configs={'inheritHeadingDepth': True, 'headingOffset': 1}
196
)
197
```
198
199
Source document:
200
```markdown
201
# Main Heading
202
{!included.md!}
203
## Sub Heading
204
{!included.md!}
205
```
206
207
If `included.md` contains:
208
```markdown
209
# Included Heading
210
Content here.
211
```
212
213
Result with `inheritHeadingDepth=True`:
214
```markdown
215
# Main Heading
216
## Included Heading
217
Content here.
218
## Sub Heading
219
### Included Heading
220
Content here.
221
```
222
223
### Line Range Processing
224
225
The extension supports flexible line selection:
226
227
```markdown
228
{!large_file.md!lines=1-5 10 15-20}
229
```
230
231
- Ranges are inclusive: `1-5` includes lines 1, 2, 3, 4, and 5
232
- Out-of-bounds lines are handled gracefully with warnings
233
- Invalid ranges are corrected automatically
234
235
### Error Handling
236
237
```python
238
# Exception mode - raises FileNotFoundError for missing files
239
strict_include = MarkdownInclude(configs={'throwException': True})
240
241
try:
242
html = markdown.markdown(source, extensions=[strict_include])
243
except FileNotFoundError as e:
244
print(f"Include file not found: {e}")
245
246
# Warning mode (default) - prints warnings and continues
247
normal_include = MarkdownInclude(configs={'throwException': False})
248
html = markdown.markdown(source, extensions=[normal_include])
249
```
250
251
## Types
252
253
```python { .api }
254
# Import types from markdown library
255
from markdown.extensions import Extension
256
from markdown.preprocessors import Preprocessor
257
258
# Regular expression patterns used internally
259
import re
260
INC_SYNTAX = re.compile(r"{!\s*(.+?)\s*!((\blines\b)=([0-9 -]+))?}")
261
HEADING_SYNTAX = re.compile("^#+")
262
```