tabnas_markdown/html.rs
1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! HTML renderer for the finished CommonMark tree. Port of `ts/src/html.ts`
4//! and `go/html.go`; keep the three in step.
5//!
6//! The conformance suite compares this output to the spec's expected HTML
7//! byte for byte, so newline placement is a correctness contract here, not
8//! a formatting preference. The discipline that makes it come out right is
9//! the reference renderer's:
10//!
11//! - every block writes `cr()` before its opening tag and after its closing
12//! tag, and `cr()` is a no-op when the buffer is already at the start of
13//! a line;
14//! - no block ever emits a newline on behalf of a neighbour or a child.
15//!
16//! Because a block only ever asks for "be at line start", nested blocks
17//! compose without doubling up: `<li>` deliberately does *not* end a line,
18//! and the newline in `<li>\n<p>...` is the paragraph's own leading `cr()`.
19//! A tight item, whose paragraph is skipped entirely, therefore renders as
20//! `<li>text</li>` with no interior newlines at all.
21//!
22//! The renderer reads only the finished tree, never `string_content`,
23//! which the inline phase has already consumed.
24
25use crate::common::{escape_xml, js_space_index, normalize_uri};
26use crate::node::{ListType, NodeId, NodeType, TableAlign, Tree};
27use crate::options::Options;
28
29/// An HTML attribute as name and already-escaped value.
30struct Attr<'a>(&'a str, String);
31
32/// The output buffer and the one bit of state `cr` needs.
33struct Renderer {
34 buf: String,
35 /// Exactly "the buffer is empty or ends with a newline", maintained by
36 /// `lit` and `tag` rather than re-read from the buffer. An empty buffer
37 /// counts as at-line-start, so a leading `cr()` (every top-level block
38 /// opens with one) writes nothing.
39 at_line_start: bool,
40}
41
42impl Renderer {
43 fn lit(&mut self, s: &str) {
44 // An empty write must not claim the line is dirty, or the next
45 // `cr()` would insert a spurious newline.
46 if s.is_empty() {
47 return;
48 }
49 self.buf.push_str(s);
50 self.at_line_start = s.ends_with('\n');
51 }
52
53 /// Append a newline only if the buffer does not already end with one.
54 fn cr(&mut self) {
55 if !self.at_line_start {
56 self.lit("\n");
57 }
58 }
59
60 /// Write an opening, closing or self-closing tag. A tag always ends
61 /// with `>`, so the buffer is never at a line start after one.
62 fn tag(&mut self, name: &str, attrs: &[Attr<'_>], self_closing: bool) {
63 self.buf.push('<');
64 self.buf.push_str(name);
65 for Attr(attr_name, value) in attrs {
66 self.buf.push(' ');
67 self.buf.push_str(attr_name);
68 self.buf.push_str("=\"");
69 self.buf.push_str(value);
70 self.buf.push('"');
71 }
72 if self_closing {
73 self.buf.push_str(" /");
74 }
75 self.buf.push('>');
76 self.at_line_start = false;
77 }
78}
79
80// --- GFM disallowed raw HTML (tagfilter) ------------------------------------
81
82/// GFM's tagfilter set. These nine tags change how the *rest* of a document
83/// is interpreted (everything after `<xmp>` or `<plaintext>` stops being
84/// markup at all), so GFM neutralises them by rewriting the leading `<` as
85/// `<`, opening and closing, in any case. Every other tag still passes
86/// through verbatim, as CommonMark requires.
87///
88/// This is purely a rendering concern: nothing rewrites the node, so the
89/// literal in the tree and the `value` in the AST stay exactly as written.
90///
91/// No name is a prefix of another, so the order here is immaterial.
92pub const DISALLOWED_TAGS: [&str; 9] = [
93 "title",
94 "textarea",
95 "style",
96 "xmp",
97 "iframe",
98 "noembed",
99 "noframes",
100 "script",
101 "plaintext",
102];
103
104/// The TypeScript's lookahead, `(?=[\t\n\f\r />]|$)`: the tag name must be
105/// followed by whitespace, `/`, `>` or the end of the text, so
106/// `<scriptlet>` and `<titles>` are untouched.
107fn is_tag_name_end(c: u8) -> bool {
108 matches!(c, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' | b'/' | b'>')
109}
110
111/// The byte length of the disallowed-tag match starting at `s[i]` (which
112/// must be `<`): the `<`, an optional `/` and the tag name, exactly what
113/// the TypeScript's regex captures. `None` for no match.
114///
115/// Case folding is ASCII-only, deliberately. The TypeScript applies the `i`
116/// flag without `u`, which never folds a non-ASCII code point onto an
117/// ASCII one.
118fn disallowed_tag_len(s: &[u8], i: usize) -> Option<usize> {
119 let mut j = i + 1;
120 if j < s.len() && s[j] == b'/' {
121 j += 1;
122 }
123
124 for name in DISALLOWED_TAGS {
125 let name = name.as_bytes();
126 if s.len() - j < name.len() {
127 continue;
128 }
129 if !s[j..j + name.len()]
130 .iter()
131 .zip(name)
132 .all(|(c, n)| c.to_ascii_lowercase() == *n)
133 {
134 continue;
135 }
136 let end = j + name.len();
137 if end == s.len() || is_tag_name_end(s[end]) {
138 return Some(end - i);
139 }
140 }
141
142 None
143}
144
145fn filter_disallowed_tags(s: &str) -> String {
146 // Cheap reject: the vast majority of raw HTML holds none of these.
147 if !s.contains('<') {
148 return s.to_string();
149 }
150
151 let bytes = s.as_bytes();
152 let mut out = String::new();
153 let mut matched = false;
154 let mut last = 0;
155
156 let mut i = 0;
157 while i < bytes.len() {
158 if bytes[i] != b'<' {
159 i += 1;
160 continue;
161 }
162 let Some(n) = disallowed_tag_len(bytes, i) else {
163 i += 1;
164 continue;
165 };
166 if !matched {
167 matched = true;
168 out.reserve(s.len() + 8);
169 }
170 out.push_str(&s[last..i]);
171 // Only the leading `<` changes; the tag name is copied as written.
172 out.push_str("<");
173 out.push_str(&s[i + 1..i + n]);
174 last = i + n;
175 i = last;
176 }
177
178 if !matched {
179 return s.to_string();
180 }
181 out.push_str(&s[last..]);
182 out
183}
184
185/// Raw HTML as written, minus the tags GFM's tagfilter neutralises.
186fn raw_html(literal: &str, gfm: bool) -> String {
187 if gfm {
188 filter_disallowed_tags(literal)
189 } else {
190 literal.to_string()
191 }
192}
193
194/// Everything before the first whitespace run, which is what the
195/// TypeScript gets from `info.split(/\s+/)[0]`: an info string that
196/// *starts* with whitespace yields `""`, which suppresses the class
197/// attribute entirely. The block phase trims the info string, but an entity
198/// such as ` ` unescapes to a space afterwards, so leading whitespace
199/// is reachable.
200fn first_info_word(info: &str) -> &str {
201 match js_space_index(info) {
202 Some((sp, _)) => &info[..sp],
203 None => info,
204 }
205}
206
207/// Render `tree` (one that has been through both parse phases) as HTML.
208///
209/// Two options reach the renderer. `breaks` turns soft line breaks into
210/// hard ones. `gfm` selects one thing only, the disallowed-raw-HTML
211/// filter, which the extension defines at render time rather than at
212/// parse time. Everything else GFM adds is settled by then: by the time a
213/// `del` node or an item's checked state exists, the renderer just prints
214/// it.
215///
216/// `gfm` defaults to whatever the *document* was parsed with rather than to
217/// the package default, so [`render_html`] with `None` on a `gfm: false`
218/// parse renders plain CommonMark. Explicit options still win.
219pub fn render_html(tree: &Tree, options: Option<&Options>) -> String {
220 let root = tree.root();
221 let opts = Options {
222 gfm: options.map_or(tree.get(root).gfm, |o| o.gfm),
223 breaks: options.is_some_and(|o| o.breaks),
224 };
225 render_html_with(tree, opts)
226}
227
228/// Render with already-resolved options, the way the Go `RenderHTML`
229/// takes them.
230pub fn render_html_with(tree: &Tree, opts: Options) -> String {
231 // Section 6.9 soft line breaks: rendered as a newline, or as a hard
232 // break when the caller asks for `breaks`.
233 let softbreak = if opts.breaks { "<br />\n" } else { "\n" };
234
235 let mut r = Renderer {
236 buf: String::new(),
237 at_line_start: true,
238 };
239
240 // GFM tables carry their alignment once, on the table, but it is
241 // rendered per cell. Tracking the current table's alignments and the
242 // current row's column as the walk goes is what keeps that an O(1)
243 // lookup instead of counting a cell's previous siblings; a table can
244 // never contain another table (its cells hold inlines only), so one of
245 // each is enough.
246 let mut table_align: &[TableAlign] = &[];
247 let mut cell_index = 0usize;
248
249 let mut walker = tree.walker(tree.root());
250
251 while let Some(event) = walker.next(tree) {
252 let id = event.node;
253 let node = tree.get(id);
254 let entering = event.entering;
255
256 match node.node_type {
257 // The document wrapper renders nothing of its own.
258 NodeType::Document => {}
259
260 NodeType::Paragraph => {
261 // Section 5.3: "if a list is tight, we remove the <p> tags
262 // from the item contents". The paragraph's grandparent is
263 // the list; a paragraph whose grandparent is a list is
264 // necessarily an item's direct child.
265 let grandparent = node.parent.and_then(|p| tree.get(p).parent);
266 let tight = grandparent.is_some_and(|g| {
267 let g = tree.get(g);
268 g.node_type == NodeType::List && g.list_data.as_ref().is_some_and(|d| d.tight)
269 });
270
271 if entering {
272 if !tight {
273 r.cr();
274 r.tag("p", &[], false);
275 }
276 // GFM task list item. The block phase consumed the
277 // `[x]` marker and left the state on the item, so the
278 // checkbox is written here, at the head of the item's
279 // first paragraph: directly after `<li>` when the list
280 // is tight, and inside the `<p>` when it is loose. The
281 // trailing space is the separator the extension's own
282 // output shows between the checkbox and the item text.
283 if let Some(item) = node.parent.map(|p| tree.get(p)) {
284 if item.node_type == NodeType::Item && item.first_child == Some(id) {
285 if let Some(checked) = item.checked {
286 let mut attrs = Vec::new();
287 if checked {
288 attrs.push(Attr("checked", String::new()));
289 }
290 attrs.push(Attr("disabled", String::new()));
291 attrs.push(Attr("type", "checkbox".to_string()));
292 r.tag("input", &attrs, false);
293 r.lit(" ");
294 }
295 }
296 }
297 } else if !tight {
298 r.tag("/p", &[], false);
299 r.cr();
300 }
301 }
302
303 NodeType::Heading => {
304 let name = format!("h{}", node.level);
305 if entering {
306 r.cr();
307 r.tag(&name, &[], false);
308 } else {
309 r.tag(&format!("/{name}"), &[], false);
310 r.cr();
311 }
312 }
313
314 NodeType::ThematicBreak => {
315 r.cr();
316 r.tag("hr", &[], true);
317 r.cr();
318 }
319
320 NodeType::BlockQuote => {
321 r.cr();
322 r.tag(
323 if entering {
324 "blockquote"
325 } else {
326 "/blockquote"
327 },
328 &[],
329 false,
330 );
331 r.cr();
332 }
333
334 NodeType::List => {
335 let data = node.list_data.as_ref();
336 let ordered = data.is_some_and(|d| d.list_type == ListType::Ordered);
337 let name = if ordered { "ol" } else { "ul" };
338 if entering {
339 let mut attrs = Vec::new();
340 // Section 5.3: the start number is only rendered when it
341 // is not 1, and `start="0"` is meaningful, so this is an
342 // inequality, not a truthiness test.
343 if let Some(d) = data {
344 if ordered && d.start != 1 {
345 attrs.push(Attr("start", d.start.to_string()));
346 }
347 }
348 r.cr();
349 r.tag(name, &attrs, false);
350 } else {
351 r.cr();
352 r.tag(&format!("/{name}"), &[], false);
353 }
354 r.cr();
355 }
356
357 NodeType::Item => {
358 // No `cr()` after `<li>`: a tight item renders
359 // `<li>text</li>`, and a loose one gets its newline from the
360 // leading `cr()` of the first child block.
361 if entering {
362 r.tag("li", &[], false);
363 } else {
364 r.tag("/li", &[], false);
365 r.cr();
366 }
367 }
368
369 NodeType::CodeBlock => {
370 let mut attrs = Vec::new();
371 // Section 4.5: "the first word of the info string is
372 // typically used to specify the language". The info string
373 // arrives from the block phase already backslash-unescaped
374 // and entity-decoded; only the escaping for attribute
375 // context is left to do here.
376 let info = node.info.as_deref().unwrap_or("");
377 let first_word = if info.is_empty() {
378 ""
379 } else {
380 first_info_word(info)
381 };
382 if !first_word.is_empty() {
383 attrs.push(Attr(
384 "class",
385 format!("language-{}", escape_xml(first_word)),
386 ));
387 }
388 r.cr();
389 r.tag("pre", &[], false);
390 r.tag("code", &attrs, false);
391 // The block phase guarantees the literal already ends with
392 // a newline (or is empty, for an empty fenced block, which
393 // renders as `<pre><code></code></pre>`).
394 r.lit(&escape_xml(&node.literal));
395 r.tag("/code", &[], false);
396 r.tag("/pre", &[], false);
397 r.cr();
398 }
399
400 NodeType::HtmlBlock => {
401 // Section 4.6: raw HTML passes through verbatim, unescaped,
402 // except for the nine tags GFM's tagfilter neutralises.
403 r.cr();
404 r.lit(&raw_html(&node.literal, opts.gfm));
405 r.cr();
406 }
407
408 // --- GFM tables ---
409 //
410 // `<thead>` and `<tbody>` have no node of their own: the header
411 // row is the one row flagged as such, and the body is every row
412 // after it. That is also why `<tbody>` is written by the *first*
413 // body row rather than unconditionally: a table with no body
414 // rows must have no `<tbody>` at all.
415 NodeType::Table => {
416 if entering {
417 table_align = node.table_align.as_deref().unwrap_or(&[]);
418 r.cr();
419 r.tag("table", &[], false);
420 } else {
421 r.cr();
422 r.tag("/table", &[], false);
423 }
424 r.cr();
425 }
426
427 NodeType::TableRow => {
428 let header = node.is_header_row;
429 if entering {
430 if header {
431 r.cr();
432 r.tag("thead", &[], false);
433 } else if node.prev.is_none_or(|p| tree.get(p).is_header_row) {
434 r.cr();
435 r.tag("tbody", &[], false);
436 }
437 r.cr();
438 r.tag("tr", &[], false);
439 cell_index = 0;
440 } else {
441 r.cr();
442 r.tag("/tr", &[], false);
443 r.cr();
444 if header {
445 r.tag("/thead", &[], false);
446 } else if node.next.is_none() {
447 r.tag("/tbody", &[], false);
448 }
449 }
450 r.cr();
451 }
452
453 NodeType::TableCell => {
454 let name = if node.parent.is_some_and(|p| tree.get(p).is_header_row) {
455 "th"
456 } else {
457 "td"
458 };
459 if entering {
460 let mut attrs = Vec::new();
461 // Out of range and a column with no colon both mean no
462 // attribute at all.
463 if let Some(Some(align)) = table_align.get(cell_index) {
464 attrs.push(Attr("align", align.as_str().to_string()));
465 }
466 cell_index += 1;
467 r.tag(name, &attrs, false);
468 } else {
469 r.tag(&format!("/{name}"), &[], false);
470 r.cr();
471 }
472 }
473
474 NodeType::Text => r.lit(&escape_xml(&node.literal)),
475
476 NodeType::Softbreak => r.lit(softbreak),
477
478 NodeType::Linebreak => {
479 r.tag("br", &[], true);
480 r.cr();
481 }
482
483 NodeType::Code => {
484 r.tag("code", &[], false);
485 r.lit(&escape_xml(&node.literal));
486 r.tag("/code", &[], false);
487 }
488
489 NodeType::HtmlInline => r.lit(&raw_html(&node.literal, opts.gfm)),
490
491 NodeType::Emph => r.tag(if entering { "em" } else { "/em" }, &[], false),
492
493 NodeType::Strong => r.tag(if entering { "strong" } else { "/strong" }, &[], false),
494
495 NodeType::Del => r.tag(if entering { "del" } else { "/del" }, &[], false),
496
497 // Only a parse that keeps references makes these, and the tree
498 // a renderer is given comes from the parse that resolves them.
499 NodeType::LinkReference | NodeType::ImageReference => {}
500
501 NodeType::Link => {
502 if entering {
503 let mut attrs =
504 vec![Attr("href", escape_xml(&normalize_uri(&node.destination)))];
505 // An empty title is dropped: `[link](/url "")` renders as
506 // a bare `<a href="/url">`.
507 if let Some(title) = node.title.as_deref().filter(|t| !t.is_empty()) {
508 attrs.push(Attr("title", escape_xml(title)));
509 }
510 r.tag("a", &attrs, false);
511 } else {
512 r.tag("/a", &[], false);
513 }
514 }
515
516 NodeType::Image => {
517 if entering {
518 let mut attrs = vec![
519 Attr("src", escape_xml(&normalize_uri(&node.destination))),
520 Attr("alt", escape_xml(&alt_text(tree, id))),
521 ];
522 if let Some(title) = node.title.as_deref().filter(|t| !t.is_empty()) {
523 attrs.push(Attr("title", escape_xml(title)));
524 }
525 r.tag("img", &attrs, true);
526 // The children have been consumed into `alt`; jump the
527 // walk straight to this image's exit event so they are
528 // not also rendered as markup.
529 walker.resume_at(id, false);
530 }
531 }
532 }
533 }
534
535 r.buf
536}
537
538/// Section 6.4 images: "the image description gets represented as the alt
539/// attribute", as plain text. Descend the subtree keeping the text and
540/// code-span literals and dropping the markup wrappers, so
541/// `` yields `alt="foo bar"` and a nested link
542/// contributes only its text.
543///
544/// Raw inline HTML and line breaks inside a description are not exercised
545/// by the spec suite and the two reference implementations disagree: cmark
546/// escapes the raw HTML into the attribute and turns breaks into spaces,
547/// commonmark.js emits the HTML verbatim (producing a malformed attribute)
548/// and turns breaks into newlines. The literal is kept, escaped, since the
549/// result is attribute-context text, and breaks follow commonmark.js.
550fn alt_text(tree: &Tree, image: NodeId) -> String {
551 let mut alt = String::new();
552
553 let mut walker = tree.walker(image);
554 walker.next(tree); // discard the image's own entering event
555
556 while let Some(event) = walker.next(tree) {
557 if event.node == image {
558 break;
559 }
560 if !event.entering {
561 continue;
562 }
563 let node = tree.get(event.node);
564 match node.node_type {
565 NodeType::Text | NodeType::Code | NodeType::HtmlInline => alt.push_str(&node.literal),
566 NodeType::Softbreak | NodeType::Linebreak => alt.push('\n'),
567 // Containers (emph, strong, link, a nested image) contribute
568 // nothing themselves; the walk still descends into their
569 // children.
570 _ => {}
571 }
572 }
573
574 alt
575}