html-to-markdown-rs 3.18.7

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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Main conversion pipeline for HTML to Markdown.
//!
//! This module implements the core conversion functions and the tree walker that transforms
//! HTML DOM nodes into Markdown output.

#![allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    clippy::trivially_copy_pass_by_ref,
    clippy::items_after_statements
)]

use std::borrow::Cow;
use std::collections::HashSet;

use crate::converter::dom_context::DomContext;
use crate::converter::main_helpers::{
    collapse_excess_blank_lines, effective_max_depth, extract_head_metadata, format_metadata_frontmatter,
    is_inline_element, repair_limit_warning, strip_trailing_backslash_breaks, trim_line_end_whitespace,
    trim_trailing_whitespace,
};
use crate::converter::plain_text::extract_plain_text;
use crate::converter::preprocessing_helpers::{is_page_header, should_drop_for_preprocessing};
use crate::converter::utility::content::{is_block_level_element, normalized_tag_name};
use crate::converter::utility::preprocessing::{PRESERVED_MENU_ATTRIBUTE, restore_preserved_menu_elements};
use crate::converter::utility::serialization::serialize_tag_to_html;
use crate::options::{NewlineStyle, OutputFormat};

use crate::converter::block::container::HandlerContext;
use crate::error::Result;
use crate::options::ConversionOptions;

use crate::converter::context::{Context, InlineCollectorHandle};
use crate::types::structure_collector::StructureCollectorHandle;

mod block_boundary;
mod context_setup;
mod exclusions;
mod markdown_walk;
mod parse;
mod prepare;
mod table_parts;
use self::block_boundary::{separate_in_list_item, separate_words_at_block_boundary};
use self::context_setup::create_conversion_context;
use self::markdown_walk::walk_nodes;
pub use self::markdown_walk::{WalkSpares, walk_opened};
use self::parse::{ParsedPage, finish_dom_parse, parse_for_conversion};
pub use self::prepare::owner_mark_numbers_after_cleanup;
use self::prepare::prepare_html;

type ConversionOutput = (
    String,
    Option<crate::types::DocumentStructure>,
    Vec<crate::types::TableData>,
    Option<crate::types::ProcessingWarning>,
);

pub struct ConversionParameters<'a> {
    pub inert_bodies: &'a std::collections::HashMap<String, String>,
    pub inline_collector: Option<InlineCollectorHandle>,
    #[cfg(feature = "metadata")]
    pub metadata_collector: Option<crate::metadata::MetadataCollectorHandle>,
    #[cfg(feature = "visitor")]
    pub visitor: Option<crate::visitor::VisitorHandle>,
    pub structure_collector: Option<StructureCollectorHandle>,
    pub base_url: Option<std::rc::Rc<url::Url>>,
    pub document_base_href: Option<&'a str>,
    /// The limit that the head repair reached before this conversion, if it reached one.
    ///
    /// ~keep The converter joins it with the limits of its own repairs and gives one warning
    /// ~keep for the conversion. The caller gives no warning of its own.
    pub head_repair_limit: Option<crate::types::WarningKind>,
}
/// Internal implementation of HTML to Markdown conversion.
///
/// Returns the converted content, optional document structure, extracted tables, and at most
/// one warning: the depth-limit warning of the walk, or else the warning of a repair that
/// reached a limit.
pub fn convert_html_impl(
    html: &str,
    options: &ConversionOptions,
    parameters: ConversionParameters<'_>,
) -> Result<ConversionOutput> {
    let inert_bodies = parameters.inert_bodies;
    let structure_collector = parameters.structure_collector.as_ref().map(std::rc::Rc::clone);
    let document_base_href = parameters.document_base_href;
    let (preprocessed, prepare_limit, as_written, kept_scripts) = prepare_html(html, options)?;
    let repaired_page = std::cell::OnceCell::new();
    let ParsedPage {
        source: parsed_source,
        mut dom,
        mut dom_ctx,
        len: preprocessed_len,
        repair_limit,
    } = parse_for_conversion(&preprocessed, &repaired_page, options, as_written)?;
    let repair_warning = repair_limit.or(prepare_limit).or(parameters.head_repair_limit);
    let kept_scripts = finish_dom_parse(&mut dom, &mut dom_ctx, inert_bodies, preprocessed_len, kept_scripts)?;
    let parser = dom.parser();
    let mut output = String::with_capacity(preprocessed_len.saturating_add(preprocessed_len / 4));
    let is_plain_text = options.output_format == OutputFormat::Plain;
    let frontmatter = prepare_frontmatter(
        &dom,
        parser,
        parsed_source,
        options,
        document_base_href,
        #[cfg(feature = "metadata")]
        parameters.metadata_collector.as_ref(),
    );
    output.push_str(&frontmatter);
    if !frontmatter.is_empty() {
        output.push('\n');
    }

    let reference_collector = create_reference_collector(options);

    let mut ctx = create_conversion_context(html, options, parameters, reference_collector.as_ref(), kept_scripts);
    if !options.skip_images
        && dom.nodes().iter().any(|node| {
            matches!(node, tl::Node::Tag(tag) if tag.name().as_utf8_str().eq_ignore_ascii_case("img")
                || tag.name().as_utf8_str().eq_ignore_ascii_case("svg"))
        })
    {
        ctx.media_boundary = Some(std::rc::Rc::new(std::cell::Cell::new(Default::default())));
    }

    apply_exclusions(&dom, options, &mut ctx);
    walk_document(&dom, parser, &mut output, options, &ctx, &dom_ctx);

    trace_walk_complete(&ctx);

    check_visitor_error(&ctx)?;

    let depth_warning = depth_warning(&ctx, options).or_else(|| repair_warning.map(repair_limit_warning));

    // ~keep Drop ctx before unwrapping the structure collector Rc — ctx holds a cloned Rc
    // ~keep reference to the same collector, and Rc::try_unwrap requires exactly one reference.
    drop(ctx);

    append_references(&mut output, reference_collector);
    let output = finalize_output(&dom, parser, options, output, &frontmatter, is_plain_text);
    let (document, tables) = finish_structure_collector(structure_collector);
    trace_render_complete(&output, &tables);
    Ok((output, document, tables, depth_warning))
}

