html-to-markdown-rs 3.17.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
fn close_code(
    state: &mut Tier1State,
    frame: &OpenTag,
    trim_boundary_whitespace: bool,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    if state.escape_ctx.contains(EscapeCtx::PRE) || state.escape_ctx.contains(EscapeCtx::CODE) {
        return Ok(());
    }
    // ~keep Phase CC: smart backtick escaping (mirrors inline/code.rs:260).
    // Open emitted nothing; content from `frame.content_start` to buf
    // end is the raw code content.  Choose num_backticks + delimiter
    // spaces from that slice, then truncate and re-emit wrapped.
    let buf = state.cell_or_output_mut();
    let content_start = clamp_to_char_boundary(buf, frame.content_start);
    if content_start >= buf.len() {
        // ~keep issue #481: a body that WAS non-empty but entirely whitespace before
        // `flush_text` dropped it is not an empty one. Tier-2 keeps `<code> </code>` as
        // a code span whose content is that space; erasing it here, as the genuinely
        // empty `<code></code>` case correctly does, would drop both the span and the
        // word separator it stands between.
        if frame.dropped_whitespace_only_text {
            return Err(BailReason::WhitespaceOnlyInlineEmphasis);
        }
        // ~keep No content emitted between open and close — Tier-2 emits
        // nothing for empty <code></code>.
        return Ok(());
    }

    // ~keep issue #483, backtick form: this span's opening backtick is about to be inserted
    // right after a preceding code span's closing one, which reparses as a single span
    // carrying both literal backticks. Tier-2 merges the two spans
    // (`wrapped::emit_code_span`); Tier-1 does not, so it bails.
    if buf[..content_start].ends_with('`') {
        return Err(BailReason::AdjacentInlineEmphasis);
    }

    // ~keep issue #487: `content` may contain internal '\n' bytes, each marking where a
    // `<br>` split this span (`emit_void`'s `TagKind::LineBreak` arm) -- a text
    // node's own line ending never reaches this buffer as a bare '\n' (`flush_text`'s
    // `in_code` branch already folds it to a space). Split on it and render each
    // segment as its own smart-escaped backtick span (`format_inline_code_segment`,
    // computed per segment rather than once over the whole original content), joined
    // by the "  \n" hard-break marker OUTSIDE the backticks -- the only marker shape
    // this scanner ever needs, since the router bails to Tier-2 whenever
    // `newline_style` is not `Spaces`. An empty segment (an adjacent, leading, or
    // trailing `<br>`) is dropped rather than rendered as a dangling empty `` `` ``
    // pair with nothing before or after it. Only the FIRST segment can ever be
    // adjacent to a preceding sibling's closing backtick -- checked once, above,
    // against `buf[..content_start]` before this loop runs -- every later segment is
    // preceded by our own separator instead.
    let (leading, content, trailing) = code_span_parts(&buf[content_start..], trim_boundary_whitespace);
    buf.truncate(content_start);
    buf.push_str(&leading);

    let mut first = true;
    for segment in content.split('\n').filter(|segment| !segment.is_empty()) {
        if !first {
            buf.push_str(crate::converter::main_helpers::hard_break_marker(options));
        }
        format_inline_code_segment(buf, segment);
        first = false;
    }
    buf.push_str(&trailing);
    Ok(())
}

fn code_span_parts(original: &str, trim_boundary_whitespace: bool) -> (String, String, String) {
    let trimmed = original.trim();
    if !trim_boundary_whitespace || trimmed.is_empty() {
        return (String::new(), original.to_owned(), String::new());
    }
    let leading_len = original.len() - original.trim_start().len();
    let trailing_start = original.trim_end().len();
    (
        original[..leading_len].to_owned(),
        trimmed.to_owned(),
        original[trailing_start..].to_owned(),
    )
}

