html-to-markdown-rs 3.23.0

High-performance HTML to Markdown converter using the astral-html tokenizer. 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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! Code and pre element handlers for HTML to Markdown conversion.
//!
//! Handles `<code>` and `<pre>` elements including:
//! - Inline code with backtick formatting
//! - Code block formatting (indented or fenced)
//! - Language detection from class attributes
//! - The lines of a code block as they are in the page
//! - Visitor callback integration

mod delimiters;

use self::delimiters::{longest_consecutive_run, min_safe_code_span_delimiter_length};
use crate::converter::Context;
use crate::converter::dom_context::DomContext;
use crate::converter::inline::HandlerContext;
use crate::converter::inline::wrapped::emit_code_span;
use crate::converter::main::walk_node;
use crate::converter::text::dedent_code_block;
use crate::converter::walk::{CaptureEnd, Close, Open};
use crate::options::ConversionOptions;
use std::rc::Rc;

#[cfg(feature = "visitor")]
use crate::converter::utility::serialization::serialize_node;
#[cfg(feature = "visitor")]
use std::borrow::Cow;

/// Minimum length of a Markdown code fence (```` ``` ```` or `~~~`) per CommonMark.
const MIN_FENCE_LENGTH: usize = 3;

/// Open an inline `<code>` element, or a `<kbd>` or a `<samp>` that holds a link. Lists its
/// children in `children`.
///
/// In code the element writes nothing of its own. Else the walk captures the text of the
/// children for [`close_code`], with the links that they hold.
pub fn open_code(
    node_handle: &crate::dom::NodeHandle,
    tag: &crate::dom::HTMLTag,
    parser: &crate::dom::Parser,
    context: &Context,
    children: &mut Vec<crate::dom::NodeHandle>,
) -> Open {
    children.extend(tag.children().top().iter().copied());
    if context.code_element_is_transparent() {
        return Open::children_only();
    }
    let links = Rc::new(std::cell::RefCell::new(Vec::new()));
    let breaks = Rc::new(std::cell::RefCell::new(Vec::new()));
    let code_ctx = Context {
        in_code: true,
        inline_code_breaks: Some((node_handle.get_inner(), breaks.clone())),
        inline_code_links: if context.in_code {
            context.inline_code_links.clone()
        } else if contains_anchor(tag, parser) {
            Some(links.clone())
        } else {
            None
        },
        ..context.clone()
    };
    Open {
        scope: Some(Rc::new(code_ctx)),
        close: Close::Capture(CaptureEnd::Code(CodeEnd {
            links,
            breaks,
            source_whitespace_only: children.iter().all(|child| {
                matches!(child.get(parser), Some(crate::dom::Node::Raw(raw))
                    if crate::text::decode_html_entities_cow(&raw.as_utf8_str()).trim().is_empty())
            }),
        })),
    }
}

/// What [`open_code`] leaves for [`close_code`]: the links that the children wrote.
pub struct CodeEnd {
    links: Rc<std::cell::RefCell<Vec<crate::converter::context::InlineCodeLink>>>,
    breaks: Rc<std::cell::RefCell<Vec<usize>>>,
    source_whitespace_only: bool,
}

