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
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
//! Text node processing for HTML to Markdown conversion.
//!
//! Handles raw text nodes with:
//! - HTML entity decoding
//! - Whitespace normalization and stripping
//! - Text escaping with configurable escape modes
//! - Visitor callbacks (when feature enabled)
//! - List item indentation

use std::borrow::Cow;

use crate::converter::block::container::HandlerContext;
use crate::converter::dom_context::DomContext;
use crate::converter::main_helpers::{hard_break_marker, is_inline_element};
use crate::converter::utility::content::{NextElement, ZERO_WIDTH_SPACE, line_end_before_element};
use crate::converter::utility::siblings::{
    FollowingContent, br_follows_enclosing_elements, content_starts_with_block, following_sibling_content,
    get_next_sibling_tag, get_previous_sibling_tag, next_sibling_is_inline_tag, text_place, zero_width_space_follows,
};
use crate::converter::utility::white_space::{
    TextClass, cell_text, classify_text, edges, is_blank, is_collapsible, space_is_owed, starts_with_unicode_space,
    unicode_space_is_kept, visible, with_line_feeds,
};
use crate::text;
#[cfg(feature = "visitor")]
use crate::visitor::EMPTY_ATTRS;

type Context = crate::converter::Context;

/// Process a raw text node during HTML to Markdown conversion.
///
/// Handles:
/// - HTML entity decoding
/// - Whitespace normalization and stripping
/// - Text escaping with configurable escape modes
/// - Visitor callbacks (when feature enabled)
/// - List item indentation
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn process_text_node(
    raw: &str,
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    output: &mut String,
    handler: HandlerContext<'_>,
) {
    TextProcessor {
        node_handle,
        parser,
        output,
        handler,
    }
    .process(raw);
}

/// Whether white space is written at the start of a fresh block, where it is no space.
/// `was_fresh` is the fresh block flag of the context before the node wrote anything.
pub const fn is_fresh_block_start(ctx: &Context, was_fresh: bool) -> bool {
    was_fresh && !ctx.convert_as_inline && !ctx.in_table_cell && !ctx.in_list_item
}

struct WhitespaceFacts {
    had_newlines: bool,
    has_double_newline: bool,
    was_fresh_block_start: bool,
}

struct ProcessedText {
    output: String,
    semantic: Option<String>,
}

impl ProcessedText {
    fn same(text: String, capture_semantic: bool) -> Self {
        Self {
            semantic: capture_semantic.then(|| text.clone()),
            output: text,
        }
    }
}

struct TextProcessor<'dom, 'output, 'handler> {
    node_handle: &'dom tl::NodeHandle,
    parser: &'dom tl::Parser<'dom>,
    output: &'output mut String,
    handler: HandlerContext<'handler>,
}

