html-to-markdown-rs 3.18.0

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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Shared emission for inline elements that wrap their trimmed content in a delimiter pair.
//!
//! Every such element has the same two edge cases, and both were originally fixed for
//! `<strong>`/`<em>` alone (issues #483 and #481) while the other handlers kept their own
//! byte-for-byte copy of the naive emission and kept the bugs:
//!
//! - A delimiter built from a repeated character (`*`, `**`, `~~`, `==`) that opens
//!   immediately after the matching close of a preceding sibling forms ONE longer
//!   delimiter run on reparse, not two spans.
//! - A body that is non-empty but entirely whitespace stands for a word separator, and a
//!   handler that only tests `!trimmed.is_empty()` drops it, joining the words either side.

use tl::{NodeHandle, Parser};

type DomContext = crate::converter::DomContext;
type Context = crate::converter::Context;
type ConversionOptions = crate::options::ConversionOptions;

/// Where a wrapper is being emitted: its DOM node, the parser and DOM lookup context, and the
/// conversion `Context` of the buffer it writes into.
///
/// ~keep Bundled because every emitter passes exactly these four together; `ctx` is needed for
/// ~keep `block_output_ptr`, which tells a block's own buffer apart from an enclosing wrapper's
/// ~keep scratch buffer (issue #504).
#[derive(Clone, Copy)]
pub struct InlineSite<'p> {
    pub node_handle: &'p NodeHandle,
    pub parser: &'p Parser<'p>,
    pub dom_ctx: &'p DomContext,
    pub ctx: &'p Context,
    pub options: &'p ConversionOptions,
}

/// Tag names that render with the single `strong_em_symbol` italic delimiter.
///
/// `<var>` and `<dfn>` wrap their content in exactly the same one-character pair `<em>`/`<i>`
/// do, so a `<var>` opening right after an `<em>` closes forms one longer delimiter run just
/// as two `<em>`s would -- the corruption issue #483 describes does not care which tag
/// emitted each half of the run. ~keep
pub const EMPHASIS_SIBLING_TAGS: [&str; 4] = ["em", "i", "var", "dfn"];

/// Tag names that render with the doubled `strong_em_symbol` bold delimiter.
pub const STRONG_SIBLING_TAGS: [&str; 2] = ["strong", "b"];

/// The delimiter pair an inline element wraps its trimmed content in, and what it may merge
/// that pair with.
///
/// `open`/`close` are the exact strings emitted around the content. Pass `("", "")` for an
/// element that renders with no marker of its own, such as a `<strong>` nested inside another
/// `<strong>`.
///
/// `merge_symbol` is the single character `open` is built from, used to detect and merge a
/// `CommonMark` adjacency with the immediately preceding sibling's close marker (issue #483,
/// see [`merge_adjacent_emphasis`](crate::converter::merge_adjacent_emphasis)) instead of
/// opening a second, textually-adjacent delimiter run. Use `None` for a delimiter that cannot
/// form a run at all -- Djot's `{-`/`-}` and `{+`/`+}` pairs, `<mark>`'s HTML style, or an
/// arbitrary caller-configured `sub_symbol`. A `Some` whose character does not make up the
/// whole of `open` is treated the same way, so a caller cannot accidentally pop bytes that are
/// not a delimiter run.
///
/// `sibling_tag_names` lists the HTML tag names (e.g. `["strong", "b"]`) that make this
/// element's immediately preceding DOM sibling a genuine candidate for that merge. Buffer
/// content alone is ambiguous: ordinary prose can coincidentally end in a literal `*`/`**`
/// (CommonMark spec example 442, `<p>*<em>foo</em></p>` -> `**foo*`, NOT a merge into `*foo*`)
/// that is indistinguishable, byte-for-byte, from a just-emitted close marker. Requiring the
/// DOM to actually show a matching sibling element resolves the ambiguity in favor of "no
/// merge" whenever the preceding content is plain text. ~keep
#[derive(Clone, Copy)]
pub struct InlineDelimiters<'a> {
    pub open: &'a str,
    pub close: &'a str,
    pub merge_symbol: Option<char>,
    pub sibling_tag_names: &'a [&'a str],
}

