html-to-markdown-rs 3.22.2

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
//! Cell and row handling for Markdown conversion.
//!
//! Provides functionality for processing table cells and rows, including:
//! - Row conversion to Markdown format
//! - Cell layout handling with colspan/rowspan support
//! - Layout table row conversion to list items

use crate::converter::block::container::HandlerContext;
use crate::converter::utility::content::normalized_tag_name;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;

use super::cell::{
    cell_text_content, collect_table_cells, convert_table_cell, emit_cell_text, get_colspan_rowspan, render_cell_text,
};

/// Maximum allowed table columns to prevent unbounded memory usage.
const MAX_TABLE_COLS: usize = 1000;
const MAX_CELL_WIDTH: usize = 200;

/// Rendered markdown of each cell visited by the column-width pre-pass, keyed by DOM node id.
///
/// ~keep The pre-pass and the render pass walk the same cell subtrees, so the pre-pass result
/// ~keep can be emitted directly instead of rendering twice — but only where the two passes are
/// ~keep provably byte-identical. The pre-pass context sets `measure_width_only` (nested tables
/// ~keep degrade to raw text, issue #406) and `skip_visitor_hooks`, and a second walk is
/// ~keep observable through any collector handle shared via the context. The caller decides via
/// ~keep `enabled` (see `builder::cell_text_reuse_allowed`); when disabled this stores nothing.
pub struct CellTextCache {
    entries: HashMap<u32, String>,
    enabled: bool,
}

impl CellTextCache {
    /// Create a cache; `enabled == false` makes every store a no-op and every lookup a miss.
    pub fn new(enabled: bool) -> Self {
        Self {
            entries: HashMap::new(),
            enabled,
        }
    }

    pub(super) const fn enable(&mut self) {
        self.enabled = true;
    }

    pub(super) fn store(&mut self, node_id: u32, text: String) {
        if self.enabled {
            self.entries.insert(node_id, text);
        }
    }

    pub(super) fn take(&mut self, node_id: u32) -> Option<String> {
        if self.enabled {
            self.entries.remove(&node_id)
        } else {
            None
        }
    }
}

// ~keep Widths must reflect the emission walk, while the existing visitor preview and quiet
// ~keep width walk retain their callback order. Record generated padding instead of parsing pipes (#904).
#[derive(Default)]
pub struct RenderedWidths {
    widths: Vec<usize>,
    edits: Vec<WidthEdit>,
}

#[cfg(feature = "visitor")]
pub(super) struct RenderedWidthCheckpoint {
    widths: Vec<usize>,
    edits: usize,
}

enum WidthEdit {
    Cell {
        padding: Range<usize>,
        column: usize,
        text_len: usize,
    },
    Separator {
        padding: Range<usize>,
        columns: usize,
    },
}

impl RenderedWidths {
    #[cfg(feature = "visitor")]
    pub(super) fn checkpoint(&self) -> RenderedWidthCheckpoint {
        RenderedWidthCheckpoint {
            widths: self.widths.clone(),
            edits: self.edits.len(),
        }
    }

    #[cfg(feature = "visitor")]
    pub(super) fn rollback(&mut self, checkpoint: RenderedWidthCheckpoint) {
        self.widths = checkpoint.widths;
        self.edits.truncate(checkpoint.edits);
    }

    fn record_cell(&mut self, padding: Range<usize>, column: usize, text_len: usize) {
        if column >= MAX_TABLE_COLS {
            return;
        }
        if column >= self.widths.len() {
            self.widths.resize(column + 1, 0);
        }
        self.widths[column] = self.widths[column].max(text_len.min(MAX_CELL_WIDTH));
        self.edits.push(WidthEdit::Cell {
            padding,
            column,
            text_len,
        });
    }

    fn commit_row(&mut self, first_edit: usize, output_start: usize) {
        for edit in &mut self.edits[first_edit..] {
            let padding = match edit {
                WidthEdit::Cell { padding, .. } | WidthEdit::Separator { padding, .. } => padding,
            };
            padding.start += output_start;
            padding.end += output_start;
        }
    }