fn create_reference_collector(
    options: &ConversionOptions,
) -> Option<crate::converter::reference_collector::ReferenceCollectorHandle> {
    (options.link_style == crate::options::LinkStyle::Reference).then(|| {
        std::rc::Rc::new(std::cell::RefCell::new(
            crate::converter::reference_collector::ReferenceCollector::new(),
        ))
    })
}

fn trace_parse_complete(dom: &tl::VDom<'_>, input_len: usize) {
    tracing::debug!(
        target: "html_to_markdown::convert",
        node_count = dom.nodes().len(),
        input_len,
        "html parse stage complete"
    );
}

fn trace_walk_complete(ctx: &Context) {
    tracing::debug!(
        target: "html_to_markdown::convert",
        depth_limit_reached = ctx.depth_limit_reached.get(),
        "dom walk stage complete"
    );
}

fn trace_render_complete(output: &str, tables: &[crate::types::TableData]) {
    tracing::debug!(
        target: "html_to_markdown::convert",
        output_len = output.len(),
        table_count = tables.len(),
        "render stage complete"
    );
}

fn apply_exclusions(dom: &tl::VDom<'_>, options: &ConversionOptions, ctx: &mut Context) {
    if options.exclude_selectors.is_empty() {
        return;
    }
    let mut excluded: HashSet<u32> = HashSet::new();
    for selector in &options.exclude_selectors {
        if let Some(iter) = dom.query_selector(selector) {
            excluded.extend(iter.map(|handle| handle.get_inner()));
        }
    }
    ctx.set_excluded_node_ids(excluded);
}

fn walk_document(
    dom: &tl::VDom<'_>,
    parser: &tl::Parser<'_>,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
    dom_ctx: &DomContext,
) {
    let top_level_start = output.len();
    let handler = HandlerContext::new(options, ctx, 0, dom_ctx);
    walk_nodes(dom.children(), parser, output, handler);
    // ~keep The document end is the one block boundary no subsequent dispatch can observe.
    if options.newline_style == NewlineStyle::Backslash {
        strip_trailing_backslash_breaks(output, top_level_start);
    }
}

fn depth_warning(ctx: &Context, options: &ConversionOptions) -> Option<crate::types::ProcessingWarning> {
    let max_depth = effective_max_depth(options);
    ctx.depth_limit_reached.get().then(|| {
        tracing::warn!(
            target: "html_to_markdown::convert",
            max_depth,
            "DOM traversal reached the effective depth limit; deeper nodes were skipped"
        );
        crate::types::ProcessingWarning {
            kind: crate::types::WarningKind::DepthLimitExceeded,
            message: format!(
                "DOM traversal reached the effective depth limit of {max_depth}; deeper nodes were skipped."
            ),
        }
    })
}