/// Wrap `content` in backtick delimiters, choosing the fence width and delimiter-space
/// padding from `content` alone.
///
/// The per-segment counterpart to what this replaced: `close_code` used to compute these
/// once over the whole span's content, but a `<br>`-split span now needs them computed
/// independently for each segment, since a backtick run in one half must not force a wider
/// fence on a half that has none (issue #487). Mirrors
/// `handlers::code_block::format_inline_code`.
fn format_inline_code_segment(buf: &mut String, content: &str) {
    let contains_backtick = content.contains('`');
    let first_char = content.chars().next();
    let last_char = content.chars().last();
    let starts_with_space = first_char == Some(' ');
    let ends_with_space = last_char == Some(' ');
    let starts_with_backtick = first_char == Some('`');
    let ends_with_backtick = last_char == Some('`');
    // ~keep No all-spaces case: CommonMark strips one space from each end of a code span
    // only when the content is NOT entirely spaces, so padding an all-spaces body
    // changes what it contains. Mirrors `handlers::code_block::format_inline_code`.
    let needs_spaces =
        starts_with_backtick || ends_with_backtick || (starts_with_space && ends_with_space && contains_backtick);
    let num_backticks = if contains_backtick {
        min_safe_code_span_delimiter_length(content)
    } else {
        1
    };

    for _ in 0..num_backticks {
        buf.push('`');
    }
    if needs_spaces {
        buf.push(' ');
    }
    buf.push_str(content);
    if needs_spaces {
        buf.push(' ');
    }
    for _ in 0..num_backticks {
        buf.push('`');
    }
}

/// Compute the length of the longest consecutive run of `` ` `` in `content`.
///
/// ~keep Mirrors `converter::handlers::code_block::longest_consecutive_run`
/// (see the shared-helper note on `MIN_FENCE_LENGTH` above).
fn longest_consecutive_backtick_run(content: &str) -> usize {
    content
        .chars()
        .fold((0usize, 0usize), |(max, current), c| {
            if c == '`' {
                let next = current + 1;
                (max.max(next), next)
            } else {
                (max, 0)
            }
        })
        .0
}

/// Smallest backtick-run length (starting at 1) that does not occur as a run inside `content`.
///
/// ~keep Mirrors `converter::handlers::code_block::min_safe_code_span_delimiter_length`
/// byte-for-byte (see the shared-helper note on `MIN_FENCE_LENGTH` above). CommonMark
/// closes an inline code span at the next backtick string of the *same* length as the
/// opener (6.1), so `longest_run + 1` unconditionally over-escapes: content `` `` `` (a
/// single length-2 run, no length-1 run) is valid with a single backtick delimiter.
fn min_safe_code_span_delimiter_length(content: &str) -> usize {
    let mut run_lengths = std::collections::HashSet::new();
    let mut current = 0usize;
    for c in content.chars() {
        if c == '`' {
            current += 1;
        } else {
            if current > 0 {
                run_lengths.insert(current);
            }
            current = 0;
        }
    }
    if current > 0 {
        run_lengths.insert(current);
    }

    let mut candidate = 1usize;
    while run_lengths.contains(&candidate) {
        candidate += 1;
    }
    candidate
}

/// Returns `true` if every byte of `needle` appears in `haystack`, in order, not
/// necessarily contiguously (a byte-level subsequence test). O(haystack.len()), no
/// allocation.
///
/// ~keep Used by `close_link`'s nested-markup autolink guard: greedy left-to-right
/// matching is correct for subsequence testing regardless of UTF-8 char
/// boundaries — if a char sequence is a subsequence of another, each char's
/// byte run appears intact and in order, so the greedy byte scan below always
/// finds it. A byte-level "match" that happens to straddle char boundaries can
/// only make this return `true` MORE often than a char-aware version would,
/// never less — which only makes the caller's bail more conservative, never
/// less safe.
fn is_byte_subsequence(needle: &str, haystack: &str) -> bool {
    let mut needle_bytes = needle.bytes();
    let Some(mut want) = needle_bytes.next() else {
        return true;
    };
    for byte in haystack.bytes() {
        if byte == want {
            match needle_bytes.next() {
                Some(next_want) => want = next_want,
                None => return true,
            }
        }
    }
    false
}