    pub fn repad(self, output: &mut String, output_start: usize, options: &crate::options::ConversionOptions) {
        if self.edits.is_empty() {
            return;
        }
        let original = output.split_off(output_start);
        output.reserve(original.len());
        let mut copied = 0;
        // ~keep Ranges come from ASCII padding boundaries at emission, in output order;
        // ~keep cell text and callback-owned row output are copied verbatim, including literal pipes.
        for edit in self.edits {
            let padding = match &edit {
                WidthEdit::Cell { padding, .. } | WidthEdit::Separator { padding, .. } => padding,
            };
            output.push_str(&original[copied..padding.start - output_start]);
            copied = padding.end - output_start;
            match edit {
                WidthEdit::Cell { column, text_len, .. } => {
                    let width = self.widths.get(column).copied().unwrap_or(0);
                    output.extend(std::iter::repeat_n(' ', width.saturating_sub(text_len)));
                }
                WidthEdit::Separator { columns, .. } => {
                    emit_header_separator(output, options, columns, &self.widths);
                }
            }
        }
        output.push_str(&original[copied..]);
    }
}

/// Read-only conversion inputs threaded together through row/cell rendering: the parser, user
/// options, conversion `Context`, and DOM lookup context.
///
/// ~keep These four are always passed as a group across this module's row-rendering functions;
/// ~keep bundling them keeps each function's own signature down to its row/cell-specific
/// ~keep parameters instead of repeating all four everywhere (too-many-parameters).
#[derive(Clone, Copy)]
pub struct RowEnv<'p> {
    pub parser: &'p crate::dom::Parser<'p>,
    pub options: &'p crate::options::ConversionOptions,
    pub ctx: &'p super::super::super::Context,
    pub dom_ctx: &'p super::super::super::DomContext,
}

/// Append one layout-table cell's converted text to `row_text`, space-joining after the first
/// non-empty cell.
///
/// Extracted from `append_layout_row`'s per-cell loop body — identical cell-name check,
/// inline-image handling, and whitespace trim, unchanged.
fn append_layout_cell_text(cell_handle: &crate::dom::NodeHandle, row_text: &mut String, env: RowEnv<'_>, depth: usize) {
    if env.ctx.excluded_node_ids.contains(&cell_handle.get_inner()) {
        return;
    }
    let Some(crate::dom::Node::Tag(cell_tag)) = cell_handle.get(env.parser) else {
        return;
    };
    let cell_name: Cow<'_, str> = env.dom_ctx.tag_info(cell_handle.get_inner(), env.parser).map_or_else(
        || normalized_tag_name(cell_tag.name().as_utf8_str()).into_owned().into(),
        |info| Cow::Borrowed(info.name.as_str()),
    );
    if !matches!(cell_name.as_ref(), "td" | "th" | "cell") {
        return;
    }

    let mut cell_text = String::new();
    // ~keep issue #433/#500: a layout row renders as a list item, and list items keep inline
    // ~keep images by default (only headings degrade an image to its alt text), so this cell
    // ~keep always allows them regardless of `keep_inline_images_in`. That option still governs
    // ~keep image handling elsewhere; it is simply not needed to keep images in a layout cell.
    let cell_allow_inline_images = true;
    let cell_ctx = super::super::super::Context {
        convert_as_inline: true,
        in_layout_cell: true,
        cell_allow_inline_images,
        in_cell_of_inputs: super::scanner::cell_holds_only_inputs(
            *cell_handle,
            env.parser,
            env.dom_ctx,
            env.options.br_in_tables,
        ),
        ..env.ctx.clone()
    };
    let cell_children = cell_tag.children();
    for cell_child in cell_children.top() {
        super::super::super::walk_node(
            cell_child,
            env.parser,
            &mut cell_text,
            crate::converter::block::container::HandlerContext::new(env.options, &cell_ctx, depth + 1, env.dom_ctx),
        );
    }
    let cell_content = crate::text::normalize_whitespace_cow(&cell_text);
    if !cell_content.trim().is_empty() {
        if !row_text.is_empty() {
            row_text.push(' ');
        }
        row_text.push_str(cell_content.trim());
    }
}