impl TextProcessor<'_, '_, '_> {
    fn process(&mut self, raw: &str) {
        let mut decoded = text::decode_html_entities_cow(raw);
        if !self.handler.ctx.in_code {
            decoded = with_line_feeds(decoded);
        }
        if decoded.is_empty() {
            return;
        }
        let facts = WhitespaceFacts {
            had_newlines: decoded.contains('\n'),
            has_double_newline: decoded.contains("\n\n") || decoded.contains("\r\n\r\n"),
            was_fresh_block_start: self.handler.ctx.at_fresh_block_start.get(),
        };
        if self.handler.options.strip_newlines && (decoded.contains('\r') || decoded.contains('\n')) {
            decoded = Cow::Owned(decoded.replace(['\r', '\n'], " "));
        }
        if is_blank(&decoded) {
            let output_start = self.output.len();
            self.emit_whitespace(decoded.as_ref(), &facts);
            if crate::converter::structure_capture::is_text_capture_active(self.handler.ctx) {
                self.append_semantic_output(output_start);
            }
            return;
        }
        let decoded = self.without_line_end_before_zero_width_space(decoded);
        let escape_asterisks = self.escape_asterisks();
        let capture_semantic = crate::converter::structure_capture::is_text_capture_active(self.handler.ctx);
        let processed = self.process_content(decoded, escape_asterisks, facts.was_fresh_block_start, capture_semantic);
        #[cfg(feature = "visitor")]
        let Some(final_text) = self.apply_visitor(processed) else {
            return;
        };
        #[cfg(not(feature = "visitor"))]
        let final_text = processed;
        self.emit_processed(&final_text.output);
        if let Some(semantic) = final_text.semantic.as_deref() {
            crate::converter::structure_capture::append_text(self.handler.ctx, semantic);
        }
    }

    /// Removes the white space with a line end that `text` ends with when a zero-width space
    /// follows it.
    ///
    /// ~keep A zero-width space is a place where a line can break, not a space: a browser
    /// ~keep drops the line end beside it, so `long\n<span></span>&#8203;word` is one word.
    fn without_line_end_before_zero_width_space<'text>(&self, text: Cow<'text, str>) -> Cow<'text, str> {
        if self.handler.ctx.in_code || self.handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict {
            return text;
        }
        let TextClass::Text {
            core,
            suffix: Some(suffix),
            ..
        } = classify_text(text.as_ref())
        else {
            return text;
        };
        // ~keep The segment break goes when a zero-width space is on either side of it: the
        // ~keep last character of this text, or the first character after it.
        let after =
            zero_width_space_follows(self.node_handle, self.parser, self.handler.dom_ctx).then_some(ZERO_WIDTH_SPACE);
        if suffix.writes_space(core.chars().last(), after) {
            return text;
        }
        Cow::Owned(text.trim_end_matches(is_collapsible).to_string())
    }

    fn escape_asterisks(&self) -> bool {
        self.handler.options.escape_asterisks
            || self
                .handler
                .ctx
                .djot_rule_like_text
                .as_ref()
                .is_some_and(crate::converter::context::DjotRuleLikeText::current)
    }

    fn emit_whitespace(&mut self, value: &str, facts: &WhitespaceFacts) {
        let ctx = self.handler.ctx;
        if ctx.in_code {
            self.output.push_str(value);
            return;
        }
        if self.at_paragraph_buffer_start() {
            return;
        }
        if self.handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict {
            self.emit_strict_whitespace(value, facts.has_double_newline);
            return;
        }
        if self.between_adjacent_images() {
            self.output.push(if facts.had_newlines { '\n' } else { ' ' });
            return;
        }
        if self.at_fresh_block_start(facts.was_fresh_block_start) {
            return;
        }
        if facts.had_newlines {
            self.emit_newline_whitespace(value, facts.was_fresh_block_start);
        } else if !matches!(classify_text(value), TextClass::WhiteSpaceOnly(_)) {
            // ~keep A blank text that holds a no-break space is written, whatever white space
            // ~keep of the source is before it: a browser shows `one <span>&nbsp;</span>two`
            // ~keep with both spaces. Only its own collapsible white space joins a space
            // ~keep already written (rule 4). `<li>&nbsp;</li>` is a block start and drops it.
            let kept = if space_is_owed(self.output) {
                value
            } else {
                value.trim_start_matches(is_collapsible)
            };
            self.output.push_str(kept);
        } else if !self.at_block_line_start() && !self.output.ends_with(' ') && !self.after_hard_break() {
            // ~keep A space-only text between two blocks of a quote (`<p>8</p> <p>0</p>`) is a
            // ~keep line of one space, as before this change: only the block's own buffer
            // ~keep refuses a space at a line start. A line that a `<br>` ended starts the next
            // ~keep one in a list item's own buffer too: the text after it writes the indent.
            self.output.push(' ');
        }
    }

    fn after_hard_break(&self) -> bool {
        self.output.ends_with(hard_break_marker(self.handler.options))
    }

    fn at_block_line_start(&self) -> bool {
        std::ptr::from_ref::<String>(self.output) as usize == self.handler.ctx.block_output_ptr
            && (self.output.is_empty() || self.output.ends_with('\n'))
    }

    fn between_adjacent_images(&self) -> bool {
        get_previous_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx) == Some("img")
            && get_next_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx) == Some("img")
    }

    fn emit_strict_whitespace(&mut self, value: &str, has_double_newline: bool) {
        let ctx = self.handler.ctx;
        if ctx.convert_as_inline || ctx.in_table_cell || ctx.in_list_item {
            self.output.push_str(value);
        } else if has_double_newline {
            if !self.output.ends_with("\n\n") {
                self.output.push('\n');
            }
        } else {
            self.output.push_str(value);
        }
    }

    fn at_paragraph_buffer_start(&self) -> bool {
        self.handler.ctx.in_paragraph
            && std::ptr::from_ref::<String>(self.output) as usize == self.handler.ctx.block_output_ptr
            && self.output.len() == self.handler.ctx.block_content_start
    }

    const fn at_fresh_block_start(&self, was_fresh: bool) -> bool {
        is_fresh_block_start(self.handler.ctx, was_fresh)
    }

    /// Writes the one space of a blank text that holds a line end, where the rule owes it:
    /// before an inline sibling, or at the end of an inline element that a word follows. A
    /// no-break space in such a text is written as it is when it is the only one.
    fn emit_newline_whitespace(&mut self, value: &str, was_fresh: bool) {
        if self.output.is_empty() {
            if !was_fresh && self.handler.ctx.inline_depth > 0 {
                self.output.push(' ');
            }
            return;
        }
        if self.output.ends_with("\n\n") {
            return;
        }
        let next_tag = get_next_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx);
        // ~keep An option that no select list holds is text of its line, as a select list is:
        // ~keep the line end before it is one space.
        let before_bare_option = !self.handler.ctx.in_option_list && matches!(next_tag, Some("option" | "optgroup"));
        if !before_bare_option && next_tag.is_some_and(|next_tag| !self.next_tag_is_inline_for_whitespace(next_tag)) {
            return;
        }
        let mut kept = value.chars().filter(|character| !is_collapsible(*character));
        let first_kept = kept.next();
        let holds_more = kept.next().is_some();
        if let (Some(character), false) = (first_kept, holds_more) {
            self.output.push(character);
            return;
        }
        let needs_space = next_tag.is_some()
            || holds_more
            || newline_span_needs_separating_space(
                self.node_handle,
                self.parser,
                self.handler.dom_ctx,
                self.handler.ctx.in_option_list,
            );
        if needs_space && space_is_owed(self.output) {
            self.output.push(' ');
        }
    }

    fn process_content(
        &self,
        value: Cow<'_, str>,
        escape_asterisks: bool,
        was_fresh: bool,
        capture_semantic: bool,
    ) -> ProcessedText {
        let ctx = self.handler.ctx;
        if ((ctx.in_code && !ctx.in_code_block) || ctx.in_ruby) && ctx.in_table_cell {
            return ProcessedText::same(
                text::fold_cell_line_breaks_verbatim_cow(value.as_ref()).into_owned(),
                capture_semantic,
            );
        }
        if ctx.in_code && !ctx.in_code_block {
            return ProcessedText::same(
                text::fold_cell_line_breaks_verbatim_cow(value.as_ref()).into_owned(),
                capture_semantic,
            );
        }
        if ctx.in_code || ctx.in_ruby {
            return ProcessedText::same(value.into_owned(), capture_semantic);
        }
        if ctx.in_table_cell {
            return self.process_table_cell(value.as_ref(), escape_asterisks, capture_semantic);
        }
        if self.handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict {
            return self.process_strict(value.as_ref(), escape_asterisks, capture_semantic);
        }
        self.process_normalized(value.as_ref(), escape_asterisks, was_fresh, capture_semantic)
    }

    fn process_table_cell(&self, value: &str, escape_asterisks: bool, capture_semantic: bool) -> ProcessedText {
        let options = self.handler.options;
        let normalized = if options.whitespace_mode == crate::options::WhitespaceMode::Normalized {
            let collapsed = cell_text(value);
            // ~keep White space after a space is the same run of white space, as in `skip_prefix`.
            match collapsed.strip_prefix(' ') {
                Some(rest) if !space_is_owed(self.output) && !self.keeps_unicode_space(value) => {
                    Cow::Owned(rest.to_string())
                }
                _ => collapsed,
            }
        } else {
            text::fold_cell_line_breaks_verbatim_cow(value)
        };
        let mut output = String::with_capacity(normalized.len());
        text::escape_into(
            &mut output,
            normalized.as_ref(),
            options.escape_misc,
            escape_asterisks,
            options.escape_underscores,
            options.escape_ascii,
        );
        if !options.escape_misc && !options.escape_ascii && output.contains('|') {
            output = output.replace('|', r"\|");
        }
        let output = crate::converter::utility::escaping::escape_djot_table_cell_literal(
            &output,
            options.output_format,
            self.handler.ctx.in_table_cell,
        )
        .into_owned();
        ProcessedText {
            output,
            semantic: capture_semantic.then(|| normalized.into_owned()),
        }
    }

    fn process_strict(&self, value: &str, escape_asterisks: bool, capture_semantic: bool) -> ProcessedText {
        let follows_break = get_next_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx) == Some("br")
            || br_follows_enclosing_elements(self.node_handle.get_inner(), self.parser, self.handler.dom_ctx);
        let trimmed_end = follows_break
            .then(|| strip_single_trailing_line_ending(value))
            .flatten()
            .unwrap_or(value);
        let preceded_by_break = get_previous_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx)
            == Some("br")
            || (self.handler.ctx.inline_buffer_after_hard_break && self.output.trim_matches([' ', '\t']).is_empty());
        let strict = preceded_by_break
            .then(|| strip_single_leading_line_ending(trimmed_end))
            .flatten()
            .unwrap_or(trimmed_end);
        let strict = if self.at_paragraph_buffer_start() {
            strict.trim_start_matches([' ', '\t', '\r', '\n'])
        } else {
            strict
        };
        let options = self.handler.options;
        let output = text::escape(
            strict,
            options.escape_misc,
            escape_asterisks,
            options.escape_underscores,
            options.escape_ascii,
        )
        .into_owned();
        ProcessedText {
            output,
            semantic: capture_semantic.then(|| strict.to_string()),
        }
    }

    fn process_normalized(
        &self,
        value: &str,
        escape_asterisks: bool,
        was_fresh: bool,
        capture_semantic: bool,
    ) -> ProcessedText {
        let has_double_newline = value.contains("\n\n") || value.contains("\r\n\r\n");
        let trailing_single_newline = value.ends_with('\n') && !value.ends_with("\n\n") && !value.ends_with("\r\n\r\n");
        let (prefix, suffix) = edges(value);
        let line_indent = (self.output.ends_with(hard_break_marker(self.handler.options))
            && starts_with_unicode_space(value))
        .then(|| crate::converter::utility::white_space::unicode_line_indent(value));
        let prefix = line_indent.as_deref().unwrap_or(prefix);
        let core = visible(value);
        let mut output = String::with_capacity(prefix.len() + core.len() + suffix.len() + 2);
        let mut semantic = capture_semantic.then(|| String::with_capacity(output.capacity()));
        if (line_indent.is_some() || !self.skip_prefix(prefix, value, was_fresh)) && !prefix.is_empty() {
            output.push_str(prefix);
            if let Some(semantic) = semantic.as_mut() {
                semantic.push_str(prefix);
            }
        }
        let options = self.handler.options;
        output.push_str(&text::escape(
            core.as_ref(),
            options.escape_misc,
            escape_asterisks,
            options.escape_underscores,
            options.escape_ascii,
        ));
        if let Some(semantic) = semantic.as_mut() {
            semantic.push_str(core.as_ref());
        }
        if !suffix.is_empty() {
            output.push_str(suffix);
            if let Some(semantic) = semantic.as_mut() {
                semantic.push_str(suffix);
            }
        } else if trailing_single_newline {
            let output_end = output.len();
            self.append_trailing_line_ending(&mut output, has_double_newline);
            if let Some(semantic) = semantic.as_mut() {
                semantic.push_str(&output[output_end..]);
            }
        }
        ProcessedText { output, semantic }
    }

    fn skip_prefix(&self, prefix: &str, value: &str, was_fresh: bool) -> bool {
        is_fresh_block_start(self.handler.ctx, was_fresh)
            || self.output.ends_with("\n\n")
            || ["* ", "- ", ". ", "] "]
                .iter()
                .any(|ending| self.output.ends_with(ending))
            // ~keep White space after a space is the same run of white space, whatever lies
            // ~keep between the two: an element that wrote nothing is no word. A Unicode space
            // ~keep is no such white space.
            || (!space_is_owed(self.output) && prefix == " " && !self.keeps_unicode_space(value))
    }

    // ~keep A Unicode prefix after an empty block is content beside a list's structural indent (#868).
    fn keeps_list_block_prefix(&self) -> bool {
        if !self.handler.ctx.in_list_item || !self.output.trim_end_matches([' ', '\t']).ends_with('\n') {
            return false;
        }
        let dom_ctx = self.handler.dom_ctx;
        let previous = dom_ctx
            .prev_tag_map
            .get(self.node_handle.get_inner() as usize)
            .and_then(std::cell::OnceCell::get)
            .copied()
            .flatten();
        previous.is_some_and(|previous| {
            dom_ctx
                .tag_info(previous, self.parser)
                .is_some_and(|info| info.name == "span")
                && !dom_ctx.holds_text(previous, self.parser)
                && matches!(
                    crate::converter::utility::siblings::previous_content_block_through(
                        self.node_handle,
                        self.parser,
                        dom_ctx,
                        crate::converter::utility::white_space::writes_in_text_flow,
                    ),
                    Some(
                        "p" | "div"
                            | "table"
                            | "h1"
                            | "h2"
                            | "h3"
                            | "h4"
                            | "h5"
                            | "h6"
                            | "blockquote"
                            | "pre"
                            | "section"
                            | "article"
                            | "figure"
                            | "dl"
                            | "aside"
                            | "footer"
                            | "main"
                            | "details"
                            | "figcaption"
                            | "address"
                            | "fieldset"
                            | "center"
                            | "dialog"
                            | "hgroup"
                            | "header"
                    )
                )
        })
    }

    /// Whether `value` starts with a Unicode space that is written after the space the output
    /// ends with.
    fn keeps_unicode_space(&self, value: &str) -> bool {
        self.output.ends_with(' ')
            && starts_with_unicode_space(value)
            && (self.keeps_list_block_prefix()
                || unicode_space_is_kept(
                    self.output,
                    text_place(
                        *self.node_handle,
                        self.parser,
                        self.handler.dom_ctx,
                        self.handler.ctx.in_table_cell,
                    ),
                ))
    }

    fn append_trailing_line_ending(&self, output: &mut String, has_double_newline: bool) {
        let safe_start = crate::converter::utility::content::floor_char_boundary(
            self.output,
            self.handler.ctx.block_content_start.min(self.output.len()),
        );
        if self.output[safe_start..].ends_with("\n\n") {
            return;
        }
        if has_double_newline {
            output.push('\n');
            return;
        }
        if let Some(next_tag) = get_next_sibling_tag(self.node_handle, self.parser, self.handler.dom_ctx) {
            self.append_before_next_tag(output, next_tag);
        } else if self.handler.ctx.inline_depth > 0
            || self.handler.ctx.convert_as_inline
            || self.handler.ctx.in_paragraph
        {
            output.push(' ');
        } else if !br_follows_enclosing_elements(self.node_handle.get_inner(), self.parser, self.handler.dom_ctx) {
            output.push('\n');
        }
    }

    fn append_before_next_tag(&self, output: &mut String, next_tag: &str) {
        // ~keep Only a line break ends the line: before any other element the line end of the
        // ~keep source is white space between two words, also when the element is empty (#778).
        if next_tag == "br" {
            return;
        }
        let ctx = self.handler.ctx;
        let in_running_text = ctx.inline_depth > 0 || ctx.convert_as_inline || ctx.in_paragraph;
        let dom_ctx = self.handler.dom_ctx;
        let starts_with_block = dom_ctx
            .next_tag_id(self.node_handle.get_inner(), self.parser)
            .is_some_and(|next| content_starts_with_block(next, self.parser, dom_ctx));
        let next = NextElement::new(self.next_tag_is_inline_for_whitespace(next_tag), starts_with_block);
        output.push(line_end_before_element(in_running_text, next));
    }

    fn next_tag_is_inline_for_whitespace(&self, next_tag: &str) -> bool {
        if next_tag != "datalist" {
            return is_inline_element(next_tag);
        }
        let dom_ctx = self.handler.dom_ctx;
        let Some(next) = dom_ctx.next_tag_id(self.node_handle.get_inner(), self.parser) else {
            return false;
        };
        if self.handler.ctx.excluded_node_ids.contains(&next) {
            return false;
        }
        #[cfg(feature = "visitor")]
        if self.handler.ctx.visitor.is_some() && !self.handler.ctx.skip_visitor_hooks {
            return true;
        }
        if let Some(cached) = dom_ctx.datalist_content_cache.borrow().get(&next).copied() {
            return cached;
        }
        // ~keep This local classification must not change HTML repair. Cache by list so
        // ~keep adjacent text/comment fragments never rescan the same option subtree.
        let has_content = self.datalist_may_write_content(next);
        dom_ctx.datalist_content_cache.borrow_mut().insert(next, has_content);
        has_content
    }

    fn datalist_may_write_content(&self, node_id: u32) -> bool {
        let dom_ctx = self.handler.dom_ctx;
        let options = self.handler.options;
        let max_depth = crate::converter::main_helpers::effective_max_depth(options);
        let mut stack = vec![(tl::NodeHandle::new(node_id), self.handler.depth)];
        while let Some((handle, depth)) = stack.pop() {
            if depth >= max_depth || self.handler.ctx.excluded_node_ids.contains(&handle.get_inner()) {
                continue;
            }
            #[cfg(test)]
            DATALIST_NODE_READS.with(|reads| reads.set(reads.get() + 1));
            match handle.get(self.parser) {
                Some(tl::Node::Raw(raw)) => {
                    let raw_text = raw.as_utf8_str();
                    let decoded = text::decode_html_entities_cow(raw_text.as_ref());
                    if !decoded.trim().is_empty() {
                        return true;
                    }
                }
                Some(tl::Node::Tag(tag)) => {
                    let Some(info) = dom_ctx.tag_info(handle.get_inner(), self.parser) else {
                        continue;
                    };
                    let name = info.name.as_str();
                    if crate::converter::main::should_skip_tag(name, &handle, tag, self.parser, self.handler) {
                        continue;
                    }
                    if options
                        .preserve_tags
                        .iter()
                        .any(|preserved| name.eq_ignore_ascii_case(preserved))
                    {
                        return true;
                    }
                    if matches!(name, "script" | "style" | "template" | "noscript") {
                        continue;
                    }
                    // ~keep Media may write without text nodes; default inputs write nothing.
                    if matches!(name, "img" | "svg" | "math" | "iframe" | "audio" | "video") {
                        return true;
                    }
                    if let Some(children) = dom_ctx.children_of(handle.get_inner()) {
                        stack.extend(children.iter().map(|child| (*child, depth + 1)));
                    }
                }
                _ => {}
            }
        }
        false
    }

    #[cfg(feature = "visitor")]
    fn apply_visitor(&self, processed: ProcessedText) -> Option<ProcessedText> {
        use crate::visitor::{NodeContext, NodeType, VisitResult};

        let Some(visitor_handle) = self.handler.ctx.visitor.as_ref() else {
            return Some(processed);
        };
        let node_id = self.node_handle.get_inner();
        let parent_tag = self.handler.dom_ctx.parent_tag_name(node_id, self.parser);
        let node_ctx = NodeContext::with_borrowed_attributes(
            NodeType::Text,
            Cow::Borrowed(""),
            &EMPTY_ATTRS,
            self.handler.depth,
            self.handler.dom_ctx.get_sibling_index(node_id).unwrap_or(0),
            parent_tag.map(Cow::Borrowed),
            true,
        );
        let result = visitor_handle
            .lock()
            .expect("visitor mutex poisoned")
            .visit_text(&node_ctx, &processed.output);
        match result {
            VisitResult::Continue | VisitResult::PreserveHtml => Some(processed),
            VisitResult::Custom(custom) if self.handler.ctx.inline_depth == 0 && !self.handler.ctx.in_heading => {
                Some(ProcessedText {
                    semantic: processed.semantic.as_ref().map(|_| custom.clone()),
                    output: custom,
                })
            }
            VisitResult::Custom(_) => Some(processed),
            VisitResult::Skip => None,
            VisitResult::Error(error) => {
                if self.handler.ctx.visitor_error.borrow().is_none() {
                    *self.handler.ctx.visitor_error.borrow_mut() = Some(error);
                }
                None
            }
        }
    }

    fn append_semantic_output(&self, output_start: usize) {
        if let Some(text) = self.output.get(output_start..) {
            crate::converter::structure_capture::append_text(self.handler.ctx, text);
        }
    }

    fn emit_processed(&mut self, final_text: &str) {
        push_running_text(
            self.output,
            final_text,
            TextSite {
                node_handle: self.node_handle,
                parser: self.parser,
                options: self.handler.options,
                ctx: self.handler.ctx,
                dom_ctx: self.handler.dom_ctx,
            },
        );
    }
}