/// Rewrites the link the scanner has already opened in `dest` into GFM autolink form
/// (`<href>`) when Tier-2 would do the same, returning `Ok(true)` when it did.
///
/// Mirrors Tier-2's predicate at `handlers/link.rs:91-101` exactly: `options.autolinks &&
/// !options.default_title && href non-empty && has_uri_scheme(href) && (label == href ||
/// (mailto: && label == href[7..]))`. `dest[trim_start..]` is Tier-2's `raw_text` for the
/// common flat-text case -- both sides have already collapsed whitespace/NBSP the same way,
/// and neither has run `escape_link_label` or bracket-wrapping yet.
fn try_emit_autolink(
    dest: &mut String,
    trim_start: usize,
    frame: &OpenTag,
    href_str: &str,
    has_nested_tag: bool,
    options: &ConversionOptions,
) -> Result<bool, BailReason> {
    if !options.autolinks || options.default_title || href_str.is_empty() || !has_uri_scheme(href_str) {
        return Ok(false);
    }
    let mailto_suffix = href_str.strip_prefix("mailto:");
    let label = &dest[trim_start..];
    if has_nested_tag {
        // ~keep A nested tag means the buffer is no longer flat text, so a literal
        // `label == href` compare is untrustworthy: `<b>u</b>` renders as `**u**`,
        // which never equals bare `u`, yet Tier-2 -- which compares against the
        // TAG-STRIPPED text -- would autolink it. Bailing on every nested tag is not
        // the fix either: measured against `tools/benchmark-harness/fixtures`,
        // 85-100% of scheme-href `<a>` elements on every fixture that has any are
        // wrapped in at least a `<span>`, so a blanket bail would drop nearly every
        // real page off the Tier-1 fast path.
        // ~keep
        // ~keep Instead, a cheap PROVABLY CONSERVATIVE precheck. Every transformation
        // Tier-1 applies while rendering a label (emphasis/strong/strikethrough and
        // inserted markers, code-span backtick fences, label-bracket escaping,
        // `![alt](src)` for a nested `<img>`) only INSERTS characters; none delete or
        // substitute the underlying text. Tier-2's `raw_text` is that same underlying
        // text with tags stripped and whitespace collapsed, both of which only REMOVE
        // characters. So `raw_text` is always a subsequence of this buffer, and if
        // `raw_text == target` then `target` is a subsequence of the buffer too.
        // Contrapositive: a `target` that is NOT a subsequence proves Tier-2 cannot
        // autolink either, so falling through to the normal link form is safe. Bail
        // only when the precheck cannot rule it out.
        let could_be_autolink = is_byte_subsequence(href_str, label)
            || mailto_suffix.is_some_and(|suffix| is_byte_subsequence(suffix, label));
        if could_be_autolink {
            return Err(BailReason::LinkAutolinkNestedMarkup);
        }
        // ~keep Ruled out above, so the exact `label == target` match below cannot fire
        // either -- equality would imply the subsequence that was just disproved.
    }
    let rendered = if label == href_str {
        href_str
    } else if mailto_suffix == Some(label) {
        // ~keep `mailto_suffix` is `Some` on this arm by construction.
        mailto_suffix.unwrap_or(href_str)
    } else {
        return Ok(false);
    };
    // ~keep An autolink has no bracket wrapping at all, but the scanner already emitted
    // the opening `[` at link-open time, before it could know the label. Remove it,
    // mirroring the href-less branch in `close_link` that does the same cleanup.
    let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
    let label_start = if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
        dest.remove(bracket_pos);
        trim_start - 1
    } else {
        trim_start
    };
    let rendered = rendered.to_owned();
    dest.truncate(label_start);
    dest.push('<');
    dest.push_str(&rendered);
    dest.push('>');
    Ok(true)
}