/// Append a layout table row as a list item.
///
/// For tables used for visual layout, converts rows to list items
/// instead of table format for better readability.
///
/// # Arguments
/// * `row_handle` - Handle to the row element
/// * `output` - Mutable string to append content
/// * `env` - Parser, options, conversion context, and DOM context
/// * `depth` - Current recursion depth (the row's own depth; cell content is walked at `depth + 1`)
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn append_layout_row(row_handle: &crate::dom::NodeHandle, output: &mut String, env: RowEnv<'_>, depth: usize) {
    if env.ctx.excluded_node_ids.contains(&row_handle.get_inner()) {
        return;
    }
    let Some(crate::dom::Node::Tag(row_tag)) = row_handle.get(env.parser) else {
        return;
    };
    let mut row_text = String::new();
    let row_children = row_tag.children();
    for cell_handle in row_children.top() {
        append_layout_cell_text(cell_handle, &mut row_text, env, depth);
    }

    append_layout_text(output, &row_text, env.options, env.ctx);
}

pub(super) fn append_layout_text(
    output: &mut String,
    row_text: &str,
    options: &crate::options::ConversionOptions,
    ctx: &super::super::super::Context,
) {
    let trimmed = row_text.trim();
    if !trimmed.is_empty() {
        if !output.is_empty() && !output.ends_with('\n') {
            output.push('\n');
        }
        let marker = layout_row_bullet(options, ctx);
        let formatted = strip_leading_bullet(trimmed, options);
        output.push(marker);
        output.push(' ');
        output.push_str(formatted);
        output.push('\n');
    }
}

/// The list marker a layout row renders with.
///
/// A layout table's rows are list items, so they cycle through `options.bullets` by nesting
/// depth exactly as `list::item` does. The row sits one level deeper than its surroundings --
/// `ul_depth` is still the *enclosing* depth here, where `list::item` has already counted its
/// own `<ul>` -- so the index is `ul_depth` rather than `ul_depth - 1`. A layout table nested
/// in a list therefore takes the next marker instead of repeating its parent's (issue #472).
fn layout_row_bullet(options: &crate::options::ConversionOptions, ctx: &super::super::super::Context) -> char {
    let bullets: Vec<char> = options.bullets.chars().collect();
    if bullets.is_empty() {
        return '*';
    }
    bullets[ctx.ul_depth % bullets.len()]
}

/// Drop a leading list marker the cell content already produced, so the row's own marker is not
/// doubled up. Any configured bullet counts, not just `-`: the marker being stripped was written
/// by this same cycling rule, so hardcoding one character missed every other configured set.
fn strip_leading_bullet<'a>(trimmed: &'a str, options: &crate::options::ConversionOptions) -> &'a str {
    for bullet in options.bullets.chars().chain(['-', '*', '+']) {
        let mut marker = String::with_capacity(2);
        marker.push(bullet);
        marker.push(' ');
        if let Some(rest) = trimmed.strip_prefix(marker.as_str()) {
            return rest.trim_start();
        }
    }
    trimmed
}

/// Advance `col` past any columns whose rowspan tracker still has rows remaining, decrementing
/// each as it is skipped and clearing the tracker entry once exhausted.
///
/// Extracted from `collect_row_cell_widths`'s inner loop — identical decrement-and-clear logic,
/// unchanged.
fn skip_rowspan_columns(col: &mut usize, rowspan_tracker: &mut [Option<usize>]) {
    while *col < rowspan_tracker.len() {
        let Some(Some(remaining)) = rowspan_tracker.get_mut(*col) else {
            break;
        };
        if *remaining == 0 {
            break;
        }
        *remaining -= 1;
        if *remaining == 0 {
            rowspan_tracker[*col] = None;
        }
        *col += 1;
    }
}

