0
# Core API
1
2
Essential functions for converting markdown to HTML with support for intermediate processing and dialect selection.
3
4
## Capabilities
5
6
### Parse Function
7
8
Parse markdown text into a JsonML tree representation for intermediate processing.
9
10
```javascript { .api }
11
/**
12
* Parse markdown text into JsonML tree representation
13
* @param {string} source - Markdown text to parse
14
* @param {string|Object} dialect - Dialect name ("Gruber", "Maruku") or dialect object (default: "Gruber")
15
* @returns {Array} JsonML tree representing markdown structure
16
*/
17
function parse(source, dialect);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
var markdown = require("markdown").markdown;
24
25
// Basic parsing
26
var tree = markdown.parse("Hello **World**!");
27
// Returns: ["markdown", {}, ["para", {}, "Hello ", ["strong", {}, "World"], "!"]]
28
29
// With Maruku dialect
30
var tree = markdown.parse("Hello **World**!\n{: .greeting}", "Maruku");
31
32
// Access references from parsed tree
33
var tree = markdown.parse("[Link text][ref]\n\n[ref]: http://example.com");
34
var references = tree[1].references;
35
console.log(references.ref.href); // "http://example.com"
36
```
37
38
### ToHTML Function
39
40
Convert markdown text or JsonML tree directly to HTML string with full processing.
41
42
```javascript { .api }
43
/**
44
* Convert markdown text or JsonML tree directly to HTML string
45
* @param {string|Array} source - Markdown text or JsonML tree from parse()
46
* @param {string|Object} dialect - Dialect name ("Gruber", "Maruku") or dialect object (default: "Gruber")
47
* @param {Object} options - Processing options
48
* @param {Function} options.preprocessTreeNode - Function to preprocess tree nodes before HTML conversion
49
* @returns {string} Well-formed HTML string
50
*/
51
function toHTML(source, dialect, options);
52
```
53
54
**Usage Examples:**
55
56
```javascript
57
var markdown = require("markdown").markdown;
58
59
// Simple conversion
60
var html = markdown.toHTML("Hello **World**!");
61
// Returns: "<p>Hello <strong>World</strong>!</p>"
62
63
// With dialect selection
64
var html = markdown.toHTML("# Header\n\nContent", "Maruku");
65
66
// With preprocessing options
67
var html = markdown.toHTML("Hello **World**!", "Gruber", {
68
preprocessTreeNode: function(jsonml, references) {
69
// Custom preprocessing logic
70
return jsonml;
71
}
72
});
73
74
// Convert existing JsonML tree
75
var tree = markdown.parse("Hello **World**!");
76
var html = markdown.toHTML(tree);
77
```
78
79
### ToHTMLTree Function
80
81
Convert markdown to HTML JsonML tree for custom processing before rendering.
82
83
```javascript { .api }
84
/**
85
* Convert markdown to HTML JsonML tree for processing
86
* @param {string|Array} input - Markdown text or markdown JsonML tree from parse()
87
* @param {string|Object} dialect - Dialect name ("Gruber", "Maruku") or dialect object (default: "Gruber")
88
* @param {Object} options - Processing options
89
* @param {Function} options.preprocessTreeNode - Function to preprocess tree nodes during conversion
90
* @returns {Array} JsonML tree representing HTML structure
91
*/
92
function toHTMLTree(input, dialect, options);
93
```
94
95
**Usage Examples:**
96
97
```javascript
98
var markdown = require("markdown").markdown;
99
100
// Convert to HTML tree for processing
101
var htmlTree = markdown.toHTMLTree("Hello **World**!");
102
// Returns: ["html", {}, ["p", {}, "Hello ", ["strong", {}, "World"], "!"]]
103
104
// Process HTML tree (e.g., collect all links)
105
function collectLinks(jsonml) {
106
var links = [];
107
if (Array.isArray(jsonml)) {
108
if (jsonml[0] === "a") {
109
links.push(jsonml[1].href);
110
}
111
for (var i = 1; i < jsonml.length; i++) {
112
if (Array.isArray(jsonml[i])) {
113
links = links.concat(collectLinks(jsonml[i]));
114
}
115
}
116
}
117
return links;
118
}
119
120
var htmlTree = markdown.toHTMLTree("[Link](http://example.com)");
121
var links = collectLinks(htmlTree);
122
console.log(links); // ["http://example.com"]
123
124
// Render processed tree to HTML
125
var html = markdown.renderJsonML(htmlTree);
126
```
127
128
### RenderJsonML Function
129
130
Render JsonML tree to well-formed HTML/XML string with formatting options.
131
132
```javascript { .api }
133
/**
134
* Render JsonML tree to well-formed HTML/XML string
135
* @param {Array} jsonml - JsonML array to render (from toHTMLTree or custom)
136
* @param {Object} options - Rendering options
137
* @param {boolean} options.root - Include root element in output (default: false)
138
* @returns {string} Well-formed HTML/XML string
139
*/
140
function renderJsonML(jsonml, options);
141
```
142
143
**Usage Examples:**
144
145
```javascript
146
var markdown = require("markdown").markdown;
147
148
// Basic rendering (excludes root element)
149
var htmlTree = ["html", {}, ["p", {}, "Hello World"]];
150
var html = markdown.renderJsonML(htmlTree);
151
// Returns: "<p>Hello World</p>"
152
153
// Include root element
154
var html = markdown.renderJsonML(htmlTree, { root: true });
155
// Returns: "<html><p>Hello World</p></html>"
156
157
// Custom JsonML construction
158
var customTree = [
159
"div",
160
{ class: "content", id: "main" },
161
["h1", {}, "Title"],
162
["p", {}, "Paragraph text"]
163
];
164
var html = markdown.renderJsonML(customTree, { root: true });
165
// Returns: '<div class="content" id="main"><h1>Title</h1><p>Paragraph text</p></div>'
166
```
167
168
### Advanced Multi-Stage Processing
169
170
Example of using the three-stage architecture for custom processing:
171
172
```javascript
173
var markdown = require("markdown").markdown;
174
175
// Stage 1: Parse markdown to markdown JsonML
176
var text = "[Markdown] is a simple [markup language]\n\n[markup language]: http://example.com";
177
var markdownTree = markdown.parse(text);
178
179
// Access and modify references
180
var refs = markdownTree[1].references;
181
if (!refs["markdown"]) {
182
refs["markdown"] = {
183
href: "http://en.wikipedia.org/wiki/Markdown"
184
};
185
}
186
187
// Stage 2: Convert to HTML JsonML
188
var htmlTree = markdown.toHTMLTree(markdownTree);
189
190
// Stage 3: Render to HTML string
191
var html = markdown.renderJsonML(htmlTree);
192
console.log(html);
193
// Result includes both original and added references
194
```
195
196
## Error Handling
197
198
The core API functions handle errors as follows:
199
200
- **parse()**: Throws Error for unknown dialects
201
- **toHTML()**: Throws Error for unknown dialects
202
- **toHTMLTree()**: Throws Error for unknown dialects
203
- **renderJsonML()**: Does not throw, handles malformed JsonML gracefully
204
205
All functions return deterministic results for valid inputs and fail fast for invalid dialects.
206
207
## Utility Functions
208
209
### mk_block Function
210
211
Create enhanced string blocks with metadata for internal processing.
212
213
```javascript { .api }
214
/**
215
* Create enhanced string block with metadata
216
* @param {string} block - Block content
217
* @param {string} trail - Trailing content (default: "\n\n")
218
* @param {number} line - Line number (optional)
219
* @returns {string} Enhanced string with trailing and lineNumber properties
220
*/
221
function mk_block(block, trail, line);
222
```
223
224
**Usage Examples:**
225
226
```javascript
227
var markdown = require("markdown").markdown;
228
229
// Create basic block
230
var block = markdown.mk_block("# Header", "\n\n");
231
console.log(block.toString()); // "# Header"
232
console.log(block.trailing); // "\n\n"
233
234
// Create block with line number
235
var block = markdown.mk_block("Paragraph text", "\n\n", 5);
236
console.log(block.lineNumber); // 5
237
238
// Used internally by block processing
239
var md = new markdown.Markdown();
240
var blocks = md.split_blocks("# Header\n\nParagraph");
241
// Each block is created with mk_block internally
242
```
243
244
**Note:** This is primarily an internal utility function used by the parser, but it's part of the public API and can be useful for custom dialect development.
245
246
## Dialect Helper Functions
247
248
### inline_until_char Function
249
250
Process inline content until a specific character is encountered, used internally by dialect processors.
251
252
```javascript { .api }
253
/**
254
* Process inline content until specific character
255
* @param {string} text - Text to process for inline elements
256
* @param {string} want - Character to stop processing at
257
* @returns {Array|null} [consumed_length, nodes_array] or null if character not found
258
*/
259
function Markdown.DialectHelpers.inline_until_char(text, want);
260
```
261
262
**Usage Examples:**
263
264
```javascript
265
var markdown = require("markdown").markdown;
266
267
// Process inline content until closing bracket
268
var result = markdown.DialectHelpers.inline_until_char("text with **bold**]", "]");
269
if (result) {
270
console.log("Consumed characters:", result[0]); // Number of characters processed
271
console.log("Processed nodes:", result[1]); // Array of inline JsonML nodes
272
// result[1] might be: ["text with ", ["strong", {}, "bold"]]
273
}
274
275
// Used internally in custom dialect development
276
var customDialect = {
277
inline: {
278
"[": function(text) {
279
var content = markdown.DialectHelpers.inline_until_char(text.substr(1), "]");
280
if (content) {
281
return [
282
content[0] + 2, // +1 for opening [, +1 for closing ]
283
["custom_element", {}, content[1]]
284
];
285
}
286
return [1, "["];
287
}
288
}
289
};
290
```
291
292
**Note:** This function is primarily used internally by link and image processing, but is exposed as part of the public API for custom dialect development.