/// Where a piece of running text is written: the node it comes from and the state of the walk.
#[derive(Clone, Copy)]
pub struct TextSite<'a> {
    pub node_handle: &'a tl::NodeHandle,
    pub parser: &'a tl::Parser<'a>,
    pub options: &'a crate::options::ConversionOptions,
    pub ctx: &'a crate::converter::Context,
    pub dom_ctx: &'a DomContext,
}

/// Writes escaped running text to `output` as a text node does: the list item indent before it,
/// and the escape of a block marker where the text starts a line.
pub fn push_running_text(output: &mut String, final_text: &str, site: TextSite<'_>) {
    let ctx = site.ctx;
    let options = site.options;
    crate::converter::list::utils::indent_list_item_line_start(output, ctx, options);
    let text_start = output.len();
    push_processed_text(output, final_text, site);
    let writes_to_block = writes_to_block(std::ptr::from_ref::<String>(output) as usize, ctx);
    if !ctx.in_code && options.output_format == crate::options::OutputFormat::Markdown {
        if writes_to_block {
            crate::converter::utility::escaping::escape_block_start(
                output,
                text_start,
                ctx.in_list_item,
                next_sibling_is_inline_tag(site.node_handle, site.parser, site.dom_ctx),
            );
        }
        crate::converter::utility::escaping::escape_continuation_line_start(
            output,
            text_start,
            ctx.inline_buffer_after_hard_break,
        );
    } else if !ctx.in_code && options.output_format == crate::options::OutputFormat::Djot {
        if writes_to_block {
            crate::converter::utility::escaping::escape_djot_list_item_start(output, text_start, ctx.in_list_item);
        }
        crate::converter::utility::escaping::escape_djot_continuation_line_start(
            output,
            text_start,
            ctx.inline_buffer_after_hard_break,
        );
    }
}

