0
# Rendering
1
2
Multiple output format renderers for converting AST nodes to various formats including HTML and reStructuredText. Renderers provide customizable options and can be extended for additional output formats.
3
4
## Capabilities
5
6
### HTML Renderer
7
8
Converts AST nodes to HTML output with configurable options for handling line breaks and other formatting details.
9
10
```python { .api }
11
class HtmlRenderer:
12
def __init__(self, options={}):
13
"""
14
Initialize HTML renderer with optional configuration.
15
16
Args:
17
options (dict): Configuration options including:
18
- 'softbreak': String to use for soft line breaks (default: '\n')
19
- 'safe': Boolean to enable safe mode, filtering dangerous URLs (default: False)
20
- 'sourcepos': Boolean to add source position attributes (default: False)
21
"""
22
23
def render(self, ast):
24
"""
25
Render an AST to HTML.
26
27
Args:
28
ast (Node): Root node of the AST to render
29
30
Returns:
31
str: HTML representation of the AST
32
"""
33
34
def tag(self, name, attrs=None, selfclosing=None):
35
"""
36
Add an HTML tag to output buffer.
37
38
Args:
39
name (str): Tag name
40
attrs (list): List of [key, value] attribute pairs (optional)
41
selfclosing (bool): Whether tag is self-closing (optional)
42
"""
43
```
44
45
### reStructuredText Renderer
46
47
Converts AST nodes to reStructuredText format with configurable indentation.
48
49
```python { .api }
50
class ReStructuredTextRenderer:
51
def __init__(self, indent_char=' '):
52
"""
53
Initialize reStructuredText renderer.
54
55
Args:
56
indent_char (str): Character to use for indentation (default: space)
57
"""
58
59
def render(self, ast):
60
"""
61
Render an AST to reStructuredText.
62
63
Args:
64
ast (Node): Root node of the AST to render
65
66
Returns:
67
str: reStructuredText representation of the AST
68
"""
69
```
70
71
### Base Renderer Class
72
73
Abstract base class that provides common rendering functionality and can be extended to create custom renderers.
74
75
```python { .api }
76
class Renderer:
77
def render(self, ast):
78
"""
79
Render an AST by walking through all nodes.
80
81
Args:
82
ast (Node): Root node of the AST to render
83
84
Returns:
85
str: Rendered output (format depends on renderer implementation)
86
"""
87
88
def lit(self, s):
89
"""
90
Concatenate a literal string to the output buffer.
91
92
Args:
93
s (str): String to add to output
94
"""
95
96
def cr(self):
97
"""
98
Add a newline to output if not already present at the end.
99
"""
100
101
def out(self, s):
102
"""
103
Concatenate a string to output, possibly with escaping.
104
105
Args:
106
s (str): String to add to output
107
"""
108
```
109
110
## Usage Examples
111
112
### HTML Rendering
113
114
```python
115
from commonmark import Parser, HtmlRenderer
116
117
parser = Parser()
118
renderer = HtmlRenderer()
119
120
markdown = """
121
# Title
122
123
This is a paragraph with **bold** and *italic* text.
124
125
- List item 1
126
- List item 2
127
"""
128
129
ast = parser.parse(markdown)
130
html = renderer.render(ast)
131
print(html)
132
```
133
134
### HTML with Custom Options
135
136
```python
137
from commonmark import Parser, HtmlRenderer
138
139
parser = Parser()
140
renderer = HtmlRenderer(options={'softbreak': '<br />\n'})
141
142
markdown = "Line 1\nLine 2"
143
ast = parser.parse(markdown)
144
html = renderer.render(ast)
145
print(html) # Soft breaks rendered as <br /> tags
146
```
147
148
### reStructuredText Rendering
149
150
```python
151
from commonmark import Parser, ReStructuredTextRenderer
152
153
parser = Parser()
154
renderer = ReStructuredTextRenderer()
155
156
markdown = """
157
# Main Title
158
159
## Subtitle
160
161
Some text with **bold** formatting.
162
"""
163
164
ast = parser.parse(markdown)
165
rst = renderer.render(ast)
166
print(rst)
167
```
168
169
### Custom Indentation
170
171
```python
172
from commonmark import Parser, ReStructuredTextRenderer
173
174
parser = Parser()
175
renderer = ReStructuredTextRenderer(indent_char='\t') # Use tabs
176
177
markdown = """
178
- Item 1
179
- Nested item
180
- Item 2
181
"""
182
183
ast = parser.parse(markdown)
184
rst = renderer.render(ast)
185
print(rst) # Uses tab characters for indentation
186
```
187
188
### Multiple Format Rendering
189
190
```python
191
from commonmark import Parser, HtmlRenderer, ReStructuredTextRenderer
192
193
parser = Parser()
194
html_renderer = HtmlRenderer()
195
rst_renderer = ReStructuredTextRenderer()
196
197
markdown = "# Hello\n*World*"
198
ast = parser.parse(markdown)
199
200
html = html_renderer.render(ast)
201
rst = rst_renderer.render(ast)
202
203
print("HTML:", html)
204
print("RST:", rst)
205
```
206
207
## Renderer Options
208
209
### HTML Renderer Options
210
211
- `softbreak`: String to use for soft line breaks (default: `'\n'`)
212
- `safe`: Boolean to enable safe mode, filtering dangerous URLs like `javascript:` and `vbscript:` (default: `False`)
213
- `sourcepos`: Boolean to add `data-sourcepos` attributes to HTML elements with source position information (default: `False`)
214
215
### reStructuredText Renderer Options
216
217
- `indent_char`: Character to use for indentation (default: `' '` - space character)