/// ~keep Wrap every non-empty Markdown block in its own delimiter pair so a blank line cannot
/// split one inline delimiter run into literal markers (issue #724).
pub fn wrap_block_runs(content: &str, open: &str, close: &str) -> String {
    let (prefix, suffix, trimmed) = crate::converter::chomp_inline(content);
    let mut wrapped = String::with_capacity(content.len() + open.len() + close.len());
    wrapped.push_str(prefix);

    for (index, block) in trimmed.split("\n\n").enumerate() {
        if index > 0 {
            wrapped.push_str("\n\n");
        }
        if block.trim_matches([' ', '\t']).is_empty() {
            wrapped.push_str(block);
        } else {
            let body_start = markdown_block_prefix_len(block);
            let body_end = block.trim_end_matches([' ', '\t']).len();
            if body_end <= body_start {
                wrapped.push_str(block);
                continue;
            }
            wrapped.push_str(&block[..body_start]);
            wrapped.push_str(open);
            wrapped.push_str(&block[body_start..body_end]);
            wrapped.push_str(close);
            wrapped.push_str(&block[body_end..]);
        }
    }

    wrapped.push_str(suffix);
    wrapped
}

/// ~keep General inline handlers split only plain paragraph-like runs. Structured Markdown
/// remains on its established path because moving a delimiter across nested list/quote syntax
/// changes the block tree; legend opts into that explicitly for its pinned list behavior.
pub fn block_runs_are_plain(content: &str) -> bool {
    block_runs_are_single_line(content)
        && content.split("\n\n").all(|block| {
            let indentation = block.bytes().take_while(|byte| matches!(byte, b' ' | b'\t')).count();
            markdown_block_prefix_len(block) == indentation
        })
}

/// ~keep Multi-line structured blocks need tree-aware delimiter placement; the shared wrapper
/// safely handles single-line blocks while preserving their Markdown prefixes.
pub fn block_runs_are_single_line(content: &str) -> bool {
    content.split("\n\n").all(|block| !block.contains('\n'))
}

/// ~keep A block quote that is a task item's first content keeps its opener outside inline
/// delimiters, so the checkbox line cannot turn the opener into literal text (#643). Other
/// block-like children retain their established inline-wrapper behavior.
pub fn emit_first_block_wrapped(
    output: &mut String,
    content: &str,
    open: &str,
    close: &str,
    ctx: &Context,
    parser: &Parser<'_>,
) -> bool {
    if open.is_empty()
        || !ctx
            .first_writer
            .as_ref()
            .is_some_and(|first_writer| first_writer.starts_with_blockquote(parser))
        || !block_runs_are_single_line(content.trim_end_matches('\n'))
        || !crate::converter::utility::escaping::opens_block(content.trim_start())
    {
        return false;
    }

    output.push_str(&wrap_block_runs(content, open, close));
    true
}

// ~keep Markdown block syntax stays outside the inline delimiters: `* **x**` remains a list,
// ~keep whereas `*** x**` is an ambiguous delimiter run rather than a bold list item.
fn markdown_block_prefix_len(block: &str) -> usize {
    let bytes = block.as_bytes();
    let mut position = bytes.iter().take_while(|byte| matches!(byte, b' ' | b'\t')).count();

    while bytes.get(position..position + 2) == Some(b"> ") {
        position += 2;
    }

    if matches!(bytes.get(position), Some(b'-' | b'+' | b'*')) && matches!(bytes.get(position + 1), Some(b' ' | b'\t'))
    {
        return position + 2;
    }

    let digits_start = position;
    while bytes.get(position).is_some_and(u8::is_ascii_digit) {
        position += 1;
    }
    if position > digits_start
        && matches!(bytes.get(position), Some(b'.' | b')'))
        && matches!(bytes.get(position + 1), Some(b' ' | b'\t'))
    {
        return position + 2;
    }

    let heading_start = position;
    while bytes.get(position) == Some(&b'#') && position - heading_start < 6 {
        position += 1;
    }
    if position > heading_start && bytes.get(position) == Some(&b' ') {
        return position + 1;
    }

    digits_start
}