fn push_processed_text(output: &mut String, final_text: &str, site: TextSite<'_>) {
    let ctx = site.ctx;
    // ~keep Code is verbatim. The handler of the code block adds the indent of the list item to
    // ~keep every line of the finished block, so a blank line in the code starts no paragraph here.
    if !ctx.in_list_item || ctx.in_code {
        output.push_str(final_text);
        return;
    }
    if final_text.contains('\n') && !final_text.contains("\n\n") {
        let mut lines = final_text.split_inclusive('\n').peekable();
        while let Some(line) = lines.next() {
            output.push_str(line);
            if lines.peek().is_some() {
                crate::converter::list::utils::indent_list_item_line_start(output, ctx, site.options);
            }
        }
        return;
    }
    if !final_text.contains("\n\n") {
        output.push_str(final_text);
        return;
    }
    let indent = " ".repeat(4 * ctx.list_depth);
    for (index, part) in final_text.split("\n\n").enumerate() {
        if index > 0 {
            output.push_str("\n\n");
            output.push_str(&indent);
        }
        output.push_str(part.trim());
    }
}

fn writes_to_block(output_ptr: usize, ctx: &crate::converter::Context) -> bool {
    let writes_to_task_marker = ctx.task_item_scope == Some((ctx.list_depth, ctx.blockquote_depth))
        && ctx
            .first_writer
            .as_ref()
            .is_some_and(crate::converter::list::item::FirstWriter::is_open);
    !ctx.convert_as_inline
        && !ctx.in_heading
        && !ctx.in_table_cell
        && !ctx.in_marker_text()
        && !writes_to_task_marker
        && (ctx.block_output_ptr == 0 || output_ptr == ctx.block_output_ptr)
}