/// Collect the rendered text content of every cell in a row for width calculation.
///
/// `rowspan_tracker` mirrors the tracker in `convert_table_row` so that spanned
/// columns are skipped in the width pre-pass just as they are skipped in rendering.
/// Pass a shared tracker across all row calls to correctly handle multi-row spans.
///
/// `depth` is the row's own recursion depth; cell content is measured at `depth + 1`.
///
/// # Arguments
/// * `node_handle` - Handle to the row element
/// * `env` - Parser, options, conversion context, and DOM context
/// * `col_widths` - Per-column max content widths accumulated so far
/// * `rowspan_tracker` - Mutable array tracking rowspan remainder for each column
/// * `cell_cache` - Rendered markdown to store for later reuse by the render pass
/// * `depth` - Row's own recursion depth
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn collect_row_cell_widths(
    node_handle: &crate::dom::NodeHandle,
    env: RowEnv<'_>,
    col_widths: &mut Vec<usize>,
    rowspan_tracker: &mut Vec<Option<usize>>,
    cell_cache: &mut CellTextCache,
    depth: usize,
) {
    let mut cells = Vec::new();
    collect_table_cells(node_handle, env.parser, env.dom_ctx, env.ctx, &mut cells);

    let mut col = 0usize;
    let mut cell_iter = cells.iter();

    loop {
        skip_rowspan_columns(&mut col, rowspan_tracker);

        let Some(cell_handle) = cell_iter.next() else {
            break;
        };

        let text = cell_text_content(cell_handle, env.parser, env.options, env.ctx, env.dom_ctx, depth + 1);
        let width = text.chars().count().min(MAX_CELL_WIDTH);
        cell_cache.store(cell_handle.get_inner(), text);

        if col >= col_widths.len() {
            col_widths.resize(col + 1, 0);
        }
        if width > col_widths[col] {
            col_widths[col] = width;
        }

        let (colspan, rowspan) = get_colspan_rowspan(cell_handle, env.parser);

        if rowspan > 1 {
            if col >= rowspan_tracker.len() {
                rowspan_tracker.resize(col + 1, None);
            }
            rowspan_tracker[col] = Some(rowspan - 1);
        }

        col = col.saturating_add(colspan);
    }
}

/// Emit one cell of a rendered row, reusing the pre-pass rendering when it is cached.
///
/// `env.ctx` is used as the cell's own context (already carrying `in_table_cell = true`).
/// `depth` is the cell's own recursion depth. `deferred_tables` is forwarded to
/// [`convert_table_cell`]; see [`super::cell::render_cell_text`] for what it does.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn emit_row_cell(
    cell_handle: &crate::dom::NodeHandle,
    row_text: &mut String,
    env: RowEnv<'_>,
    emission: CellEmission,
    render: &mut RowRender<'_>,
    is_single_cell_row: bool,
) {
    let deferred_tables = is_single_cell_row.then_some(&mut *render.deferred_tables);
    if let Some(widths) = render.rendered_widths.as_deref_mut() {
        let text = render.cell_cache.take(cell_handle.get_inner()).unwrap_or_else(|| {
            render_cell_text(
                cell_handle,
                env.parser,
                HandlerContext::new(env.options, env.ctx, emission.depth, env.dom_ctx),
                deferred_tables,
            )
        });
        let text_len = text.chars().count();
        let padding_start = row_text.len() + 1 + text.len();
        emit_cell_text(cell_handle, env.parser, row_text, &text, emission.col_width);
        let old_padding = emission.col_width.unwrap_or(0).saturating_sub(text_len);
        widths.record_cell(padding_start..padding_start + old_padding, emission.column, text_len);
        return;
    }
    if let Some(text) = render.cell_cache.take(cell_handle.get_inner()) {
        emit_cell_text(cell_handle, env.parser, row_text, &text, emission.col_width);
    } else {
        convert_table_cell(
            cell_handle,
            env.parser,
            row_text,
            HandlerContext::new(env.options, env.ctx, emission.depth, env.dom_ctx),
            emission.col_width,
            deferred_tables,
        );
    }
}

#[derive(Clone, Copy)]
struct CellEmission {
    col_width: Option<usize>,
    depth: usize,
    column: usize,
}

/// Minimum separator dash count per column (matches `---`).
const MIN_SEPARATOR_DASHES: usize = 3;

