html-to-markdown-rs 3.19.1

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Handlers for HTML5 figure elements.
//!
//! Processes figure-related semantic elements:
//! - `<figure>` - Self-contained illustration, diagram, photo, code listing, etc.
//! - `<figcaption>` - Caption or legend for a figure
//!
//! Figure elements group an image (or other media) with its associated caption.
//! The Markdown output preserves this relationship through content organization.

#[cfg(feature = "visitor")]
use std::borrow::Cow;

/// Handles the `<figure>` element.
///
/// A figure element contains content (typically images) and optionally a figcaption.
/// The handler collects all content and cleans up extra line breaks.
///
/// # Behavior
///
/// - **Inline mode**: Children are processed inline without block spacing
/// - **Block mode**: Content is collected, line breaks normalized, and wrapped with blank lines
/// - **Image normalization**: Removes extra spaces before `![` to improve Markdown formatting
///
/// # Implementation Details
///
/// The handler performs the following on the collected content:
/// 1. Normalizes newline + image sequences: `\n![` → `![`
/// 2. Normalizes space + image sequences: ` ![` → `![`
/// 3. Trims the final content and wraps it with blank lines
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_figure(
    _tag_name: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) {
    // ~keep In an inline context the dispatcher gives the children to the walk and this handler
    // ~keep does not run.
    if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
        #[cfg(feature = "visitor")]
        if visit_figure_start(tag, node_handle, parser, output, handler) {
            return;
        }

        let figure_start = output.len();

        let mut figure_content = collect_figure_content(tag, parser, handler);

        // ~keep A trailing <br> run with no following sibling has no next dispatch to catch
        // ~keep it in `walk_node`'s pre-block-dispatch strip, since the figure's content is
        // ~keep simply finished here — so this closes its own trailing run the same way
        // ~keep `paragraph.rs` closes its own (issue #464 follow-up). `trim_matches` below
        // ~keep does not treat `\` as trimmable, so it cannot clean this up on its own.
        crate::converter::main_helpers::strip_trailing_backslash_breaks_from_fresh_buffer(
            &mut figure_content,
            handler.options.newline_style,
        );

        figure_content = figure_content.replace("\n![", "![");
        figure_content = figure_content.replace(" ![", "![");

        let content = figure_content
            .trim_start_matches('\n')
            .trim_end_matches(['\n', ' ', '\t']);
        // ~keep Keep the code renderer's four-space prefix, but strip ordinary figure padding (#819).
        let trimmed = if handler.options.code_block_style == crate::options::CodeBlockStyle::Indented
            && content.starts_with("    ")
        {
            content
        } else {
            content.trim_start_matches([' ', '\t'])
        };
        if !trimmed.is_empty() {
            crate::converter::block::div::push_block(output, handler.options, handler.ctx, trimmed);
        }

        #[cfg(feature = "visitor")]
        visit_figure_end(tag, node_handle, parser, output, figure_start, handler);
    }
}

fn collect_figure_content(tag: &tl::HTMLTag<'_>, parser: &tl::Parser, handler: super::HandlerContext<'_>) -> String {
    let mut content = String::new();
    super::walk_tag_children(tag, parser, &mut content, handler);
    content
}

#[cfg(feature = "visitor")]
fn visit_figure_start(
    tag: &tl::HTMLTag<'_>,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) -> bool {
    use crate::visitor::{NodeContext, NodeType, VisitResult};

    let Some(visitor_handle) = handler.ctx.visitor.as_ref() else {
        return false;
    };
    let node_id = node_handle.get_inner();
    let parent_tag = handler.dom_ctx.parent_tag_name(node_id, parser);
    let node_ctx = NodeContext::with_lazy_attributes(
        NodeType::Figure,
        Cow::Borrowed("figure"),
        tag,
        handler.depth,
        handler.dom_ctx.get_sibling_index(node_id).unwrap_or(0),
        parent_tag.map(Cow::Borrowed),
        false,
    );
    let visit_result = visitor_handle
        .lock()
        .expect("visitor mutex poisoned")
        .visit_figure_start(&node_ctx);
    match visit_result {
        VisitResult::Continue => false,
        VisitResult::Skip => true,
        VisitResult::Custom(custom) => {
            render_custom_figure(&node_ctx, node_handle, parser, output, &custom, handler.ctx);
            true
        }
        VisitResult::PreserveHtml => {
            output.push_str(&crate::converter::utility::serialization::serialize_node(
                node_handle,
                parser,
            ));
            true
        }
        VisitResult::Error(error) => {
            record_visitor_error(handler.ctx, error);
            true
        }
    }
}