/// Trim the link label Tier-1 has just written in place, keeping a hard line break that sits
/// at either edge of it.
///
/// A `<br>` against the `</a>` is real content: `<a href="H">A<br></a>B` renders as A, a line
/// break, then B, and `[A  \n](H)B` re-parses to exactly that (issue #497). The blanket
/// trailing-whitespace trim this replaced ate the marker's two spaces and its newline, since
/// flattened they are indistinguishable from incidental whitespace before a `</a>`.
///
/// Mirrors Tier-2's `assemble_label` (`utility/content.rs`) including its two edge rules: a
/// run of breaks at one edge collapses to a single break, because two adjacent markers put a
/// blank line in the label and a blank line ends the paragraph the link lives in; and a label
/// holding nothing but breaks collapses to empty, because a break needs a line on both sides
/// to mean anything.
///
/// ~keep `marker` is selected from the complete conversion options: Markdown Tier-1 uses the
/// spaces form, while Djot always uses the backslash form regardless of `newline_style`.
///
/// With `keeps_breaks` false -- a heading or a pipe-table cell, neither of which can carry a
/// hard break at all -- every marker in the label is folded to a space instead, which is what
/// Tier-2 does at emission time in `line_break.rs`.
fn trim_label_preserving_boundary_hard_breaks(dest: &mut String, trim_start: usize, keeps_breaks: bool, marker: &str) {
    if !keeps_breaks {
        // ~keep Fold the markers away entirely rather than merely declining to keep the ones at
        // the edges. `close_heading` / `close_table_cell` would collapse them to a space
        // anyway, but they run AFTER `close_link` has escaped the label, so a marker left
        // here reaches `escape_link_label` as a real line break and its continuation line
        // gets a #496 block-opener escape that Tier-2 -- which folds at emission time,
        // in `line_break.rs`'s `in_heading` arm -- never applies. That divergence is
        // visible as `# [A \- B](H)` against Tier-2's `# [A - B](H)`.
        let label = &dest[trim_start..];
        if label.contains(marker) {
            let folded = label.replace(marker, " ");
            dest.truncate(trim_start);
            dest.push_str(&folded);
        }
        // ~keep Trim BOTH ends, not just the trailing one: Tier-2 reaches this label through
        // `normalize_link_label`, which trims both, so a folded leading break that left a
        // space behind shows up as `## [ A](H)` against Tier-2's `## [A](H)`.
        let trimmed = dest[trim_start..].trim_matches(|c: char| c.is_whitespace()).to_owned();
        dest.truncate(trim_start);
        dest.push_str(&trimmed);
        return;
    }

    let label = &dest[trim_start..];
    let without_trailing = label.trim_end_matches(marker);
    let has_trailing_break = without_trailing.len() != label.len();
    let body = without_trailing.trim_end_matches(|c: char| c.is_whitespace());
    let without_leading = body.trim_start_matches(marker);
    let has_leading_break = without_leading.len() != body.len();

    let mut rebuilt = String::with_capacity(without_leading.len() + 2 * marker.len());
    if !without_leading.is_empty() {
        if has_leading_break {
            rebuilt.push_str(marker);
        }
        rebuilt.push_str(without_leading);
        if has_trailing_break {
            rebuilt.push_str(marker);
        }
    }

    if rebuilt.len() != label.len() {
        dest.truncate(trim_start);
        dest.push_str(&rebuilt);
    }

    if let std::borrow::Cow::Owned(protected) =
        crate::converter::utility::content::protect_adjacent_hard_breaks(&dest[trim_start..])
    {
        dest.truncate(trim_start);
        dest.push_str(&protected);
    }
}