fn blank_break_content<'a>(
    content: &'a str,
    after_breaks: &'a str,
    output: &str,
    drop_at_paragraph_start: bool,
    options: &ConversionOptions,
) -> &'a str {
    // ~keep Flow owners drop a leading break (#572); detached scratch buffers retain its
    // sentinel (#504). Noncollapsible blank tails retain the old separator.
    if drop_at_paragraph_start {
        let marker = crate::converter::main_helpers::hard_break_marker(options);
        if content.ends_with(marker) && content.trim_end_matches(marker).trim().is_empty() {
            ""
        } else {
            after_breaks
        }
    } else if after_breaks.len() < content.len() && !content.ends_with('\n') {
        // ~keep ASCII blank tails keep the detached break sentinel; NBSP keeps its old separator (#863/#843).
        if after_breaks
            .chars()
            .all(crate::converter::utility::white_space::is_collapsible)
        {
            &content[..content.len() - after_breaks.len()]
        } else {
            " "
        }
    } else if output.is_empty()
        && content.ends_with('\n')
        && content
            .trim_end_matches(crate::converter::main_helpers::hard_break_marker(options))
            .chars()
            .all(crate::converter::utility::white_space::is_collapsible)
    {
        &content[content.len() - 1..]
    } else {
        content
    }
}

fn inline_break_owner(output: &String, ctx: &Context) -> Option<usize> {
    let (address, start) = ctx
        .inline_break_owner
        .unwrap_or((ctx.block_output_ptr, ctx.block_content_start));
    (std::ptr::from_ref(output) as usize == address).then_some(start)
}

fn move_leading_hard_breaks<'a>(
    output: &mut String,
    content: &'a str,
    ctx: &Context,
    options: &ConversionOptions,
) -> &'a str {
    // ~keep Table-cell block boundaries are normalized by the cell renderer; hoisting one from
    // ~keep an inline wrapper turns the folded separator into literal hard-break syntax (#645).
    if ctx.in_table_cell {
        return content;
    }

    let mut after_breaks = content;
    loop {
        let candidate = after_breaks.trim_start_matches([' ', '\t']);
        let Some(rest) = ["\\\n", "\n"]
            .into_iter()
            .find_map(|marker| candidate.strip_prefix(marker))
        else {
            break;
        };
        after_breaks = rest;
    }
    // ~keep Bare newlines carry breaks across detached wrappers until a flow owner can emit
    // them. Its leading break is dropped, even after a structural list marker or prior block.
    let drop_at_paragraph_start = inline_break_owner(output, ctx) == Some(output.len());
    if after_breaks
        .trim_end_matches(crate::converter::main_helpers::hard_break_marker(options))
        .trim()
        .is_empty()
    {
        return blank_break_content(content, after_breaks, output, drop_at_paragraph_start, options);
    }

    let mut remaining = content;
    let mut moved = false;
    loop {
        let candidate = remaining.trim_start_matches([' ', '\t']);
        let Some((marker, rest)) = ["\\\n", "\n"]
            .into_iter()
            .find_map(|marker| candidate.strip_prefix(marker).map(|rest| (marker, rest)))
        else {
            break;
        };
        if !drop_at_paragraph_start {
            let starts_on_empty_line = output.ends_with('\n');
            crate::converter::list::utils::indent_list_item_line_start(output, ctx, options);
            let marker = if marker == "\n" {
                crate::converter::main_helpers::hard_break_marker(options)
            } else {
                marker
            };
            output.push_str(if marker == "  \n" && starts_on_empty_line {
                "\\\n"
            } else {
                marker
            });
        }
        remaining = rest;
        moved = true;
    }
    if moved && !drop_at_paragraph_start {
        crate::converter::list::utils::indent_list_item_line_start(output, ctx, options);
    }
    if moved {
        remaining = remaining.trim_start_matches([' ', '\t']);
    }
    remaining
}

fn emit_break_sentinel(output: &mut String, content: &str, ctx: &Context, options: &ConversionOptions) -> bool {
    if content != "\n" {
        return false;
    }
    let owner_start = inline_break_owner(output, ctx);
    // ~keep Empty detached wrappers carry the break regardless of their delimiters. An owner
    // drops its leading break; an existing line, including a scratch line, needs real syntax.
    if owner_start == Some(output.len()) {
        return true;
    }
    output.push_str(if output.is_empty() && owner_start.is_none() {
        "\n"
    } else {
        crate::converter::main_helpers::hard_break_marker(options)
    });
    true
}