#[cfg(feature = "visitor")]
fn render_custom_figure(
    node_context: &crate::visitor::NodeContext<'_>,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    custom: &str,
    ctx: &super::Context,
) {
    use crate::visitor::VisitResult;

    let start = output.len();
    if !output.is_empty() && !output.ends_with("\n\n") {
        output.push_str("\n\n");
    }
    output.push_str(custom);
    let safe_start = crate::converter::utility::content::floor_char_boundary(output, start.min(output.len()));
    let result = ctx
        .visitor
        .as_ref()
        .expect("visitor available")
        .lock()
        .expect("visitor mutex poisoned")
        .visit_figure_end(node_context, &output[safe_start..]);
    match result {
        VisitResult::Continue => ensure_figure_trailing_blank_line(output),
        VisitResult::Custom(replacement) => replace_figure_output(output, safe_start, &replacement),
        VisitResult::Skip => output.truncate(safe_start),
        VisitResult::PreserveHtml => replace_figure_output(
            output,
            safe_start,
            &crate::converter::utility::serialization::serialize_node(node_handle, parser),
        ),
        VisitResult::Error(error) => record_visitor_error(ctx, error),
    }
}

#[cfg(feature = "visitor")]
fn visit_figure_end(
    tag: &tl::HTMLTag<'_>,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    figure_start: usize,
    handler: super::HandlerContext<'_>,
) {
    use crate::visitor::{NodeContext, NodeType, VisitResult};

    let Some(visitor_handle) = handler.ctx.visitor.as_ref() else {
        return;
    };
    let node_id = node_handle.get_inner();
    let parent_tag = handler.dom_ctx.parent_tag_name(node_id, parser);
    let node_ctx = NodeContext::with_lazy_attributes(
        NodeType::Figure,
        Cow::Borrowed("figure"),
        tag,
        handler.depth,
        handler.dom_ctx.get_sibling_index(node_id).unwrap_or(0),
        parent_tag.map(Cow::Borrowed),
        false,
    );
    let safe_start = crate::converter::utility::content::floor_char_boundary(output, figure_start.min(output.len()));
    let result = visitor_handle
        .lock()
        .expect("visitor mutex poisoned")
        .visit_figure_end(&node_ctx, &output[safe_start..]);
    match result {
        VisitResult::Continue => {}
        VisitResult::Skip => output.truncate(safe_start),
        VisitResult::Custom(custom) => replace_figure_output(output, safe_start, &custom),
        VisitResult::PreserveHtml => replace_figure_output(
            output,
            safe_start,
            &crate::converter::utility::serialization::serialize_node(node_handle, parser),
        ),
        VisitResult::Error(error) => record_visitor_error(handler.ctx, error),
    }
}

#[cfg(feature = "visitor")]
fn ensure_figure_trailing_blank_line(output: &mut String) {
    if !output.ends_with('\n') {
        output.push_str("\n\n");
    } else if !output.ends_with("\n\n") {
        output.push('\n');
    }
}

#[cfg(feature = "visitor")]
fn replace_figure_output(output: &mut String, start: usize, replacement: &str) {
    output.truncate(start);
    output.push_str(replacement);
}

#[cfg(feature = "visitor")]
fn record_visitor_error(ctx: &super::Context, error: String) {
    if ctx.visitor_error.borrow().is_none() {
        *ctx.visitor_error.borrow_mut() = Some(error);
    }
}