/// Write `content`, the text of the children of a code element, as inline code:
/// - Applying backtick delimiters, more than one when the content holds backticks
/// - Invoking visitor callbacks when the visitor feature is enabled
/// - Writing each link of the content around its part of the code
pub fn close_code(end: &CodeEnd, content: &str, mut handler: HandlerContext<'_>) {
    // ~keep An all-whitespace body is a real code span, not an empty element (#481).
    if content.is_empty() {
        return;
    }

    #[cfg(feature = "visitor")]
    if let Some(crate::dom::Node::Tag(tag)) = handler.node_handle.get(handler.parser) {
        if tag.name().as_utf8_str().eq_ignore_ascii_case("code") {
            if let Some(custom_output) = visit_inline_code(tag, content, &handler) {
                handler.output.push_str(&custom_output);
                return;
            }
        }
    }
    // ~keep Empty source line endings also reach this buffer (#868). Only retained BR
    // ~keep emissions can turn a newline-only body into actual hard breaks (#921).
    if content.bytes().all(|byte| byte == b'\n') && !end.breaks.borrow().is_empty() {
        for _ in 0..end.breaks.borrow().len() {
            emit_collected_code_break(&mut handler);
        }
        return;
    }
    if end.source_whitespace_only
        && content.bytes().all(|byte| byte == b'\n')
        && end.breaks.borrow().is_empty()
        && handler.options.whitespace_mode == crate::options::WhitespaceMode::Normalized
    {
        crate::converter::inline::wrapped::emit_whitespace_only_inline_body(content, handler.output);
        return;
    }
    if end
        .breaks
        .borrow()
        .first()
        .is_some_and(|offset| content[..*offset].bytes().all(|byte| byte == b'\n'))
        && content.starts_with('\n')
        && !handler.output.is_empty()
        && crate::converter::utility::white_space::space_is_owed(handler.output)
    {
        emit_collected_code_break(&mut handler);
    }
    emit_inline_code_with_links(content, &end.links.borrow(), &mut handler);
    if end
        .breaks
        .borrow()
        .last()
        .is_some_and(|offset| content[*offset + 1..].bytes().all(|byte| byte == b'\n'))
        && content.ends_with('\n')
        && crate::converter::utility::siblings::following_sibling_content(
            handler.node_handle.get_inner(),
            handler.parser,
            handler.dom_context,
        ) == crate::converter::utility::siblings::FollowingContent::Inline
    {
        emit_collected_code_break(&mut handler);
    }
}

/// Whether the element holds a link. An `<a>` with no `href` is no link: it is text of the code.
pub(in crate::converter) fn contains_anchor(tag: &crate::dom::HTMLTag<'_>, parser: &crate::dom::Parser<'_>) -> bool {
    let mut pending = tag.children().top().to_vec();
    while let Some(handle) = pending.pop() {
        if let Some(crate::dom::Node::Tag(child)) = handle.get(parser) {
            if child.name().as_utf8_str().eq_ignore_ascii_case("a") && child.attributes().get("href").is_some() {
                return true;
            }
            pending.extend(child.children().top().iter().copied());
        }
    }
    false
}

fn emit_inline_code_with_links(
    content: &str,
    links: &[crate::converter::context::InlineCodeLink],
    handler: &mut HandlerContext<'_>,
) {
    if links.is_empty() {
        emit_code_content(content, handler);
        return;
    }
    let mut start = 0;
    let mut pending_break = false;
    let mut emitted = false;
    for link in links {
        emit_linked_code_text(
            &content[start..link.range.start],
            &mut pending_break,
            &mut emitted,
            handler,
        );
        if pending_break && emitted {
            emit_collected_code_break(handler);
        }
        pending_break = false;
        handler.output.push_str(&link.markdown);
        emitted = true;
        start = link.range.end;
    }
    emit_linked_code_text(&content[start..], &mut pending_break, &mut emitted, handler);
}

fn emit_linked_code_text(
    content: &str,
    pending_break: &mut bool,
    emitted: &mut bool,
    handler: &mut HandlerContext<'_>,
) {
    let break_count = content.matches('\n').count();
    for (index, segment) in content.split('\n').enumerate() {
        *pending_break |= index > 0;
        if segment.is_empty() {
            continue;
        }
        if *pending_break && *emitted {
            emit_collected_code_break(handler);
        }
        let segment = if (handler.context.in_table_cell || handler.context.in_heading) && index < break_count {
            segment.trim_end()
        } else {
            segment
        };
        if segment.is_empty() {
            continue;
        }
        emit_code_content(segment, handler);
        *emitted = true;
        *pending_break = false;
    }
}

fn emit_collected_code_break(handler: &mut HandlerContext<'_>) {
    if handler.context.in_table_cell || handler.context.in_heading {
        handler.output.push(' ');
    } else {
        handler
            .output
            .push_str(crate::converter::main_helpers::hard_break_marker(handler.options));
    }
}

fn emit_code_content(content: &str, handler: &mut HandlerContext<'_>) {
    emit_inline_code(
        content,
        handler.output,
        handler.options,
        handler.node_handle,
        handler.parser,
        handler.dom_context,
    );
}

fn walk_children(tag: &crate::dom::HTMLTag<'_>, output: &mut String, context: &Context, handler: &HandlerContext<'_>) {
    for child_handle in tag.children().top() {
        walk_node(
            child_handle,
            handler.parser,
            output,
            crate::converter::block::container::HandlerContext::new(
                handler.options,
                context,
                handler.depth + 1,
                handler.dom_context,
            ),
        );
    }
}