fn append_references(
    output: &mut String,
    reference_collector: Option<
        std::rc::Rc<std::cell::RefCell<crate::converter::reference_collector::ReferenceCollector>>,
    >,
) {
    let Some(rc) = reference_collector else { return };
    let Ok(collector) = std::rc::Rc::try_unwrap(rc) else {
        return;
    };
    let ref_section = collector.into_inner().finish();
    if ref_section.is_empty() {
        return;
    }
    output.truncate(output.trim_end_matches('\n').len());
    output.push_str("\n\n");
    output.push_str(&ref_section);
}

fn finalize_output(
    dom: &tl::VDom<'_>,
    parser: &tl::Parser<'_>,
    options: &ConversionOptions,
    mut output: String,
    frontmatter: &str,
    is_plain_text: bool,
) -> String {
    if is_plain_text {
        output = extract_plain_text(dom, parser, options);
    } else {
        trim_line_end_whitespace(&mut output, options.code_block_style);
        collapse_excess_blank_lines(&mut output, options.code_block_style);
    }
    if options.wrap {
        wrap_after_frontmatter(&output, frontmatter, options)
    } else {
        output
    }
}

fn prepare_frontmatter(
    dom: &tl::VDom<'_>,
    parser: &tl::Parser<'_>,
    parsed_source: &str,
    options: &ConversionOptions,
    document_base_href: Option<&str>,
    #[cfg(feature = "metadata")] metadata_collector: Option<&crate::metadata::MetadataCollectorHandle>,
) -> String {
    let wants_frontmatter = options.extract_metadata && !options.convert_as_inline;
    #[cfg(feature = "metadata")]
    let wants_document = metadata_collector.is_some_and(|collector| collector.borrow().wants_document());
    #[cfg(not(feature = "metadata"))]
    let wants_document = false;
    if !wants_frontmatter && !wants_document {
        return String::new();
    }
    let metadata_end = crate::converter::utility::preprocessing::metadata_prefix_end(parsed_source);
    let head_metadata = extract_head_metadata(dom.children(), parser, options, document_base_href, metadata_end);
    let frontmatter = wants_frontmatter
        .then(|| format_metadata_frontmatter(&head_metadata))
        .flatten()
        .unwrap_or_default();
    #[cfg(feature = "metadata")]
    populate_metadata_collector(dom, parser, metadata_collector, head_metadata, wants_document);
    frontmatter
}

#[cfg(feature = "visitor")]
fn check_visitor_error(ctx: &Context) -> Result<()> {
    let Some(err) = ctx.visitor_error.borrow().as_ref().cloned() else {
        return Ok(());
    };
    tracing::error!(
        target: "html_to_markdown::convert",
        error = %err,
        "visitor callback returned an error; aborting conversion"
    );
    Err(crate::error::ConversionError::Visitor(err))
}

#[cfg(not(feature = "visitor"))]
const fn check_visitor_error(_ctx: &Context) -> Result<()> {
    Ok(())
}

#[cfg(feature = "metadata")]
fn populate_metadata_collector(
    dom: &tl::VDom<'_>,
    parser: &tl::Parser<'_>,
    metadata_collector: Option<&crate::metadata::MetadataCollectorHandle>,
    head_metadata: std::collections::BTreeMap<String, String>,
    wants_document: bool,
) {
    if !wants_document {
        return;
    }
    let Some(collector) = metadata_collector else {
        return;
    };
    let (language, direction) = document_language_and_direction(dom.children(), parser);
    let mut collector = collector.borrow_mut();
    if !head_metadata.is_empty() {
        collector.set_head_metadata(head_metadata);
    }
    if let Some(language) = language {
        collector.set_language(language);
    }
    if let Some(direction) = direction {
        collector.set_text_direction(direction);
    }
}

#[cfg(feature = "metadata")]
fn document_language_and_direction(
    children: &[tl::NodeHandle],
    parser: &tl::Parser<'_>,
) -> (Option<String>, Option<String>) {
    let mut language = None;
    let mut direction = None;
    for child_handle in children {
        let Some(tl::Node::Tag(tag)) = child_handle.get(parser) else {
            continue;
        };
        if !matches!(tag.name().as_utf8_str().as_ref(), "html" | "body") {
            continue;
        }
        language = language.or_else(|| {
            tag.attributes()
                .get("lang")
                .flatten()
                .map(|value| value.as_utf8_str().to_string())
        });
        direction = direction.or_else(|| {
            tag.attributes()
                .get("dir")
                .flatten()
                .map(|value| value.as_utf8_str().to_string())
        });
    }
    (language, direction)
}