/// If `col_index` still has pending rowspan rows, emit its blank continuation cell (padded to
/// `col_widths`) into `row_text` and advance `col_index` past it.
///
/// Returns `true` when a continuation cell was emitted (caller should retry from the top of the
/// loop) and `false` when `col_index` is not a pending rowspan continuation.
///
/// Extracted from `convert_table_row`'s has-span loop — identical padding and rowspan-tracker
/// bookkeeping, unchanged.
fn emit_rowspan_continuation(
    col_index: &mut usize,
    total_cols: usize,
    rowspan_tracker: &mut [Option<usize>],
    col_widths: &[usize],
    row_text: &mut String,
    rendered_widths: Option<&mut RenderedWidths>,
) -> bool {
    if *col_index >= total_cols {
        return false;
    }
    let Some(Some(remaining_rows)) = rowspan_tracker.get_mut(*col_index) else {
        return false;
    };
    if *remaining_rows == 0 {
        return false;
    }

    let width = col_widths.get(*col_index).copied();
    let padding_start = row_text.len() + 1;
    row_text.push(' ');
    if let Some(w) = width {
        for _ in 0..w {
            row_text.push(' ');
        }
    }
    row_text.push_str(" |");
    if let Some(widths) = rendered_widths {
        widths.record_cell(padding_start..padding_start + width.unwrap_or(0), *col_index, 0);
    }
    *remaining_rows -= 1;
    if *remaining_rows == 0 {
        rowspan_tracker[*col_index] = None;
    }
    *col_index += 1;
    true
}

/// Convert a table row (tr) to Markdown format.
///
/// Processes all cells in a row, handling colspan and rowspan for proper
/// column alignment. Renders header separator row after the first row.
/// Integrates with visitor pattern for custom row handling.
///
/// # Arguments
/// * `node_handle` - Handle to the row element
/// * `parser` - HTML parser instance
/// * `output` - Mutable string to append row content
/// * `options` - Conversion options
/// * `ctx` - Conversion context (visitor, etc)
/// * `row_index` - Index of this row in the table
/// * `has_span` - Whether table has colspan/rowspan
/// * `rowspan_tracker` - Mutable array tracking rowspan remainder for each column
/// * `total_cols` - Total columns in the table
/// * `header_cols` - Columns to render in separator row
/// * `dom_ctx` - DOM context
/// * `depth` - Nesting depth
/// * `is_header` - Whether this is a header row
/// * `col_widths` - Per-column max content widths for padding (empty = no padding)
/// * `cell_cache` - Markdown already rendered for these cells by the width pre-pass
/// * `deferred_tables` - Collects a nested table's markdown when this row's sole cell holds
///   one; see [`super::cell::render_cell_text`]. The caller renders these separately, after the
///   enclosing table, once every row has been processed (issue #484).
///
/// # Returns
/// `false` when the row collected zero cells (nothing was emitted); `true` otherwise. Callers
/// must only advance their own row counter when this returns `true` (issue #489).
/// Run the row-level visitor hook, if one is registered.
///
/// Returns `Some(bool)` when the visitor decided the row is fully handled and
/// `convert_table_row` must return that value immediately; `None` when rendering should
/// continue as normal. Split out of `convert_table_row` to keep that function under the
/// cyclomatic-complexity gate.
#[cfg(feature = "visitor")]
fn run_row_visitor_hook(
    node_handle: &crate::dom::NodeHandle,
    output: &mut String,
    visit: RowVisit<'_>,
) -> Option<bool> {
    visit.env.ctx.visitor.as_ref()?;
    let cell_contents = visitor_cell_contents(visit);
    run_row_visitor_with_contents(node_handle, output, visit, &cell_contents)
}