/// Remove one source line ending and its following indentation only when it is not a blank line. ~keep
fn strip_single_trailing_line_ending(text: &str) -> Option<&str> {
    let content_end = text.trim_end_matches([' ', '\t']).len();
    let without_lf = text[..content_end].strip_suffix('\n')?;
    let without_line_ending = without_lf.strip_suffix('\r').unwrap_or(without_lf);
    (!without_line_ending.ends_with('\n') && !without_line_ending.ends_with('\r')).then_some(without_line_ending)
}

/// Remove one leading source line ending only when it does not begin a blank line. ~keep
fn strip_single_leading_line_ending(text: &str) -> Option<&str> {
    let without_line_ending = text.strip_prefix("\r\n").or_else(|| text.strip_prefix('\n'))?;
    (!without_line_ending.starts_with('\n') && !without_line_ending.starts_with('\r')).then_some(without_line_ending)
}

/// Whether a whitespace-only newline text node with no in-parent next sibling
/// still separates inline content (issue #430).
///
/// Returns true when the node's parent is an inline-like element that is itself
/// followed by inline content — e.g. the lone `"\n"` inside the middle `<span>`
/// of `<span>a</span><span>\n</span><span>b</span>` — or when the nearest such
/// ancestor with a following sibling is (issue #505).
///
/// "Inline content" deliberately includes a bare text sibling, not just an element: a browser
/// renders `a<span>\n</span>b` and `a<span>\n</span><span>b</span>` identically, so asking only
/// about a following *tag* dropped the separator and welded the words together (issue #491). ~keep
fn newline_span_needs_separating_space(
    node_handle: &tl::NodeHandle,
    parser: &tl::Parser,
    dom_ctx: &DomContext,
    in_option_list: bool,
) -> bool {
    // ~keep Climb through every transparent inline ancestor that has nothing after it: in
    // ~keep `<span><span>\n</span></span>Beta` only the outer wrapper is followed by `Beta`,
    // ~keep and asking the inner one alone welded the words together (issue #505). The first
    // ~keep block ancestor ends the climb -- a newline at the end of a block separates nothing.
    let mut node_id = node_handle.get_inner();
    loop {
        let Some(parent_id) = dom_ctx.parent_of(node_id) else {
            return false;
        };
        // ~keep A bare option group writes its children in the surrounding line (#864).
        // ~keep Inside a select or data list, its line ends belong to the list's own buffer.
        let parent_is_inline = dom_ctx
            .tag_info(parent_id, parser)
            .is_some_and(|info| info.is_inline_like || (!in_option_list && info.name == "optgroup"));
        if !parent_is_inline {
            return false;
        }
        match following_sibling_content(parent_id, parser, dom_ctx) {
            FollowingContent::Inline => return true,
            FollowingContent::NotInline => return false,
            FollowingContent::Absent => node_id = parent_id,
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::DATALIST_NODE_READS;
    use crate::{ConversionOptions, TierStrategy, convert};

    #[test]
    fn should_read_an_adjacent_data_list_once_across_comment_separated_text() {
        DATALIST_NODE_READS.with(|reads| reads.set(0));
        let result = convert(
            "k\n<!--gap-->\n<datalist><span>x</span></datalist>d",
            ConversionOptions {
                tier_strategy: TierStrategy::Tier2,
                extract_metadata: false,
                ..Default::default()
            },
        )
        .expect("adjacent data list converts");

        assert_eq!(result.content.as_deref(), Some("k x d\n"));
        DATALIST_NODE_READS.with(|reads| assert_eq!(reads.get(), 3));
    }

    #[test]
    fn should_bound_empty_list_block_prefix_visits_through_nested_spans() {
        let mut jobs = 0;
        for overlapping in [false, true] {
            for depth in [4, 16, 64] {
                let ending = if overlapping {
                    "</span>&nbsp;".repeat(depth) + "b"
                } else {
                    "</span>".repeat(depth) + "&nbsp;b"
                };
                let source = format!("<ul><li>a\n{}<p></p>{ending}</li></ul>", "<span>".repeat(depth));
                let dom = tl::parse(&source, tl::ParserOptions::default()).expect("input nodes");
                assert_cold_previous_span(&dom, source.len());
                let nodes = dom.nodes().len();
                crate::converter::utility::siblings::PREVIOUS_CONTENT_BLOCK_READS.with(|reads| reads.set(0));
                crate::converter::utility::siblings::PREVIOUS_CONTENT_BLOCK_CALLS.with(|calls| calls.set(0));
                let result = convert(
                    &source,
                    ConversionOptions {
                        tier_strategy: TierStrategy::Tier2,
                        extract_metadata: false,
                        max_depth: Some(512),
                        ..Default::default()
                    },
                )
                .expect("nested empty block");
                let reads =
                    crate::converter::utility::siblings::PREVIOUS_CONTENT_BLOCK_READS.with(std::cell::Cell::get);
                let calls =
                    crate::converter::utility::siblings::PREVIOUS_CONTENT_BLOCK_CALLS.with(std::cell::Cell::get);
                if overlapping {
                    assert_eq!(
                        result.content.as_deref(),
                        Some(format!("- a\n\n  {} b\n", "\u{a0}".repeat(depth - 1)).as_str())
                    );
                } else {
                    assert_eq!(result.content.as_deref(), Some("- a\n\n   b\n"));
                }
                assert_eq!(calls, if overlapping { 1 } else { 2 });
                assert_eq!(reads, if overlapping { 2 } else { 2 * (depth + 1) });
                assert!(reads > 0 && reads <= 2 * nodes, "{reads} reads for {nodes} nodes");
                jobs += 1;
            }
        }
        assert_eq!(jobs, 6);
    }

    fn assert_cold_previous_span(dom: &tl::VDom<'_>, source_len: usize) {
        let context = crate::converter::utility::caching::build_dom_context(dom, dom.parser(), source_len);
        let span = dom
            .query_selector("span")
            .expect("span selector")
            .next()
            .expect("outer span")
            .get_inner();
        let tail = dom
            .nodes()
            .iter()
            .enumerate()
            .find(|(_, node)| matches!(node, tl::Node::Raw(raw) if raw.as_utf8_str().ends_with('b')))
            .map(|(index, _)| u32::try_from(index).expect("small input"))
            .expect("tail node");
        assert_eq!(context.prev_tag_map[tail as usize].get().copied().flatten(), Some(span));
        assert!(context.tag_info_map.iter().all(|cell| cell.get().is_none()));
    }
}