/// Wrap `output` at the wrap width, leaving the `frontmatter` it starts with as it is.
///
/// ~keep The frontmatter is YAML, not Markdown: wrapped, its closing `---` reads as a heading
/// ~keep underline and its keys join into one line that YAML cannot parse. The plain-text output
/// ~keep carries no frontmatter, so all of it is wrapped.
fn wrap_after_frontmatter(output: &str, frontmatter: &str, options: &ConversionOptions) -> String {
    let body_start = if output.starts_with(frontmatter) {
        frontmatter.len()
    } else {
        0
    };
    let mut wrapped = output[..body_start].to_owned();
    wrapped.push_str(&crate::wrapper::wrap_markdown(&output[body_start..], options));
    wrapped
}

/// Consume the structure collector and return the [`DocumentStructure`] and extracted
/// [`TableData`] entries.  Returns `(None, vec![])` when no collector was provided.
fn finish_structure_collector(
    sc: Option<StructureCollectorHandle>,
) -> (Option<crate::types::DocumentStructure>, Vec<crate::types::TableData>) {
    match sc.and_then(|rc| std::rc::Rc::try_unwrap(rc).ok()) {
        Some(cell) => {
            let (doc, tables) = cell.into_inner().finish();
            (Some(doc), tables)
        }
        None => (None, Vec::new()),
    }
}

/// Separate `node` from a block that ends right before it, so it does not continue that block's
/// last line (issues #570, #571, #583, #585).
///
/// ~keep Every block writes its own leading blank line, so a block after a list, a table or a
/// ~keep rule is separated whatever that block ended with. Inline content writes none, so it
/// ~keep continued the block's last line: a lazy continuation of the last list item, or one more
/// ~keep table row. In HTML, inline content after a block starts a block of its own, also when
/// ~keep the block sits at the end of an inline wrapper (`<span><ul>...</ul></span>text`).
/// ~keep Inside a list item the same holds, and `CommonMark` keeps a block in the item only when
/// ~keep its lines start at the item's content column: see `separate_in_list_item`.
fn separate_from_block(
    node: &tl::Node,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: HandlerContext<'_>,
) {
    let HandlerContext {
        options, ctx, dom_ctx, ..
    } = handler;
    if output.is_empty() || ctx.in_code {
        return;
    }
    // ~keep A heading or a link label converts inline, but in a cell the text after a block needs the break.
    // ~keep The strict mode keeps the white space of the source and writes no space of its own there.
    if ctx.convert_as_inline && !ctx.in_table_cell {
        if !crate::converter::utility::content::keeps_source_white_space(options, ctx) {
            separate_words_at_block_boundary(node, node_handle, parser, output, handler);
        }
        return;
    }
    if ctx.in_table_cell {
        // ~keep A block in a cell ends with no line end, so the cell break separates the inline
        // ~keep content after it (issue #645). A line break is a break of its own, and without
        // ~keep `br_in_tables` a text's leading space is the break. A kept HTML block is text in a cell.
        // ~keep A nested table adds no break: a table moved out of the cell ends its own line, and the
        // ~keep text after a table folded into the cell joins the table's last row.
        if is_inline_content(node, node_handle, parser, dom_ctx)
            && !is_line_break(node_handle, parser, dom_ctx)
            && (options.br_in_tables || !starts_with_space(node))
            && crate::converter::utility::siblings::previous_content_block(node_handle, parser, dom_ctx)
                .is_some_and(|block| block != "table" && !ctx.preserve_tags.contains(block))
        {
            crate::converter::main_helpers::separate_block_in_cell(output, options.br_in_tables);
        }
        return;
    }
    if ctx.in_list_item {
        if !parent_is_list(node_handle, parser, dom_ctx) {
            separate_in_list_item(node, node_handle, parser, output, handler);
        }
    } else if !ctx.in_list
        && ends_with_block_line_end(output)
        && !output.ends_with("\n\n")
        && is_inline_content(node, node_handle, parser, dom_ctx)
        && crate::converter::utility::siblings::previous_content_block(node_handle, parser, dom_ctx).is_some()
    {
        output.push('\n');
    }
}

/// Whether the last line of `output` holds nothing but indentation and list markers.
///
/// ~keep The backward scan stops at the first other character, so a long line costs nothing.
fn at_line_start(output: &str) -> bool {
    let before =
        output.trim_end_matches(|c: char| c.is_ascii_digit() || matches!(c, ' ' | '\t' | '-' | '*' | '+' | '.' | ')'));
    (before.is_empty() || before.ends_with('\n'))
        && (output[before.len()..].trim().is_empty() || crate::converter::list::utils::line_is_bare_list_marker(output))
}