#[cfg(feature = "visitor")]
pub(super) fn run_row_visitor_with_contents(
    node_handle: &crate::dom::NodeHandle,
    output: &mut String,
    visit: RowVisit<'_>,
    cell_contents: &[String],
) -> Option<bool> {
    use crate::visitor::{NodeContext, NodeType, VisitResult};
    let visitor_handle = visit.env.ctx.visitor.as_ref()?;
    let crate::dom::Node::Tag(tag) = node_handle.get(visit.env.parser)? else {
        return None;
    };

    let node_ctx = NodeContext::with_lazy_attributes(
        NodeType::TableRow,
        Cow::Borrowed("tr"),
        tag,
        visit.depth,
        visit.row_index,
        Some(Cow::Borrowed("table")),
        false,
    );

    let visit_result = {
        let mut visitor = visitor_handle.lock().expect("visitor mutex poisoned");
        visitor.visit_table_row(&node_ctx, cell_contents, visit.is_header)
    };

    match visit_result {
        VisitResult::Continue => None,
        // ~keep Pre-existing visitor early returns, unrelated to issue #489: `true`
        // ~keep preserves prior behavior of always advancing `row_index` here.
        VisitResult::Skip => Some(true),
        VisitResult::Custom(custom) => {
            output.push_str(&custom);
            Some(true)
        }
        VisitResult::Error(err) => {
            if visit.env.ctx.visitor_error.borrow().is_none() {
                *visit.env.ctx.visitor_error.borrow_mut() = Some(err);
            }
            Some(true)
        }
        VisitResult::PreserveHtml => {
            output.push_str(&super::super::super::serialize_node(node_handle, visit.env.parser));
            Some(true)
        }
    }
}

#[cfg(feature = "visitor")]
#[derive(Clone, Copy)]
pub(super) struct RowVisit<'a> {
    pub(super) env: RowEnv<'a>,
    pub(super) cells: &'a [crate::dom::NodeHandle],
    pub(super) row_index: usize,
    pub(super) is_header: bool,
    pub(super) depth: usize,
}

#[cfg(feature = "visitor")]
/// ~keep This visitor-only walk feeds the callback before the render pass walks each cell again.
/// ~keep Detaching shared collectors prevents duplicate metadata and structure entries.
fn visitor_cell_contents(visit: RowVisit<'_>) -> Vec<String> {
    let mut collect_ctx = super::super::super::Context {
        in_table_cell: true,
        ..visit.env.ctx.clone()
    };
    #[cfg(feature = "metadata")]
    {
        collect_ctx.metadata_collector = None;
        collect_ctx.header_capture = None;
    }
    collect_ctx.structure_collector = None;
    #[cfg(feature = "inline-images")]
    {
        collect_ctx.inline_collector = None;
    }
    visit
        .cells
        .iter()
        .map(|cell_handle| visitor_cell_text(cell_handle, visit.env, &collect_ctx, visit.depth))
        .collect()
}

#[cfg(feature = "visitor")]
fn visitor_cell_text(
    cell_handle: &crate::dom::NodeHandle,
    env: RowEnv<'_>,
    collect_ctx: &super::super::super::Context,
    depth: usize,
) -> String {
    let mut text = String::new();
    if let Some(crate::dom::Node::Tag(tag)) = cell_handle.get(env.parser) {
        let cell_ctx = collect_ctx.for_cell(*cell_handle, env.parser, env.dom_ctx, env.options.br_in_tables);
        for child_handle in tag.children().top() {
            super::super::super::walk_node(
                child_handle,
                env.parser,
                &mut text,
                crate::converter::block::container::HandlerContext::new(env.options, &cell_ctx, depth + 1, env.dom_ctx),
            );
        }
    }
    crate::text::normalize_whitespace_cow(&text).trim().to_string()
}