/// Handles the `<figcaption>` element.
///
/// A figcaption element contains text that describes or supplements the figure.
/// It is rendered as emphasized (italic) text to distinguish it from regular content.
///
/// # Behavior
///
/// - Content is collected and trimmed
/// - Non-empty content is wrapped in `*text*` (emphasis) markers
/// - Proper spacing is maintained around the caption
///
/// # Implementation Details
///
/// The handler:
/// 1. Collects and processes all children
/// 2. Checks for existing output and adds spacing as needed
/// 3. Wraps content in emphasis markers: `*caption*`
/// 4. Ensures proper blank-line spacing after the caption
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_figcaption(
    _tag_name: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) {
    let mut children = Vec::new();
    let Some(opened) = open_figcaption(node_handle, parser, handler, &mut children) else {
        return;
    };
    let mut text = String::new();
    let caption_ctx = opened
        .scope
        .as_deref()
        .unwrap_or(handler.ctx)
        .with_inline_break_owner(&text);
    for child in &children {
        super::walk_node(
            child,
            parser,
            &mut text,
            super::HandlerContext::new(handler.options, &caption_ctx, handler.depth + 1, handler.dom_ctx),
        );
    }
    close_figcaption(&text, node_handle, parser, output, handler);
}

pub fn open_figcaption(
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    handler: super::HandlerContext<'_>,
    children: &mut Vec<tl::NodeHandle>,
) -> Option<crate::converter::walk::Open> {
    let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
        return None;
    };
    children.extend(tag.children().top().iter().copied());
    Some(crate::converter::walk::Open {
        scope: Some(std::rc::Rc::new(super::Context {
            text_in_markers: true,
            ..handler.ctx.clone()
        })),
        close: crate::converter::walk::Close::Capture(crate::converter::walk::CaptureEnd::Figcaption),
    })
}

pub fn close_figcaption(
    content: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) {
    let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
        return;
    };
    #[cfg(not(feature = "visitor"))]
    let _ = tag;
    let mut text = content.to_owned();
    crate::converter::main_helpers::strip_trailing_backslash_breaks_from_fresh_buffer(
        &mut text,
        handler.options.newline_style,
    );
    let text = text.trim();
    if text.is_empty() {
        return;
    }
    #[cfg(feature = "visitor")]
    if visit_figcaption(tag, node_handle, parser, output, text, handler) {
        return;
    }
    separate_caption(output);
    output.push(handler.options.strong_em_symbol);
    output.push_str(text);
    output.push(handler.options.strong_em_symbol);
    output.push_str("\n\n");
}

#[cfg(feature = "visitor")]
fn visit_figcaption(
    tag: &tl::HTMLTag<'_>,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    text: &str,
    handler: super::HandlerContext<'_>,
) -> bool {
    use crate::visitor::{NodeContext, NodeType, VisitResult};

    let Some(visitor_handle) = handler.ctx.visitor.as_ref() else {
        return false;
    };
    let node_id = node_handle.get_inner();
    let parent_tag = handler.dom_ctx.parent_tag_name(node_id, parser);
    let node_ctx = NodeContext::with_lazy_attributes(
        NodeType::Figcaption,
        Cow::Borrowed("figcaption"),
        tag,
        handler.depth,
        handler.dom_ctx.get_sibling_index(node_id).unwrap_or(0),
        parent_tag.map(Cow::Borrowed),
        false,
    );
    let visit_result = visitor_handle
        .lock()
        .expect("visitor mutex poisoned")
        .visit_figcaption(&node_ctx, text);
    match visit_result {
        VisitResult::Continue => false,
        VisitResult::Skip => true,
        VisitResult::Custom(custom) => {
            separate_caption(output);
            output.push_str(&custom);
            if !custom.ends_with('\n') {
                output.push_str("\n\n");
            }
            true
        }
        VisitResult::PreserveHtml => {
            output.push_str(&crate::converter::utility::serialization::serialize_node(
                node_handle,
                parser,
            ));
            true
        }
        VisitResult::Error(error) => {
            record_visitor_error(handler.ctx, error);
            true
        }
    }
}