/// Whether `output` ends with a line end that a block wrote: a lone line break is not one, since
/// the block before it wrote nothing.
fn ends_with_block_line_end(output: &str) -> bool {
    output.len() >= 2 && output.ends_with('\n')
}

/// Whether `node` is inline content: non-blank text or an inline element.
fn is_inline_content(node: &tl::Node, node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
    match node {
        tl::Node::Raw(bytes) => !bytes.as_utf8_str().trim().is_empty(),
        tl::Node::Tag(_) => dom_ctx
            .tag_info(node_handle.get_inner(), parser)
            .is_some_and(|info| is_inline_element(&info.name)),
        tl::Node::Comment(_) => false,
    }
}

/// Whether `node` is text that starts with whitespace.
fn starts_with_space(node: &tl::Node) -> bool {
    matches!(node, tl::Node::Raw(bytes) if bytes.as_bytes().first().is_some_and(u8::is_ascii_whitespace))
}

/// Whether `node_handle` is a `<br>` element.
fn is_line_break(node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
    dom_ctx
        .tag_info(node_handle.get_inner(), parser)
        .is_some_and(|info| info.name == "br")
}

/// Whether the parent of `node_handle` is a `<ul>` or `<ol>` (text or items between list items).
fn parent_is_list(node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
    dom_ctx
        .parent_of(node_handle.get_inner())
        .and_then(|parent_id| dom_ctx.tag_info(parent_id, parser))
        .is_some_and(|info| matches!(info.name.as_str(), "ul" | "ol"))
}

/// Walk `node_handle` with its subtree and write the Markdown to `output`.
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn walk_node(node_handle: &tl::NodeHandle, parser: &tl::Parser, output: &mut String, handler: HandlerContext<'_>) {
    walk_nodes(std::slice::from_ref(node_handle), parser, output, handler);
}

// ~keep Resolve spacing from final emitted content after callbacks; skipped nodes and erased wrappers owe no edge.
fn finish_media_boundary(
    output: &mut String,
    start: usize,
    boundary: &std::cell::Cell<super::context::MediaBoundaryState>,
    incoming: super::context::MediaBoundaryState,
    ctx: &Context,
) {
    let Some(chunk) = output.get(start..).filter(|chunk| !chunk.is_empty()) else {
        boundary.set(incoming);
        return;
    };
    let mut current = boundary.get();
    let first = chunk.chars().next();
    let edge = first
        .filter(|character| character.is_whitespace())
        .or(current.first_edge)
        .or(first);
    current.last_edge = current.last_edge.or_else(|| chunk.chars().next_back());
    let before = output.get(..start).unwrap_or_default();
    if (incoming.pending || current.first_is_media)
        && before.ends_with(|character: char| !character.is_whitespace())
        && !incoming.last_edge.is_some_and(|character| "([{".contains(character))
        && edge.is_some_and(|character| !character.is_whitespace() && !".,;:!?)]}".contains(character))
    {
        ctx.insert_media_space(output, start);
    }
    if incoming.first_edge.is_some() {
        current.first_is_media = incoming.first_is_media;
    }
    current.first_edge = incoming.first_edge.or(edge);
    boundary.set(current);
}

struct TagCapture<'a> {
    structure: super::structure_capture::ElementTextCapture,
    #[cfg(feature = "visitor")]
    visitor: Option<crate::converter::visitor_hooks::VisitorElementState<'a>>,
    #[cfg(feature = "visitor")]
    node_id: u32,
    #[cfg(feature = "visitor")]
    output_start: usize,
    #[cfg(feature = "visitor")]
    code_break_start: Option<usize>,
    #[cfg(not(feature = "visitor"))]
    marker: std::marker::PhantomData<&'a ()>,
}

/// How an element starts.
enum Begun<'a> {
    /// The element is complete: skipped, or written whole.
    Complete,
    /// The tag is dropped and the children are walked in its place.
    Children,
    /// The handler of the element runs, and `finish_tag` ends the element.
    Open(TagCapture<'a>),
}