#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn convert_table_row(
    node_handle: &crate::dom::NodeHandle,
    output: &mut String,
    env: RowEnv<'_>,
    render: &mut RowRender<'_>,
) -> bool {
    let mut row_text = String::with_capacity(256);
    let mut cells = Vec::new();

    collect_table_cells(node_handle, env.parser, env.dom_ctx, env.ctx, &mut cells);
    // ~keep A nested table may only be deferred out of a cell that shares its row with no
    // ~keep other cell -- pulling it out of a row with a sibling would leave that sibling's
    // ~keep column position undefined (issue #469 locks the sibling-cell shape to the
    // ~keep existing flatten-and-escape behavior; issue #484 is the single-cell-row shape).
    let is_single_cell_row = cells.len() == 1;

    // ~keep A row whose only children were non-cell elements (e.g. The parser's `read_end`
    // ~keep dropped an unmatched `</table>`, stranding a `<p>` inside this `<tr>`)
    // ~keep collects zero cells here. Bailing before any output lets the *next* real
    // ~keep row become row 0 -- and thus the header -- matching Tier 1's behavior
    // ~keep (issue #489). The caller only advances `row_index` when this returns
    // ~keep `true`, so a skipped row does not consume a row-index slot.
    if cells.is_empty() {
        return false;
    }

    #[cfg(feature = "visitor")]
    let visitor_output_start = output.len();
    #[cfg(feature = "visitor")]
    if !render.visitor_is_complete {
        if let Some(early_return) = run_row_visitor_hook(
            node_handle,
            output,
            RowVisit {
                env,
                cells: &cells,
                row_index: render.row_index,
                is_header: render.is_header,
                depth: render.depth,
            },
        ) {
            *render.has_content |= output.len() > visitor_output_start;
            return early_return;
        }
    }

    // ~keep Build the per-cell context once for the entire row.  Tier-2 hot-spot
    // ~keep pass III: avoids cloning `Context` (which holds several Rc<HashSet> and
    // ~keep optional collector handles) on every cell in wikipedia-class tables.
    let cell_ctx = super::super::super::Context {
        in_table_cell: true,
        ..env.ctx.clone()
    };

    let row_env = RowEnv { ctx: &cell_ctx, ..env };
    let first_width_edit = render.rendered_widths.as_ref().map_or(0, |widths| widths.edits.len());
    let mut filled_cols = render_row_cells(&cells, &mut row_text, row_env, render, is_single_cell_row);
    // ~keep Empty emitted cells contain only padding and delimiters; a literal content pipe is escaped.
    *render.has_content |= row_text.chars().any(|ch| ch != '|' && !ch.is_whitespace());
    pad_row(
        &mut row_text,
        &mut filled_cols,
        render.total_cols,
        render.col_widths,
        render.rendered_widths.as_deref_mut(),
    );
    append_rendered_row(output, &row_text, env.options, render, first_width_edit);
    true
}

fn append_rendered_row(
    output: &mut String,
    row_text: &str,
    options: &crate::options::ConversionOptions,
    render: &mut RowRender<'_>,
    first_width_edit: usize,
) {
    if let Some(widths) = render.rendered_widths.as_deref_mut() {
        widths.commit_row(first_width_edit, output.len() + 1);
    }
    output.push('|');
    output.push_str(row_text);
    output.push('\n');
    if render.row_index == 0 {
        let separator_start = output.len();
        emit_header_separator(output, options, render.header_cols, render.col_widths);
        if let Some(widths) = render.rendered_widths.as_deref_mut() {
            widths.edits.push(WidthEdit::Separator {
                padding: separator_start..output.len(),
                columns: render.header_cols,
            });
        }
    }
}

pub struct RowRender<'a> {
    pub visitor_is_complete: bool,
    pub row_index: usize,
    pub has_content: &'a mut bool,
    pub has_span: bool,
    pub rowspan_tracker: &'a mut [Option<usize>],
    pub total_cols: usize,
    pub header_cols: usize,
    pub depth: usize,
    pub is_header: bool,
    pub col_widths: &'a [usize],
    pub cell_cache: &'a mut CellTextCache,
    pub deferred_tables: &'a mut Vec<String>,
    pub rendered_widths: Option<&'a mut RenderedWidths>,
}

fn render_row_cells(
    cells: &[crate::dom::NodeHandle],
    row_text: &mut String,
    env: RowEnv<'_>,
    render: &mut RowRender<'_>,
    is_single_cell_row: bool,
) -> usize {
    if !render.has_span {
        for (cell_index, cell_handle) in cells.iter().enumerate() {
            emit_row_cell(
                cell_handle,
                row_text,
                env,
                CellEmission {
                    col_width: render.col_widths.get(cell_index).copied(),
                    depth: render.depth + 1,
                    column: cell_index,
                },
                render,
                is_single_cell_row,
            );
        }
        return cells.len();
    }
    render_spanned_row(cells, row_text, env, render, is_single_cell_row)
}