fn close_link(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) -> Result<(), BailReason> {
    // ~keep Close the link: `](href "title")` or `](href)`
    // If no href, just emit the text as-is (Tier-2 behaviour: no link markup).
    // Link state was pushed to state.link_stack at open; pop it now.
    let (href, title, has_nested_tag) = state.link_stack.pop().unwrap_or((None, None, false));
    // ~keep Mirrors the branch ORDER of Tier-2's `line_break.rs`, where `in_heading` and
    // `in_table_cell` are both tested ahead of the link arm: a single-line ATX heading
    // and a pipe-table cell cannot carry a hard break at all, so a `<br>` in either has
    // already been folded to a space regardless of the link, and a marker kept at the
    // label's edge here would only survive as a stray trailing space.
    let keeps_boundary_hard_breaks = !state.escape_ctx.contains(EscapeCtx::HEADING) && !state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Trim the whitespace inside the link label so `[text  ](url)` collapses to
    // `[text](url)` — matches Tier-2's `normalize_link_label` (kimbrain.html and similar
    // source HTML with whitespace before `</a>`), while keeping a `<br>` that sits at
    // either edge of the label (issue #497).
    let trim_start = clamp_to_char_boundary(dest, frame.content_start);
    trim_label_preserving_boundary_hard_breaks(
        dest,
        trim_start,
        keeps_boundary_hard_breaks,
        crate::converter::main_helpers::hard_break_marker(options),
    );
    // ~keep Mirror Tier-2's `normalize_whitespace_cow` step inside
    // `normalize_link_label` (utility/content.rs:144): any Unicode whitespace
    // in the link label (notably NBSP `\u{00a0}`) collapses to a single ASCII
    // space.  Tier-1 otherwise emits `[Designed\u{a0}by](url)` where Tier-2
    // emits `[Designed by](url)`.
    normalize_link_label_nbsp(dest, trim_start);
    if let Some(href_str) = href.as_deref() {
        if try_emit_autolink(dest, trim_start, frame, href_str, has_nested_tag, options)? {
            return Ok(());
        }
    }
    // ~keep Wikipedia back-reference normalisation (Tier-2 `handlers/link.rs:205`):
    // a label of exactly `^` paired with an `#anchor` href is rewritten to
    // `↑` so it does not look like Markdown's footnote syntax.
    if let Some(href_str) = href.as_deref() {
        if href_str.starts_with('#') && dest.len() == trim_start + 1 && dest.as_bytes()[trim_start] == b'^' {
            dest.truncate(trim_start);
            dest.push('↑');
        }
    }
    if let Some(href) = href {
        emit_markdown_link_close(dest, trim_start, &href, title.as_deref(), options);
    } else {
        let bracket_search_end = clamp_to_char_boundary(dest, frame.content_start);
        if let Some(bracket_pos) = dest[..bracket_search_end].rfind('[') {
            dest.remove(bracket_pos);
        }
    }
    Ok(())
}

fn normalize_link_label_nbsp(dest: &mut String, trim_start: usize) {
    if !dest[trim_start..].contains('\u{00a0}') {
        return;
    }
    let normalized = dest[trim_start..]
        .chars()
        .map(|character| if character == '\u{00a0}' { ' ' } else { character })
        .collect::<String>();
    dest.truncate(trim_start);
    dest.push_str(&normalized);
}

fn emit_markdown_link_close(
    dest: &mut String,
    trim_start: usize,
    href: &str,
    title: Option<&str>,
    options: &ConversionOptions,
) {
    if let std::borrow::Cow::Owned(escaped_label) =
        crate::converter::utility::escaping::escape_link_label(&dest[trim_start..])
    {
        dest.truncate(trim_start);
        dest.push_str(&escaped_label);
    }
    dest.push_str("](");
    crate::converter::inline::link::append_url_destination(dest, href, options.url_escape_style, title.is_some());
    if let Some(title) = title {
        let escaped_title = crate::converter::inline::link::escape_markdown_title(title);
        dest.push_str(" \"");
        dest.push_str(&escaped_title);
        dest.push('"');
    }
    dest.push(')');
}

fn close_list(state: &mut Tier1State, kind: ListKind) {
    state.list_depth = state.list_depth.saturating_sub(1);
    if matches!(kind, ListKind::Unordered) {
        state.ul_depth = state.ul_depth.saturating_sub(1);
    }
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // the list — the cell accumulator handles any separators via the
    // `\n → space` replacement at cell-close time.
    if state.in_table_cell() {
        return;
    }
    let dest = state.cell_or_output_mut();
    if !dest.ends_with('\n') {
        dest.push('\n');
    }
    if kind == ListKind::Ordered {
        let end = dest.trim_end().len();
        state.last_ordered_list_end = Some(end);
    }
}