#[cfg(feature = "visitor")]
fn visit_inline_code(tag: &crate::dom::HTMLTag<'_>, content: &str, handler: &HandlerContext<'_>) -> Option<String> {
    use crate::visitor::{NodeContext, NodeType};

    let visitor_handle = handler.context.visitor.as_ref()?;
    let node_id = handler.node_handle.get_inner();
    let node_context = NodeContext::with_lazy_attributes(
        NodeType::Code,
        Cow::Borrowed("code"),
        tag,
        handler.depth,
        handler.dom_context.get_sibling_index(node_id).unwrap_or(0),
        handler
            .dom_context
            .parent_tag_name(node_id, handler.parser)
            .map(Cow::Borrowed),
        true,
    );
    let result = visitor_handle
        .lock()
        .expect("visitor mutex poisoned")
        .visit_code_inline(&node_context, content);
    if handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict
        && (matches!(&result, crate::visitor::VisitResult::Skip)
            || matches!(&result, crate::visitor::VisitResult::Custom(custom) if custom.trim_matches([' ', '\t']).is_empty()))
    {
        handler.dom_context.record_absent_breaks(node_id, true);
    }
    visitor_output(result, handler)
}

/// Render a `<code>` element's content as one or more backtick spans, then emit through the
/// adjacent-span merge.
///
/// `content` may contain `'\n'` bytes: `line_break.rs`'s code-SPAN branch pushes one as an
/// internal-only split marker for each `<br>` the element contained (a source text node's own
/// literal line ending is already folded to a space by the time it reaches this buffer, so
/// every `'\n'` here unambiguously came from a `<br>` — see `text_node.rs`'s
/// `in_code && !in_code_block` branch). Split on it and render each segment as its own
/// backtick span, joined by the configured `newline_style` hard-break marker OUTSIDE the
/// backticks, where it is syntax rather than span content (issue #487) — matching how
/// `<b>`/`<i>` already turn an internal `<br>` into a hard break between two delimiter pairs.
/// An empty segment (an adjacent, leading, or trailing `<br>`) is dropped rather than emitted
/// as a dangling empty `` `` `` pair with nothing before or after it. ~keep
pub(in crate::converter) fn emit_inline_code(
    content: &str,
    output: &mut String,
    options: &ConversionOptions,
    node_handle: &crate::dom::NodeHandle,
    parser: &crate::dom::Parser,
    dom_ctx: &DomContext,
) {
    let separator = crate::converter::main_helpers::hard_break_marker(options);
    let mut first = true;
    for segment in content.split('\n').filter(|segment| !segment.is_empty()) {
        if first {
            let mut span = String::with_capacity(segment.len() + 2);
            format_inline_code(segment, &mut span);
            emit_code_span(&span, segment, output, node_handle, parser, dom_ctx);
        } else {
            // ~keep Only the FIRST segment may merge into an immediately preceding
            // ~keep sibling code span (issue #483): every later segment is preceded by
            // ~keep our own separator, not a bare closing backtick, so `emit_code_span`'s
            // ~keep merge check would never fire for it anyway -- rendered directly
            // ~keep without going through that check at all.
            output.push_str(separator);
            format_inline_code(segment, output);
        }
        first = false;
    }
}