fn render_spanned_row(
    cells: &[crate::dom::NodeHandle],
    row_text: &mut String,
    env: RowEnv<'_>,
    render: &mut RowRender<'_>,
    is_single_cell_row: bool,
) -> usize {
    let mut col_index = 0;
    let mut cell_iter = cells.iter();
    loop {
        if emit_rowspan_continuation(
            &mut col_index,
            render.total_cols,
            render.rowspan_tracker,
            render.col_widths,
            row_text,
            render.rendered_widths.as_deref_mut(),
        ) {
            continue;
        }
        let Some(cell_handle) = cell_iter.next() else {
            break;
        };
        emit_row_cell(
            cell_handle,
            row_text,
            env,
            CellEmission {
                col_width: render.col_widths.get(col_index).copied(),
                depth: render.depth + 1,
                column: col_index,
            },
            render,
            is_single_cell_row,
        );
        let (colspan, rowspan) = get_colspan_rowspan(cell_handle, env.parser);
        if rowspan > 1 && col_index < render.total_cols {
            render.rowspan_tracker[col_index] = Some(rowspan - 1);
        }
        col_index = col_index.saturating_add(colspan);
    }
    col_index
}

/// ~keep Ragged rows must still declare the widest row's column count or GFM rejects the table
/// ~keep and renderers can discard cells beyond the delimiter row (issue #13).
fn pad_row(
    row_text: &mut String,
    filled_cols: &mut usize,
    total_cols: usize,
    col_widths: &[usize],
    mut rendered_widths: Option<&mut RenderedWidths>,
) {
    while *filled_cols < total_cols {
        let width = col_widths.get(*filled_cols).copied();
        let padding_start = row_text.len() + 1;
        row_text.push(' ');
        if let Some(width) = width {
            row_text.extend(std::iter::repeat_n(' ', width));
        }
        row_text.push_str(" |");
        if let Some(widths) = rendered_widths.as_deref_mut() {
            widths.record_cell(padding_start..padding_start + width.unwrap_or(0), *filled_cols, 0);
        }
        *filled_cols += 1;
    }
}

fn emit_header_separator(
    output: &mut String,
    options: &crate::options::ConversionOptions,
    header_cols: usize,
    col_widths: &[usize],
) {
    let total_cols = header_cols.clamp(1, MAX_TABLE_COLS);
    let is_djot = options.output_format == crate::options::OutputFormat::Djot;
    output.push('|');
    if !is_djot {
        output.push(' ');
    }
    for index in 0..total_cols {
        if index > 0 {
            output.push_str(if is_djot { "|" } else { " | " });
        }
        let dash_count = col_widths.get(index).copied().unwrap_or(0).max(MIN_SEPARATOR_DASHES);
        output.extend(std::iter::repeat_n('-', dash_count));
    }
    if !is_djot {
        output.push(' ');
    }
    output.push_str("|\n");
}

#[cfg(test)]
mod width_tests {
    use super::{MAX_CELL_WIDTH, MAX_TABLE_COLS, RenderedWidths};

    #[test]
    fn should_limit_recorded_widths_and_padding_to_supported_columns() {
        let mut widths = RenderedWidths::default();
        widths.record_cell(0..0, MAX_TABLE_COLS - 1, MAX_CELL_WIDTH + 1);
        assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
        assert_eq!(widths.widths[MAX_TABLE_COLS - 1], MAX_CELL_WIDTH);
        assert_eq!(widths.edits.len(), 1);

        widths.record_cell(0..0, MAX_TABLE_COLS, 1);
        assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
        assert_eq!(widths.edits.len(), 1);

        widths.record_cell(0..0, usize::MAX, 1);
        assert_eq!(widths.widths.len(), MAX_TABLE_COLS);
        assert_eq!(widths.edits.len(), 1);
    }
}