fn begin_tag<'a>(
    node_handle: &tl::NodeHandle,
    tag: &'a tl::HTMLTag<'a>,
    parser: &'a tl::Parser<'a>,
    output: &mut String,
    handler: HandlerContext<'_>,
    dom_ctx: &'a DomContext,
) -> Begun<'a> {
    let options = handler.options;
    let depth = handler.depth;
    let ctx = handler.ctx;
    let tag_name = normalized_node_tag_name(node_handle, tag, parser, dom_ctx);
    let tag_name = tag_name.as_ref();
    #[cfg(feature = "visitor")]
    let visitor_element_state = if ctx.skip_visitor_hooks || ctx.visitor.is_none() {
        None
    } else {
        let state =
            crate::converter::visitor_hooks::build_visitor_element_state(tag_name, node_handle, parser, dom_ctx);
        if start_visitor_element(&state, node_handle, tag, output, handler, tag_name).is_break() {
            return Begun::Complete;
        }
        Some(state)
    };

    match skip_or_render_tag(
        tag_name,
        node_handle,
        tag,
        parser,
        output,
        HandlerContext::new(options, ctx, depth, dom_ctx),
    ) {
        TagRoute::Handler => {}
        TagRoute::Written => return Begun::Complete,
        TagRoute::Children => return Begun::Children,
    }
    collect_document_attributes(tag_name, tag, ctx);
    let structure_capture = super::structure_capture::begin_element(tag_name, tag, ctx);
    #[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
    let element_output_start = output.len();
    strip_breaks_before_block(tag_name, output, options, ctx);

    Begun::Open(TagCapture {
        structure: structure_capture,
        #[cfg(feature = "visitor")]
        visitor: visitor_element_state,
        #[cfg(feature = "visitor")]
        node_id: node_handle.get_inner(),
        #[cfg(feature = "visitor")]
        output_start: element_output_start,
        #[cfg(feature = "visitor")]
        code_break_start: ctx.inline_code_breaks.as_ref().map(|(_, breaks)| breaks.borrow().len()),
        #[cfg(not(feature = "visitor"))]
        marker: std::marker::PhantomData,
    })
}

#[cfg(feature = "visitor")]
pub(super) fn start_visitor_element(
    state: &crate::converter::visitor_hooks::VisitorElementState<'_>,
    node_handle: &tl::NodeHandle,
    tag: &tl::HTMLTag<'_>,
    output: &mut String,
    handler: HandlerContext<'_>,
    tag_name: &str,
) -> std::ops::ControlFlow<()> {
    use crate::converter::visitor_hooks::{VisitAction, handle_visitor_element_start};
    use std::ops::ControlFlow;

    let (options, ctx, dom_ctx) = (handler.options, handler.ctx, handler.dom_ctx);
    let Some(ref visitor_handle) = ctx.visitor else {
        return ControlFlow::Continue(());
    };
    let visitor_output_start = output.len();
    let action = handle_visitor_element_start(visitor_handle, tag_name, tag, state, output, handler.depth);
    let strict = options.whitespace_mode == crate::options::WhitespaceMode::Strict;

    match action {
        VisitAction::Continue => {
            if strict && !ctx.excluded_node_ids.contains(&node_handle.get_inner()) {
                dom_ctx.record_absent_breaks(node_handle.get_inner(), false);
            }
            ControlFlow::Continue(())
        }
        VisitAction::Skip => {
            if strict {
                dom_ctx.record_absent_breaks(node_handle.get_inner(), true);
            }
            ControlFlow::Break(())
        }
        VisitAction::Custom => {
            if let Some(replacement) = output.get(visitor_output_start..) {
                capture_custom_start(handler, tag_name, tag, node_handle.get_inner(), replacement);
            }
            ControlFlow::Break(())
        }
        VisitAction::Error => ControlFlow::Break(()),
    }
}

#[cfg(feature = "visitor")]
fn capture_custom_start(
    handler: HandlerContext<'_>,
    tag_name: &str,
    tag: &tl::HTMLTag<'_>,
    node_id: u32,
    replacement: &str,
) {
    if handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict
        && replacement.trim_matches([' ', '\t']).is_empty()
    {
        handler.dom_ctx.record_absent_breaks(node_id, true);
    }
    collect_document_attributes(tag_name, tag, handler.ctx);
    super::structure_capture::replace_element_at_start(tag_name, tag, handler.ctx, replacement);
}