/// Handle a `<pre>` element and convert to Markdown.
///
/// This handler processes code block elements including:
/// - Extracting language information from class attributes
/// - Keeping the lines of the code as they are in the page
/// - Supporting multiple code block styles (indented, backticks, tildes)
/// - Invoking visitor callbacks when the visitor feature is enabled
/// - Generating appropriate markdown output
pub fn handle_pre(tag: &crate::dom::HTMLTag, handler: HandlerContext<'_>) {
    let cell_break_offsets = (handler.context.in_table_cell && handler.options.br_in_tables).then(|| {
        std::rc::Rc::new(std::cell::RefCell::new(
            crate::converter::context::CapturedOffsets::default(),
        ))
    });
    let code_ctx = Context {
        in_code: true,
        in_code_block: true,
        pre_cell_break_offsets: cell_break_offsets.clone(),
        ..handler.context.clone()
    };
    let language = detect_language(tag, handler.parser);
    let mut content = String::with_capacity(256);
    walk_children(tag, &mut content, &code_ctx, &handler);
    if content.is_empty() {
        return;
    }

    // ~keep CommonMark 5.3 keeps indented content in the last list item until an explicit boundary.
    if handler.options.code_block_style == crate::options::CodeBlockStyle::Indented
        && !handler.context.in_table_cell
        && matches!(
            crate::converter::utility::siblings::previous_content_block(
                handler.node_handle,
                handler.parser,
                handler.dom_context
            ),
            Some("ul" | "ol")
        )
    {
        if handler.context.in_list_item {
            crate::converter::list::utils::start_block_in_list_item(handler.output, handler.context, handler.options);
        } else {
            separate_code_block(handler.output, handler.context);
        }
        handler.output.push_str("<!-- -->\n\n");
    }

    let offsets = cell_break_offsets
        .as_ref()
        .map(|offsets| offsets.borrow().positions())
        .unwrap_or_default();
    let segmented = (!offsets.is_empty()).then(|| content.clone());
    let processed = process_pre_content(content, handler.options.whitespace_mode, false);
    #[cfg(feature = "visitor")]
    if let Some(custom_output) = visit_code_block(tag, language.as_deref(), &processed, &handler) {
        handler.output.push_str(&custom_output);
    } else {
        format_code_block(
            segmented.as_deref().unwrap_or(&processed),
            &offsets,
            language.as_deref(),
            handler.output,
            handler.options,
            handler.context,
        );
    }
    #[cfg(not(feature = "visitor"))]
    format_code_block(
        segmented.as_deref().unwrap_or(&processed),
        &offsets,
        language.as_deref(),
        handler.output,
        handler.options,
        handler.context,
    );
    if let Some(ref collector) = handler.context.structure_collector {
        collector.borrow_mut().push_code(&processed, language.as_deref());
    }
}

/// Whether `tag_name` is a plain block container: inside a code block it starts a line and ends a line.
///
/// ~keep A browser renders the content of a `pre` with its line feeds kept, so the text of a code block
/// ~keep is the lines of that rendering. A block box starts a line and ends a line and adds no line of
/// ~keep its own: a `<br>` or a line feed at its end is still one break, and an empty one is no line.
/// ~keep Highlighters write each line of code as such an element. Both tiers read this list.
pub(in crate::converter) fn is_line_element_in_pre(tag_name: &str) -> bool {
    matches!(
        tag_name,
        "address"
            | "article"
            | "aside"
            | "center"
            | "dialog"
            | "div"
            | "footer"
            | "header"
            | "hgroup"
            | "main"
            | "nav"
            | "search"
            | "section"
    )
}

/// Put `output` at the start of a line of the open code block, whose content starts the buffer.
fn start_pre_line(output: &mut String) {
    if !output.is_empty() && !output.ends_with('\n') {
        output.push('\n');
    }
}

/// Write the content of a plain block container that is inside a code block, on lines of its own.
pub(in crate::converter) fn handle_line_element_in_pre(
    node_handle: &crate::dom::NodeHandle,
    parser: &crate::dom::Parser,
    output: &mut String,
    handler: crate::converter::block::container::HandlerContext<'_>,
) {
    start_pre_line(output);
    crate::converter::block::container::handle_passthrough(node_handle, parser, output, handler);
    start_pre_line(output);
}

fn detect_language(tag: &crate::dom::HTMLTag<'_>, parser: &crate::dom::Parser<'_>) -> Option<String> {
    language_from_class(tag).or_else(|| {
        tag.children().top().iter().find_map(|child_handle| {
            let crate::dom::Node::Tag(child_tag) = child_handle.get(parser)? else {
                return None;
            };
            (child_tag.name() == "code")
                .then(|| language_from_class(child_tag))
                .flatten()
        })
    })
}

fn language_from_class(tag: &crate::dom::HTMLTag<'_>) -> Option<String> {
    let classes = tag.attributes().get("class")??;
    let class_text = classes.as_utf8_str();
    let classes = crate::text::decode_attribute_value_cow(&class_text);
    classes.split_whitespace().find_map(|class| {
        class
            .strip_prefix("language-")
            .or_else(|| class.strip_prefix("lang-"))
            .map(str::to_string)
    })
}