fn close_list_item(state: &mut Tier1State, frame: &OpenTag) -> Result<(), BailReason> {
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // each list item (see list/item.rs: `if !ctx.in_table_cell { ... \n ... }`).
    // Items are concatenated directly in the cell accumulator.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
            cell_buf.pop();
        }
        return Ok(());
    }
    state.list_item_marker_widths.pop();
    let after_text = state.list_items_after_text.pop().unwrap_or_default();
    trim_trailing_inline_whitespace(state);
    // ~keep A nested item, or an item after text inside its list, with nothing on its marker line
    // ~keep cannot interrupt the text before it (issue #667). Tier 2 decides whether that text is
    // ~keep an open paragraph.
    let follows_text = state.list_depth > 1 || after_text;
    let dest = state.cell_or_output_mut();
    let marker_line = dest
        .get(clamp_to_char_boundary(dest, frame.content_start)..)
        .unwrap_or_default();
    if follows_text && marker_line.split('\n').next().unwrap_or_default().trim().is_empty() {
        return Err(BailReason::EmptyNestedListItem);
    }
    // ~keep Phase EE: loose-list separator.  When this item had block-level
    // children (its content range contains a `\n\n` block separator),
    // mirror Tier-2's `handle_li` ensure_trailing_blank_line behaviour
    // so the next sibling `<li>` starts after a blank line.  Plain text
    // items still get the tight `\n` terminator.
    let had_block_children = {
        let start = clamp_to_char_boundary(dest, frame.content_start);
        dest[start..].contains("\n\n")
    };
    if had_block_children {
        if !dest.ends_with("\n\n") {
            if dest.ends_with('\n') {
                dest.push('\n');
            } else {
                dest.push_str("\n\n");
            }
        }
    } else if !dest.is_empty() && !dest.ends_with('\n') {
        dest.push('\n');
    }
    Ok(())
}

// ~keep ── Definition-list helpers ───────────────────────────────────────────────────
// ~keep
// ~keep Tier-2 reference: crates/html-to-markdown/src/converter/list/definition.rs.
// Tier-2 builds the full <dl> content in a buffer, trims it, then emits with
// "\n\n" boundaries. <dt> emits trimmed term + "\n"; <dd> emits trimmed
// description + "\n\n". Tier-1 streams the same shape by:
//   - open_dl: ensure blank line; record content_start on the frame
//   - close_dt: trim trailing whitespace, push "\n"
//   - close_dd: trim trailing whitespace, push "\n\n"
//   - close_dl: trim leading/trailing whitespace inside the dl range, then
//               normalise the trailing separator to "\n\n"
// ~keep
// ~keep Bails on dl/dt/dd are removed (see bail_unsupported). Implicit close of an
// open dt/dd when a sibling dt/dd opens is wired via OptionalCloseRule::
// CloseSiblingDtDd in spec_rules.rs and runs the same close_dt/close_dd path
// through emit_close_for_implicit.

fn open_dl(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    state.ensure_blank_line();
}

fn open_dt(state: &mut Tier1State) {
    mark_definition_in_cell(state);
}

fn open_dd(state: &mut Tier1State) {
    mark_definition_in_cell(state);
}

fn mark_definition_in_cell(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut().filter(|ts| ts.in_cell) {
        ts.definition_in_cell = true;
    }
}

fn close_dt(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() || buf.ends_with('\n') {
        return;
    }
    buf.push('\n');
}

fn close_dd(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() {
        return;
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

fn close_dl(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let buf = state.cell_or_output_mut();
    // ~keep Empty dl: emit nothing (matches Tier-2 which skips when trimmed content
    // is empty).
    if buf.len() <= frame.content_start {
        return;
    }
    // ~keep Tier-2 trims the dl's accumulated content, so any trailing whitespace
    // from the last dt/dd close should collapse to a single "\n\n" separator.
    while buf.len() > frame.content_start {
        let last = buf.as_bytes()[buf.len() - 1];
        if matches!(last, b' ' | b'\t' | b'\n' | b'\r') {
            buf.pop();
        } else {
            break;
        }
    }
    if buf.len() == frame.content_start {
        return;
    }
    buf.push_str("\n\n");
}