fn separate_caption(output: &mut String) {
    if output.is_empty() {
        return;
    }
    if output.ends_with("```\n") {
        output.push('\n');
        return;
    }
    while output.ends_with(' ') || output.ends_with('\t') {
        output.pop();
    }
    if output.ends_with('\n') && !output.ends_with("\n\n") {
        output.push('\n');
    } else if !output.ends_with('\n') {
        output.push_str("\n\n");
    }
}

/// Dispatcher for figure-related elements.
///
/// Routes `<figure>` and `<figcaption>` elements to their respective handlers.
pub fn handle(
    tag_name: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) {
    match tag_name {
        "figure" => handle_figure(tag_name, node_handle, parser, output, handler),
        "figcaption" => handle_figcaption(tag_name, node_handle, parser, output, handler),
        _ => {}
    }
}

pub fn open_figure(
    site: crate::converter::inline::HandlerContext<'_>,
    children: &mut Vec<tl::NodeHandle>,
) -> Option<crate::converter::walk::Open> {
    let node_handle = site.node_handle;
    let parser = site.parser;
    let output = site.output;
    #[cfg(feature = "visitor")]
    let handler = super::HandlerContext::new(site.options, site.context, site.depth, site.dom_context);
    let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
        return None;
    };
    #[cfg(feature = "visitor")]
    if visit_figure_start(tag, node_handle, parser, output, handler) {
        return None;
    }
    children.extend(tag.children().top().iter().copied());
    Some(crate::converter::walk::Open {
        scope: None,
        close: crate::converter::walk::Close::Capture(crate::converter::walk::CaptureEnd::Figure(output.len())),
    })
}

pub fn close_figure(
    figure_start: usize,
    content: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: super::HandlerContext<'_>,
) {
    let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
        return;
    };
    #[cfg(not(feature = "visitor"))]
    let _ = (tag, figure_start);
    let mut figure_content = content.to_owned();
    // ~keep A trailing <br> run with no following sibling has no next dispatch to catch
    // ~keep it in `walk_node`'s pre-block-dispatch strip, since the figure's content is
    // ~keep simply finished here — so this closes its own trailing run the same way
    // ~keep `paragraph.rs` closes its own (issue #464 follow-up). `trim_matches` below
    // ~keep does not treat `\` as trimmable, so it cannot clean this up on its own.
    crate::converter::main_helpers::strip_trailing_backslash_breaks_from_fresh_buffer(
        &mut figure_content,
        handler.options.newline_style,
    );

    figure_content = figure_content.replace("\n![", "![");
    figure_content = figure_content.replace(" ![", "![");

    let content = figure_content
        .trim_start_matches('\n')
        .trim_end_matches(['\n', ' ', '\t']);
    // ~keep Keep the code renderer's four-space prefix, but strip ordinary figure padding (#819).
    let trimmed = if handler.options.code_block_style == crate::options::CodeBlockStyle::Indented
        && content.starts_with("    ")
    {
        content
    } else {
        content.trim_start_matches([' ', '\t'])
    };
    if !trimmed.is_empty() {
        crate::converter::block::div::push_block(output, handler.options, handler.ctx, trimmed);
    }

    #[cfg(feature = "visitor")]
    visit_figure_end(tag, node_handle, parser, output, figure_start, handler);
}

#[cfg(test)]
mod tests {
    #[test]
    fn figure_caption_separated_from_image() {
        let html = r#"<figure><img src="photo.jpg" alt="Photo"><figcaption>A nice photo</figcaption></figure>"#;
        let result = crate::convert(html, None).unwrap();
        let content = result.content.unwrap_or_default();
        assert!(
            content.contains("![Photo](photo.jpg)"),
            "image should be present: {content}"
        );
        assert!(content.contains("A nice photo"), "caption should be present: {content}");
        let lines: Vec<&str> = content.lines().filter(|l| !l.trim().is_empty()).collect();
        let img_line = lines.iter().position(|l| l.contains("![")).unwrap_or(999);
        let cap_line = lines.iter().position(|l| l.contains("A nice photo")).unwrap_or(999);
        assert!(
            cap_line > img_line,
            "caption should be on a separate line after image, lines: {lines:?}"
        );
    }
}