fn finish_tag(
    capture: TagCapture<'_>,
    tag_name: &str,
    tag: &tl::HTMLTag<'_>,
    output: &mut String,
    handler: HandlerContext<'_>,
    stop: bool,
) {
    #[cfg(feature = "visitor")]
    if !stop {
        let safe_start =
            crate::converter::utility::content::floor_char_boundary(output, capture.output_start.min(output.len()));
        if let Some(action) =
            super::structure_capture::handle_visitor_end(super::structure_capture::VisitorEndCapture {
                state: capture.visitor.as_ref(),
                tag_name,
                tag,
                output,
                element_output_start: capture.output_start,
                ctx: handler.ctx,
                depth: handler.depth,
            })
        {
            use crate::converter::visitor_hooks::VisitAction;
            // ~keep A direct BR can be erased after its line-break callback emitted it (#921).
            // ~keep Restore its checkpoint rather than counting replacement source whitespace.
            if tag_name == "br"
                && matches!(action, VisitAction::Skip | VisitAction::Custom)
                && let Some(((owner, breaks), before)) =
                    handler.ctx.inline_code_breaks.as_ref().zip(capture.code_break_start)
                && handler.dom_ctx.parent_of(capture.node_id) == Some(*owner)
            {
                breaks.borrow_mut().truncate(before);
            }
            // ~keep Only replacing leading output invalidates a label's first-button boundary.
            if matches!(action, VisitAction::Skip | VisitAction::Custom)
                && output.get(..safe_start).is_some_and(|before| before.trim().is_empty())
            {
                handler.ctx.button_wrote.set(false);
            }
            if handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict
                && (matches!(action, VisitAction::Skip)
                    || (matches!(action, VisitAction::Custom)
                        && output
                            .get(safe_start..)
                            .is_some_and(|replacement| replacement.trim_matches([' ', '\t']).is_empty())))
            {
                handler.dom_ctx.record_absent_breaks(capture.node_id, true);
            }
        }
    }
    #[cfg(not(feature = "visitor"))]
    let _ = (output, stop);
    super::structure_capture::finish_element(capture.structure, tag_name, tag, handler.ctx);
}

fn normalized_node_tag_name<'a>(
    node_handle: &tl::NodeHandle,
    tag: &'a tl::HTMLTag<'a>,
    parser: &'a tl::Parser<'a>,
    dom_ctx: &'a DomContext,
) -> Cow<'a, str> {
    match dom_ctx.tag_info(node_handle.get_inner(), parser) {
        Some(info) => Cow::Borrowed(info.name.as_str()),
        None => normalized_tag_name(tag.name().as_utf8_str()),
    }
}

fn djot_context(
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    tag_name: &str,
    handler: HandlerContext<'_>,
) -> Option<Context> {
    let ctx = handler.ctx;
    (handler.options.output_format == OutputFormat::Djot
        && (ctx.djot_rule_like_text.is_none() || is_block_level_element(tag_name)))
    .then(|| Context {
        djot_rule_like_text: Some(crate::converter::context::DjotRuleLikeText::new(djot_rule_like_lines(
            *node_handle,
            parser,
            handler.dom_ctx,
        ))),
        ..ctx.clone()
    })
}

/// What the walk does with an element before any handler runs.
enum TagRoute {
    /// The handler of the element runs.
    Handler,
    /// The element is complete: skipped, or written as HTML.
    Written,
    /// The tag is dropped and the children are walked in its place.
    Children,
}

fn skip_or_render_tag(
    tag_name: &str,
    node_handle: &tl::NodeHandle,
    tag: &tl::HTMLTag<'_>,
    parser: &tl::Parser,
    output: &mut String,
    handler: HandlerContext<'_>,
) -> TagRoute {
    if should_skip_tag(tag_name, node_handle, tag, parser, handler) {
        if handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict
            && handler.ctx.excluded_node_ids.contains(&node_handle.get_inner())
        {
            handler.dom_ctx.record_absent_breaks(node_handle.get_inner(), true);
        }
        if handler.ctx.inline_code_links.is_none() {
            trim_trailing_whitespace(output);
        }
        return TagRoute::Written;
    }
    if handler.ctx.strip_tags.contains(tag_name) {
        return TagRoute::Children;
    }
    let preserved_menu_placeholder = tag_name == "ul"
        && handler.ctx.preserve_tags.contains("menu")
        && tag.attributes().get(PRESERVED_MENU_ATTRIBUTE).is_some();
    if (handler.ctx.preserve_tags.contains(tag_name) || preserved_menu_placeholder)
        && render_preserved_tag(
            tag_name,
            node_handle,
            parser,
            output,
            handler,
            preserved_menu_placeholder,
        )
    {
        TagRoute::Written
    } else {
        TagRoute::Handler
    }
}