#[cfg(test)]
thread_local! {
    static BLANK_PREFIX_NODE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

fn has_leading_blank_source(site: InlineSite<'_>) -> bool {
    site.dom_ctx.children_of(site.node_handle.get_inner())
        .and_then(|children| children.first())
        .inspect(|_| {
            #[cfg(test)]
            BLANK_PREFIX_NODE_READS.with(|reads| reads.set(reads.get() + 1));
        })
        .and_then(|child| child.get(site.parser))
        .is_some_and(|node| matches!(node, tl::Node::Raw(raw) if raw.as_utf8_str().starts_with(crate::converter::utility::white_space::is_collapsible)))
}

// ~keep A lone break is the #502 separator only in a block that starts its buffer. In a later
// ~keep block and in a link label it stays the hard break the page had before #871.
// ~keep A blank before the lone break, or a second break, makes it a hard break at every
// ~keep position (#897): only a wrapper that holds one break and nothing else is a separator.
// ~keep White space after the break in the wrapper's own text leaves the separator as it is.
fn keeps_hard_break(content: &str, site: InlineSite<'_>) -> bool {
    let marker = crate::converter::main_helpers::hard_break_marker(site.options);
    let body = content.trim_start_matches([' ', '\t']);
    let lone = body == "\n" || body == marker;
    ((content.len() > marker.len() && content.ends_with(marker))
        || (lone && (site.ctx.block_content_start != 0 || site.ctx.in_link)))
        && !site
            .dom_ctx
            .children_of(site.node_handle.get_inner())
            .and_then(|children| children.last())
            .and_then(|child| child.get(site.parser))
            .is_some_and(|node| {
                matches!(node, tl::Node::Raw(raw)
                    if raw.as_utf8_str().ends_with(crate::converter::utility::white_space::is_collapsible))
            })
}

fn strong_separator_content<'a>(output: &str, content: &'a str, keeps_break: bool, site: InlineSite<'_>) -> &'a str {
    let ctx = site.ctx;
    if keeps_break
        || !content.ends_with('\n')
        || !content
            .trim_end_matches(crate::converter::main_helpers::hard_break_marker(site.options))
            .chars()
            .all(crate::converter::utility::white_space::is_collapsible)
        || ctx.in_strong
        || ctx.in_code
        || ctx.in_code_block
    {
        return content;
    }
    // ~keep Italic wrappers carry rendered breaks; a leading blank prefix also belongs to the break.
    // ~keep Other blank strong/mark wrappers retain the established separator (#504).
    if (has_leading_blank_source(site)
        || site
            .dom_ctx
            .tag_info(site.node_handle.get_inner(), site.parser)
            .is_some_and(|tag| EMPHASIS_SIBLING_TAGS.contains(&tag.name.as_str())))
        && site
            .dom_ctx
            .holds_authored_break(site.node_handle.get_inner(), site.parser)
    {
        return content;
    }
    let previous =
        crate::converter::utility::siblings::get_previous_sibling_tag(site.node_handle, site.parser, site.dom_ctx);
    if !previous.is_some_and(|tag| {
        STRONG_SIBLING_TAGS.contains(&tag) && !ctx.strip_tags.contains(tag) && !ctx.preserve_tags.contains(tag)
    }) {
        return content;
    }
    let marker = if site.options.output_format == crate::options::OutputFormat::Djot {
        String::from("*")
    } else {
        [site.options.strong_em_symbol; 2].iter().collect()
    };
    if output.ends_with(&marker) { " " } else { content }
}

// ~keep Strict blank bodies without a retained BR contribute a separator, including custom blank children.
// ~keep Code/pre literals and nonempty BR callbacks keep their established break transport.
fn strict_blank_separator<'a>(content: &'a str, site: InlineSite<'_>) -> &'a str {
    if site.options.whitespace_mode == crate::options::WhitespaceMode::Strict
        && !site.ctx.in_code
        && !site.ctx.in_code_block
        && content.contains('\n')
        && content
            .chars()
            .all(crate::converter::utility::white_space::is_collapsible)
        && !site
            .dom_ctx
            .holds_authored_break(site.node_handle.get_inner(), site.parser)
    {
        " "
    } else {
        content
    }
}

/// Emit `content` wrapped in `delimiters`, handling delimiter-run adjacency with a preceding
/// sibling and a body that is non-empty but entirely whitespace.
pub fn emit_wrapped_inline(
    output: &mut String,
    content: &str,
    delimiters: &InlineDelimiters<'_>,
    site: InlineSite<'_>,
) {
    let InlineSite {
        node_handle,
        parser,
        dom_ctx,
        ctx,
        options,
    } = site;
    let InlineDelimiters {
        open,
        close,
        merge_symbol,
        sibling_tag_names,
    } = *delimiters;
    use crate::converter::utility::siblings::get_previous_sibling_tag;
    use crate::converter::{append_inline_suffix, chomp_inline, merge_adjacent_emphasis};

    let moved = move_leading_hard_breaks(output, strict_blank_separator(content, site), ctx, options);
    // ~keep A blank wrapper after real strong markup remains a separator (#502/#504).
    // DOM provenance plus the configured close marker excludes marker-looking prose.
    let content = strong_separator_content(output, moved, keeps_hard_break(content, site), site);
    let (prefix, suffix, trimmed) = chomp_inline(content);
    if emit_break_sentinel(output, content, ctx, options) {
        return;
    }
    // ~keep A noncollapsible blank body after an existing space keeps its character (#843).
    // ~keep Leading whitespace or a leading break still follows the existing blank-wrapper rule.
    let marker = crate::converter::main_helpers::hard_break_marker(options);
    let blank_body = content.trim_end_matches(marker);
    if output.ends_with([' ', '\t'])
        && !content.starts_with(crate::converter::utility::white_space::is_collapsible)
        && blank_body.chars().all(char::is_whitespace)
        && !blank_body
            .chars()
            .all(crate::converter::utility::white_space::is_collapsible)
    {
        let body = blank_body.trim_matches(crate::converter::utility::white_space::is_collapsible);
        output.push_str(body);
        let breaks = &content[blank_body.len()..];
        if breaks.is_empty() {
            append_inline_suffix(output, suffix, !body.is_empty(), node_handle, parser, dom_ctx);
        } else {
            output.push_str(breaks);
        }
        return;
    }
    // ~keep A backslash hard-break suffix must not turn a blank body into literal empty marks.
    if blank_body.trim().is_empty() {
        if content.is_empty() {
            return;
        }
        // ~keep issue #481: a whitespace-only body (e.g. `<i> </i>`) is one space at most, and
        // ~keep none where the rule of running text owes none (after a space, at a line start).
        if crate::converter::utility::white_space::space_is_owed_in(output, ctx) {
            output.push_str(prefix);
        }
        append_inline_suffix(output, suffix, false, node_handle, parser, dom_ctx);
        return;
    }

    crate::converter::utility::content::push_inline_prefix(output, prefix, options, ctx);
    let sibling_is_matching_tag =
        get_previous_sibling_tag(node_handle, parser, dom_ctx).is_some_and(|name| sibling_tag_names.contains(&name));
    let merged = prefix.is_empty()
        && sibling_is_matching_tag
        && merge_symbol.is_some_and(|symbol| {
            open.chars().all(|c| c == symbol) && merge_adjacent_emphasis(output, symbol, open.chars().count())
        });
    if !merged {
        output.push_str(open);
    }
    output.push_str(trimmed);
    output.push_str(close);
    append_inline_suffix(output, suffix, !trimmed.is_empty(), node_handle, parser, dom_ctx);
}

/// Emit an already-rendered inline code `span`, merging it into an immediately preceding
/// sibling code span rather than letting the two backticks sit adjacent.
///
/// `CommonMark` reads a code span's closing backtick immediately followed by the next span's
/// opening backtick as interior text, not as two spans: `` `A` `` and `` `B` `` written
/// back-to-back reparse as ONE span whose content carries both literal backticks -- issue
/// #483's delimiter-run adjacency in its backtick form. There is no `CommonMark` spelling for
/// two genuinely adjacent code spans, so the faithful choice is the merged span: it preserves
/// every character of the content, which the corrupted reparse does not.
///
/// Only a span that rendered as a plain single-backtick pair can merge. One that needed a
/// longer fence or delimiter spaces (because its own content contains backticks or edge
/// spaces) is emitted untouched rather than half-rewritten. ~keep
pub fn emit_code_span(
    span: &str,
    content: &str,
    output: &mut String,
    node_handle: &NodeHandle,
    parser: &Parser,
    dom_ctx: &DomContext,
) {
    use crate::converter::merge_adjacent_emphasis;
    use crate::converter::utility::siblings::get_previous_sibling_tag;

    let is_plain_single_backtick_pair =
        span.len() == content.len() + 2 && span.starts_with('`') && span.ends_with('`') && !content.contains('`');
    let previous_is_code_sibling = get_previous_sibling_tag(node_handle, parser, dom_ctx)
        .is_some_and(|name| matches!(name, "code" | "kbd" | "samp"));

    if is_plain_single_backtick_pair && previous_is_code_sibling && merge_adjacent_emphasis(output, '`', 1) {
        output.push_str(&span[1..]);
    } else {
        output.push_str(span);
    }
}

/// Push the single space a non-empty, all-whitespace inline body stands for.
///
/// Suppressed when the buffer already ends with a space, mirroring `text_node.rs`'s
/// `!output.ends_with(' ')` guards. ~keep
pub fn emit_whitespace_only_inline_body(content: &str, output: &mut String) {
    use crate::converter::chomp_inline;

    let (prefix, _, _) = chomp_inline(content);
    if !output.ends_with(' ') {
        output.push_str(prefix);
    }
}

#[cfg(test)]
mod tests {
    #[test]
    #[allow(clippy::print_stdout)]
    fn should_bound_nested_blank_break_prefix_and_content_reads() {
        let mut jobs = 0;
        for depth in [4, 16, 64, 256] {
            for newline_style in [crate::NewlineStyle::Spaces, crate::NewlineStyle::Backslash] {
                let source = format!("<p><b>a</b>{}<br>{}b</p>", "<em>".repeat(depth), "</em>".repeat(depth));
                let dom = tl::parse(&source, tl::ParserOptions::default()).expect("nested break nodes");
                let nodes = dom.nodes().len();
                assert_eq!(nodes, depth + 5);
                super::BLANK_PREFIX_NODE_READS.with(|reads| reads.set(0));
                crate::converter::dom_context::AUTHORED_BREAK_CACHE_STATS.with(|stats| stats.set((0, 0)));
                crate::converter::dom_context::HOLDS_TEXT_NODE_READS.with(|reads| reads.set(0));
                let result = crate::convert(
                    &source,
                    crate::ConversionOptions {
                        tier_strategy: crate::TierStrategy::Tier2,
                        extract_metadata: false,
                        newline_style,
                        max_depth: Some(1024),
                        ..Default::default()
                    },
                )
                .expect("nested breaks");
                let prefix_reads = super::BLANK_PREFIX_NODE_READS.with(std::cell::Cell::get);
                let content_reads = crate::converter::dom_context::HOLDS_TEXT_NODE_READS.with(std::cell::Cell::get);
                let marker = if newline_style == crate::NewlineStyle::Spaces {
                    "  \n"
                } else {
                    "\\\n"
                };
                assert_eq!(result.content.as_deref(), Some(format!("**a**{marker}b\n").as_str()));
                assert_eq!(prefix_reads, depth);
                assert_eq!(content_reads, depth);
                let (entries, capacity) =
                    crate::converter::dom_context::AUTHORED_BREAK_CACHE_STATS.with(std::cell::Cell::get);
                assert_eq!(entries, depth);
                assert!(capacity <= 2 * depth);
                assert!(content_reads > 0 && content_reads <= 4 * nodes);
                std::println!(
                    "break-cost {depth} {nodes} {prefix_reads} {content_reads} {entries} {capacity} {newline_style:?}"
                );
                jobs += 1;
            }
        }
        assert_eq!(jobs, 8);
    }

    use super::move_leading_hard_breaks;
    use crate::converter::Context;
    use crate::converter::context::ContextParameters;
    use crate::converter::url_resolve::OwnPage;
    use crate::options::ConversionOptions;

    #[test]
    fn should_drop_break_only_content_in_the_paragraphs_own_empty_buffer() {
        let options = ConversionOptions::default();
        let mut output = String::new();
        let mut context = Context::new(
            &options,
            ContextParameters {
                inline_collector: None,
                #[cfg(feature = "metadata")]
                metadata_collector: None,
                kept_scripts: crate::converter::utility::preprocessing::KeptScripts::default(),
                #[cfg(feature = "visitor")]
                visitor: None,
                structure_collector: None,
                reference_collector: None,
                base_url: None,
                own_page: OwnPage::UnknownWithoutBase,
            },
        );
        context.in_paragraph = true;
        context.block_output_ptr = std::ptr::from_ref::<String>(&output) as usize;
        let remaining = move_leading_hard_breaks(&mut output, "  \n", &context, &options);
        assert_eq!(remaining, "");
        assert_eq!(output, "");
    }
}