/// The text of a code block: the content of the `pre` without the one line feed at its start.
///
/// ~keep An HTML parser drops one line feed right after the `<pre>` tag, so a browser shows a
/// ~keep second one as a blank first line of the code. Every other character is a character of
/// ~keep the code and stays: indentation that all lines share, blank lines between lines of code,
/// ~keep spaces at a line end (issues #782, #783). The fence drops the line feeds at the end.
///
/// ~keep Strict white space mode writes the start of a block as it did before that rule: the line
/// ~keep feeds at the start are one blank first line. `tag_feed_dropped` is true for Tier-1, which
/// ~keep dropped the line feed after the tag in that mode too.
pub(in crate::converter) fn process_pre_content(
    mut content: String,
    whitespace_mode: crate::options::WhitespaceMode,
    tag_feed_dropped: bool,
) -> String {
    let leading = content.len() - content.trim_start_matches('\n').len();
    let kept = if whitespace_mode == crate::options::WhitespaceMode::Strict {
        leading.saturating_sub(usize::from(tag_feed_dropped)).min(1)
    } else {
        leading.saturating_sub(1)
    };
    content.drain(..leading - kept);
    content
}

#[cfg(feature = "visitor")]
fn visit_code_block(
    tag: &crate::dom::HTMLTag<'_>,
    language: Option<&str>,
    content: &str,
    handler: &HandlerContext<'_>,
) -> Option<String> {
    use crate::visitor::{NodeContext, NodeType};

    let visitor_handle = handler.context.visitor.as_ref()?;
    let node_id = handler.node_handle.get_inner();
    let node_context = NodeContext::with_lazy_attributes(
        NodeType::Pre,
        Cow::Borrowed("pre"),
        tag,
        handler.depth,
        handler.dom_context.get_sibling_index(node_id).unwrap_or(0),
        handler
            .dom_context
            .parent_tag_name(node_id, handler.parser)
            .map(Cow::Borrowed),
        false,
    );
    let result =
        visitor_handle
            .lock()
            .expect("visitor mutex poisoned")
            .visit_code_block(&node_context, language, content);
    if handler.options.whitespace_mode == crate::options::WhitespaceMode::Strict
        && (matches!(&result, crate::visitor::VisitResult::Skip)
            || matches!(&result, crate::visitor::VisitResult::Custom(custom) if custom.trim_matches([' ', '\t']).is_empty()))
    {
        handler.dom_context.record_absent_breaks(node_id, true);
    }
    visitor_output(result, handler)
}

#[cfg(feature = "visitor")]
fn visitor_output(result: crate::visitor::VisitResult, handler: &HandlerContext<'_>) -> Option<String> {
    use crate::visitor::VisitResult;

    match result {
        VisitResult::Continue => None,
        VisitResult::Custom(custom) => {
            crate::converter::structure_capture::replace_element(handler.context, Some(&custom));
            Some(custom)
        }
        VisitResult::Skip => {
            crate::converter::structure_capture::replace_element(handler.context, None);
            Some(String::new())
        }
        VisitResult::PreserveHtml => {
            let html = serialize_node(handler.node_handle, handler.parser);
            crate::converter::structure_capture::replace_element(handler.context, Some(&html));
            Some(html)
        }
        VisitResult::Error(error) => {
            crate::converter::structure_capture::replace_element(handler.context, None);
            if handler.context.visitor_error.borrow().is_none() {
                *handler.context.visitor_error.borrow_mut() = Some(error);
            }
            None
        }
    }
}