pub(super) fn should_skip_tag(
    tag_name: &str,
    node_handle: &tl::NodeHandle,
    tag: &tl::HTMLTag<'_>,
    parser: &tl::Parser,
    handler: HandlerContext<'_>,
) -> bool {
    #[cfg(feature = "visitor")]
    let visitor_is_active = handler.ctx.visitor.is_some() && !handler.ctx.skip_visitor_hooks;
    #[cfg(not(feature = "visitor"))]
    let visitor_is_active = false;
    (!visitor_is_active
        && should_drop_for_preprocessing(
            tag_name,
            tag,
            handler.options,
            tag_name == "header" && is_page_header(node_handle, parser, handler.dom_ctx),
        ))
        || (!handler.ctx.excluded_node_ids.is_empty()
            && handler.ctx.excluded_node_ids.contains(&node_handle.get_inner()))
}

fn render_preserved_tag(
    tag_name: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: HandlerContext<'_>,
    preserved_menu_placeholder: bool,
) -> bool {
    let ctx = handler.ctx;
    let starts_line = at_line_start(output);
    let mut html = serialize_tag_to_html(node_handle, parser);
    if preserved_menu_placeholder {
        html = restore_preserved_menu_elements(&html).into_owned();
    }
    let custom_element_starts_block =
        ctx.in_list_item && tag_name.contains('-') && !crate::converter::list::utils::line_is_bare_list_marker(output);
    let opens_html_block = (starts_line || (preserved_menu_placeholder && ctx.in_list_item))
        && !ctx.in_marker_text()
        && !ctx.in_table_cell
        && !ctx.convert_as_inline
        && !ctx.in_code
        && (custom_element_starts_block || crate::converter::utility::escaping::opens_block(html.trim_start()));
    // ~keep Custom elements are not in the converter's block-tag allowlist, so
    // ~keep `separate_from_block` cannot put a preserved custom block at the item's
    // ~keep content column. A hyphenated HTML name identifies that custom-element
    // ~keep case at the preservation boundary (issue #658).
    if opens_html_block && ctx.in_list_item {
        crate::converter::list::utils::start_block_in_list_item(output, ctx, handler.options);
    }
    output.push_str(&html);
    // ~keep An HTML block ends only at a blank line, so one follows it (issue #655).
    if opens_html_block {
        output.push_str("\n\n");
    }
    true
}

#[cfg(feature = "metadata")]
fn collect_document_attributes(tag_name: &str, tag: &tl::HTMLTag<'_>, ctx: &Context) {
    if !matches!(tag_name, "html" | "head" | "body") || !ctx.metadata_wants.document {
        return;
    }
    let Some(collector) = ctx.metadata_collector.as_ref() else {
        return;
    };
    let mut collector = collector.borrow_mut();
    if let Some(lang) = tag.attributes().get("lang").flatten() {
        collector.set_language(lang.as_utf8_str().to_string());
    }
    if let Some(dir) = tag.attributes().get("dir").flatten() {
        collector.set_text_direction(dir.as_utf8_str().to_string());
    }
}

#[cfg(not(feature = "metadata"))]
const fn collect_document_attributes(_tag_name: &str, _tag: &tl::HTMLTag<'_>, _ctx: &Context) {}

/// ~keep Block dispatch is where a trailing hard-break run becomes knowably
/// ineffective; container endings handle the no-following-sibling case themselves.
fn strip_breaks_before_block(tag_name: &str, output: &mut String, options: &ConversionOptions, ctx: &Context) {
    if !ctx.in_code && options.newline_style == NewlineStyle::Backslash && is_block_level_element(tag_name) {
        strip_trailing_backslash_breaks(output, ctx.block_content_start);
    }
}

fn djot_rule_like_lines(node_handle: tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> Vec<bool> {
    let mut text = String::with_capacity(64);
    let mut stack = vec![node_handle];
    while let Some(handle) = stack.pop() {
        match handle.get(parser) {
            Some(tl::Node::Raw(bytes)) => {
                let raw = bytes.as_utf8_str();
                text.push_str(crate::text::decode_html_entities_cow(raw.as_ref()).as_ref());
            }
            Some(tl::Node::Tag(tag)) => {
                if dom_ctx.tag_name_for(handle, parser).as_deref() == Some("br") {
                    text.push('\n');
                } else if let Some(children) = dom_ctx.children_of(handle.get_inner()) {
                    stack.extend(children.iter().rev().copied());
                } else {
                    let mut children: Vec<_> = tag.children().top().iter().copied().collect();
                    children.reverse();
                    stack.extend(children);
                }
            }
            Some(tl::Node::Comment(_)) | None => {}
        }
    }
    text.split('\n').map(crate::text::is_djot_rule_like).collect()
}