/// Format inline code with appropriate backtick delimiters.
///
/// Handles:
/// - Single backticks for normal content
/// - Double backticks when content contains backticks
/// - Space padding when needed to avoid backtick adjacency
pub(in crate::converter) fn format_inline_code(content: &str, output: &mut String) {
    let contains_backtick = content.contains('`');

    let needs_delimiter_spaces = {
        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 CommonMark strips one space from each end of a code span ONLY when the
        // ~keep content is not entirely spaces, so an all-spaces body needs no padding --
        // ~keep and padding it changes what the span contains (`` ` ` `` is one space,
        // ~keep `` `   ` `` is three). Spec example 138 is exactly this case.
        starts_with_backtick || ends_with_backtick || (starts_with_space && ends_with_space && contains_backtick)
    };

    let (num_backticks, needs_spaces) = if contains_backtick {
        (min_safe_code_span_delimiter_length(content), needs_delimiter_spaces)
    } else {
        (1, needs_delimiter_spaces)
    };

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

/// Format a code block with the specified style and language.
///
/// Supports:
/// - Indented style (4-space indentation)
/// - Fenced style with backticks (```language)
/// - Fenced style with tildes (~~~language)
fn format_code_block(
    content: &str,
    cell_break_offsets: &[usize],
    language: Option<&str>,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
) {
    if ctx.in_table_cell {
        // ~keep Neither code-block style can exist inside a GFM pipe cell: the fence (or the
        // ~keep 4-space indent) is line-structured and both styles bracket the block with blank
        // ~keep lines, so the row would be split across physical lines (issue #456). Emit the
        // ~keep content inline with the block syntax dropped — the same degradation Tier-1's
        // ~keep `close_pre` already performs, and consistent with headings and list items
        // ~keep shedding their markers in a cell. Line breaks fold to a space rather than to
        // ~keep `<br>` so that the two tiers stay byte-equal. The cell break separates the block
        // ~keep from the cell content before it (issue #645).
        let trimmed_content = content.trim_matches('\n');
        if !trimmed_content.is_empty() && !ctx.convert_as_inline && !ctx.in_code {
            crate::converter::main_helpers::separate_block_in_cell(output, options.br_in_tables);
        }
        format_preformatted_cell_content(
            content,
            cell_break_offsets,
            output,
            options.br_in_tables,
            options.whitespace_mode == crate::options::WhitespaceMode::Strict,
        );
        return;
    }

    if ctx.in_list_item {
        format_code_block_in_list_item(content, language, output, options, ctx);
        return;
    }

    separate_code_block(output, ctx);
    render_code_block(content, language, output, options);
}

/// Write the code block for `content` in the configured style. Both tiers call it.
pub(in crate::converter) fn render_code_block(
    content: &str,
    language: Option<&str>,
    output: &mut String,
    options: &ConversionOptions,
) {
    match options.code_block_style {
        crate::options::CodeBlockStyle::Indented => format_indented_code_block(content, output),
        crate::options::CodeBlockStyle::Backticks | crate::options::CodeBlockStyle::Tildes => {
            format_fenced_code_block(content, language, output, options);
        }
    }
}

fn separate_code_block(output: &mut String, context: &Context) {
    if context.convert_as_inline || output.is_empty() || output.ends_with("\n\n") {
        return;
    }
    if output.ends_with('\n') {
        output.push('\n');
    } else {
        output.push_str("\n\n");
    }
}

fn format_indented_code_block(content: &str, output: &mut String) {
    // ~keep Markdown has no indented code block that starts with a blank line.
    let indented = content
        .trim_start_matches('\n')
        .lines()
        .map(|line| {
            if line.is_empty() {
                String::new()
            } else {
                format!("    {line}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    output.push_str(&indented);
    output.push_str("\n\n");
}

fn format_fenced_code_block(content: &str, language: Option<&str>, output: &mut String, options: &ConversionOptions) {
    let fence_char = if options.code_block_style == crate::options::CodeBlockStyle::Backticks {
        '`'
    } else {
        '~'
    };
    // ~keep A fence must exceed the longest matching run in the content (CommonMark 4.5).
    let fence_length = (longest_consecutive_run(content, fence_char) + 1).max(MIN_FENCE_LENGTH);
    let fence: String = std::iter::repeat_n(fence_char, fence_length).collect();
    output.push_str(&fence);
    if let Some(language) = language {
        output.push_str(language);
    } else if !options.code_language.is_empty() {
        output.push_str(&options.code_language);
    }
    output.push('\n');
    output.push_str(content.trim_end_matches('\n'));
    output.push('\n');
    output.push_str(&fence);
    output.push_str("\n\n");
}

/// Render preformatted table-cell content as code spans, keeping real `<br>` nodes outside. ~keep
pub(in crate::converter) fn format_preformatted_cell_content(
    content: &str,
    break_offsets: &[usize],
    output: &mut String,
    br_in_tables: bool,
    preserve_whitespace: bool,
) {
    if !br_in_tables || break_offsets.is_empty() {
        let normalized = normalize_preformatted_cell_segment(content, preserve_whitespace);
        let folded = crate::text::fold_cell_line_breaks_verbatim_cow(&normalized);
        if !folded.is_empty() {
            format_inline_code(folded.as_ref(), output);
        }
        return;
    }

    let (normalized, break_offsets) = normalize_preformatted_cell_content(content, break_offsets, preserve_whitespace);
    let mut start = 0;
    let mut wrote_segment = false;
    let mut pending_breaks = 0;
    for offset in break_offsets {
        if offset < start || !normalized.is_char_boundary(offset) {
            continue;
        }
        let segment = crate::text::fold_cell_line_breaks_verbatim_cow(&normalized[start..offset]);
        if !segment.is_empty() {
            if wrote_segment {
                for _ in 0..pending_breaks {
                    output.push_str("<br>");
                }
            }
            format_inline_code(segment.as_ref(), output);
            wrote_segment = true;
            pending_breaks = 0;
        }
        pending_breaks += 1;
        start = offset + 1;
    }
    let segment = crate::text::fold_cell_line_breaks_verbatim_cow(&normalized[start..]);
    if !segment.is_empty() {
        if wrote_segment {
            for _ in 0..pending_breaks {
                output.push_str("<br>");
            }
        }
        format_inline_code(segment.as_ref(), output);
    }
}

fn normalize_preformatted_cell_content(
    content: &str,
    break_offsets: &[usize],
    preserve_whitespace: bool,
) -> (String, Vec<usize>) {
    let core = content.trim_matches('\n');
    let core_start = content.len() - content.trim_start_matches('\n').len();
    let normalized = if preserve_whitespace {
        core.to_string()
    } else {
        dedent_code_block(core)
    };
    let newline_offsets: Vec<usize> = normalized.match_indices('\n').map(|(offset, _)| offset).collect();
    let normalized_break_offsets = break_offsets
        .iter()
        .filter_map(|&offset| offset.checked_sub(core_start))
        .filter(|&offset| offset < core.len() && core.as_bytes().get(offset) == Some(&b'\n'))
        .map(|offset| core[..offset].bytes().filter(|&byte| byte == b'\n').count())
        .filter_map(|ordinal| newline_offsets.get(ordinal).copied())
        .collect();
    (normalized, normalized_break_offsets)
}

fn normalize_preformatted_cell_segment(content: &str, preserve_whitespace: bool) -> String {
    let content = content.trim_matches('\n');
    if preserve_whitespace {
        content.to_string()
    } else {
        dedent_code_block(content)
    }
}

/// Format a code block that is a child of a list item.
///
/// ~keep A fenced (or indented) code block spans several physical lines, but the
/// ~keep only call site that indented list continuation content
/// ~keep (`block/paragraph.rs`'s list continuation) indented a single
/// ~keep leading position, not every line a block emits. CommonMark's list
/// ~keep container match is per physical line: a non-blank line that is not
/// ~keep indented to `list_indent_columns` is not part of the item, so an
/// ~keep unindented closing fence (or any interior content line) drops the rest
/// ~keep of the block, and the item itself, out of the list on re-parse
/// ~keep (CommonMark spec examples 263, 273, 274, 318, 324). Render into a
/// ~keep scratch buffer first so every line can be indented uniformly, then only
/// ~keep skip the indent on the very first line when this block sits directly
/// ~keep after the marker text (i.e. it is the item's first content, not a
/// ~keep continuation) — that line already starts at the right column.
fn format_code_block_in_list_item(
    content: &str,
    language: Option<&str>,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
) {
    let mut rendered = String::new();
    let plain_ctx = Context {
        in_list_item: false,
        ..ctx.clone()
    };
    format_code_block(content, &[], language, &mut rendered, options, &plain_ctx);

    // ~keep A plain suffix check like `output.ends_with("* ")` also matches the closing
    // ~keep "**"/"*" of `<strong>`/`<em>` immediately followed by a migrated trailing
    // ~keep space, indistinguishable from a real bare bullet by suffix alone -- and, being
    // ~keep hardcoded to `-`/`*`, never matched the third bullet `+` at all. Both false
    // ~keep positive (fake marker) and false negative (real `+ ` marker) misclassified
    // ~keep this fenced block relative to the marker, either gluing the opening fence onto
    // ~keep the previous inline line (breaking the fence syntax) or doubly indenting the
    // ~keep first line. See `list::utils::line_is_bare_list_marker`'s doc comment.
    let is_continuation = !ctx.convert_as_inline
        && !output.is_empty()
        && !crate::converter::list::utils::line_is_bare_list_marker(output);

    if is_continuation {
        crate::converter::trim_trailing_whitespace(output);
        if !output.ends_with("\n\n") {
            if output.ends_with('\n') {
                output.push('\n');
            } else {
                output.push_str("\n\n");
            }
        }
    }

    let indent =
        crate::converter::list::utils::continuation_indent_string(ctx.list_indent_columns, options).unwrap_or_default();

    for (index, segment) in rendered.split_inclusive('\n').enumerate() {
        let line = segment.strip_suffix('\n').unwrap_or(segment);
        if line.is_empty() || (index == 0 && !is_continuation) {
            output.push_str(segment);
        } else {
            output.push_str(&indent);
            output.push_str(segment);
        }
    }
}

pub struct PreEnd {
    offsets: Option<Rc<std::cell::RefCell<crate::converter::context::CapturedOffsets>>>,
    language: Option<String>,
}

pub fn open_pre(
    tag: &crate::dom::HTMLTag,
    parser: &crate::dom::Parser,
    context: &Context,
    options: &ConversionOptions,
    children: &mut Vec<crate::dom::NodeHandle>,
) -> Open {
    let offsets = (context.in_table_cell && options.br_in_tables).then(|| {
        Rc::new(std::cell::RefCell::new(
            crate::converter::context::CapturedOffsets::default(),
        ))
    });
    let code_ctx = Context {
        in_code: true,
        in_code_block: true,
        pre_cell_break_offsets: offsets.clone(),
        ..context.clone()
    };
    children.extend(tag.children().top().iter().copied());
    Open {
        scope: Some(Rc::new(code_ctx)),
        close: Close::Capture(CaptureEnd::Pre(PreEnd {
            offsets,
            language: detect_language(tag, parser),
        })),
    }
}

pub fn close_pre(end: &PreEnd, captured: &str, handler: HandlerContext<'_>) {
    if captured.is_empty() {
        return;
    }
    let Some(crate::dom::Node::Tag(tag)) = handler.node_handle.get(handler.parser) else {
        return;
    };
    #[cfg(not(feature = "visitor"))]
    let _ = tag;
    let content = captured.to_owned();
    let language = &end.language;
    let cell_break_offsets = &end.offsets;
    // ~keep CommonMark 5.3 keeps indented content in the last list item until an explicit boundary.
    if handler.options.code_block_style == crate::options::CodeBlockStyle::Indented
        && !handler.context.in_table_cell
        && matches!(
            crate::converter::utility::siblings::previous_content_block(
                handler.node_handle,
                handler.parser,
                handler.dom_context
            ),
            Some("ul" | "ol")
        )
    {
        if handler.context.in_list_item {
            crate::converter::list::utils::start_block_in_list_item(handler.output, handler.context, handler.options);
        } else {
            separate_code_block(handler.output, handler.context);
        }
        handler.output.push_str("<!-- -->\n\n");
    }

    let offsets = cell_break_offsets
        .as_ref()
        .map(|offsets| offsets.borrow().positions())
        .unwrap_or_default();
    let segmented = (!offsets.is_empty()).then(|| content.clone());
    let processed = process_pre_content(content, handler.options.whitespace_mode, false);
    #[cfg(feature = "visitor")]
    if let Some(custom_output) = visit_code_block(tag, language.as_deref(), &processed, &handler) {
        handler.output.push_str(&custom_output);
    } else {
        format_code_block(
            segmented.as_deref().unwrap_or(&processed),
            &offsets,
            language.as_deref(),
            handler.output,
            handler.options,
            handler.context,
        );
    }
    #[cfg(not(feature = "visitor"))]
    format_code_block(
        segmented.as_deref().unwrap_or(&processed),
        &offsets,
        language.as_deref(),
        handler.output,
        handler.options,
        handler.context,
    );
    if let Some(ref collector) = handler.context.structure_collector {
        collector.borrow_mut().push_code(&processed, language.as_deref());
    }
}

pub fn open_line_element_in_pre(
    node: &crate::dom::NodeHandle,
    parser: &crate::dom::Parser,
    output: &mut String,
    children: &mut Vec<crate::dom::NodeHandle>,
) -> Option<Open> {
    let Some(crate::dom::Node::Tag(tag)) = node.get(parser) else {
        return None;
    };
    start_pre_line(output);
    children.extend(tag.children().top().iter().copied());
    Some(Open {
        scope: None,
        close: Close::PreLine,
    })
}

pub fn close_line_element_in_pre(output: &mut String) {
    start_pre_line(output);
}