lumesh 0.18.2

a lighting shell ⚡ bash alternative
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
use std::collections::{BTreeMap, HashMap};
use tabled::{
    Table, Tabled,
    builder::Builder,
    settings::{
        Color, Modify, Style, Width,
        object::{Columns, Rows},
        panel::HorizontalPanel,
        peaker::PriorityMax,
    },
};

use crate::{Expression, expression::table::TableData, libs::bin::into_lib::strip_ansi_escapes};

/// 嵌套表格能接受的最小可用宽度,低于这个值就没必要画表格了
const MIN_TABLE_WIDTH: usize = 20;

/// 一列要保持"可读"所需的最小宽度:低于这个宽度,即使技术上能塞进去,
/// 也会退化成一列高瘦的竖条,观感上等价于"表格被拆碎"。
const MIN_READABLE_COL_WIDTH: usize = 4;

/// 允许在 fit_width 基础上再压缩的宽度容忍系数。
/// 适度超宽可以靠 wrap 挽回;超过太多说明列本身撑不开,
/// wrap 只会把表格拆得很碎,不如直接回退文本。
const WRAP_TOLERANCE: f64 = 1.5;

/// 计算多行字符串中"可见"最大宽度(去除 ANSI 转义序列后按字符数计)
fn visible_width(s: &str) -> usize {
    s.lines()
        .map(|l| strip_ansi_escapes(l).chars().count())
        .max()
        .unwrap_or(0)
}

/// 计算文本中最长的空白分隔 token 的可见宽度(去 ANSI)。
/// 这是 keep_words(true) 语义下,一列不可能再压缩到更窄的下限。
fn max_token_width(text: &str) -> usize {
    text.split_whitespace()
        .map(|w| strip_ansi_escapes(w).chars().count())
        .max()
        .unwrap_or(0)
}

/// 廉价预筛:只看列数 + 首行(非表头)数据总长度,
/// 用于在真正构建 Builder/Table 之前就排除明显没救的情况。
/// 这只是"跳过构建"的快速路径,不是最终决策——
/// 真正的判断在表格构建完成、fit_width 之前,对完整渲染结果测宽度
/// (见 `accept_natural_width`)。
fn quick_reject(
    cols: usize,
    first_row_total_len: usize,
    max_width: usize,
    max_wraped_width: usize,
) -> bool {
    if cols == 0 {
        return true;
    }
    if max_wraped_width + cols * 3 + 1 >= max_width {
        return true;
    }
    if cols * MIN_READABLE_COL_WIDTH > max_width {
        return true;
    }
    (first_row_total_len as f64) > max_width as f64 * WRAP_TOLERANCE
}

/// 权威判断:表格已经 build() 完毕、样式已应用,但**尚未调用 fit_width**,
/// 此时测的是自然宽度,未被强制压缩,判断才有意义。
/// 必须在这个时机调用——`Width::wrap` 之后的宽度恒 <= max_width,
/// 用它判断"要不要放弃"为时已晚(这正是最初 bug 的根因)。
fn accept_natural_width(table: &Table, max_width: usize) -> bool {
    visible_width(&table.to_string()) as f64 <= max_width as f64 * WRAP_TOLERANCE
}

/// 嵌套表格的统一收尾:先做自然宽度把关,通过才 fit_width;
/// 顶层表格(nested == false)跳过把关,保持"必须画出来"的既有行为。
fn finalize_table(mut table: Table, max_width: usize, nested: bool) -> Option<Table> {
    if nested && !accept_natural_width(&table, max_width) {
        return None;
    }
    fit_width(&mut table, max_width);
    Some(table)
}

pub fn pretty_printer(arg: &Expression) -> Result<Expression, crate::RuntimeError> {
    let specified_width = crossterm::terminal::size().unwrap_or((120, 0)).0 as usize;
    match arg {
        Expression::Table(table_data) => {
            let out = print_table_with_tabled(table_data, true, specified_width, false)
                .map(|t| t.to_string())
                .unwrap_or_else(|| format!("{arg:#}"));
            println!("{}", out)
        }
        Expression::Map(exprs) => {
            let out = pprint_map(exprs.as_ref(), true, specified_width)
                .map(|t| t.to_string())
                .unwrap_or_else(|| format!("{arg:#}"));
            println!("{}", out)
        }
        Expression::HMap(exprs) => {
            let out = pprint_hmap(exprs.as_ref(), true, specified_width)
                .map(|t| t.to_string())
                .unwrap_or_else(|| format!("{arg:#}"));
            println!("{}", out)
        }
        Expression::List(exprs) => {
            let out = pprint_list(exprs.as_ref(), true, specified_width, false)
                .map(|t| t.to_string())
                .unwrap_or_else(|| format!("{arg:#}"));
            println!("{}", out)
        }
        _ => {
            println!("{arg:#}");
        }
    }
    Ok(Expression::None)
}

pub fn pretty_formatter(arg: &Expression) -> String {
    let specified_width = crossterm::terminal::size().unwrap_or((120, 0)).0 as usize;
    match arg {
        Expression::Table(table_data) => {
            print_table_with_tabled(table_data, false, specified_width, false)
                .map(|t| t.to_string())
                .unwrap_or_else(|| format!("{arg:#}"))
        }
        Expression::Map(exprs) => pprint_map(exprs.as_ref(), false, specified_width)
            .map(|t| t.to_string())
            .unwrap_or_else(|| format!("{arg:#}")),
        Expression::HMap(exprs) => pprint_hmap(exprs.as_ref(), false, specified_width)
            .map(|t| t.to_string())
            .unwrap_or_else(|| format!("{arg:#}")),
        Expression::List(exprs) => pprint_list(exprs.as_ref(), false, specified_width, false)
            .map(|t| t.to_string())
            .unwrap_or_else(|| format!("{arg:#}")),
        _ => format!("{arg:#}"),
    }
}

#[derive(Tabled, PartialEq, Eq, PartialOrd, Ord)]
struct KeyValueRow {
    #[tabled(rename = "KEY")]
    key: String,
    #[tabled(rename = "VALUE")]
    value: String,
}

/// 尝试用子表格渲染,宽度不够/结构不适合时回退成 Display 文本
fn try_render_sub_table<F>(build: F, fallback_val: &Expression, cell_width: usize) -> String
where
    F: FnOnce() -> Option<Table>,
{
    // 空间太小,直接不画表格,连 build 都不必调用
    if cell_width < MIN_TABLE_WIDTH {
        return textwrap::fill(&format!("{fallback_val}"), cell_width.max(1));
    }

    let sub = match build() {
        Some(t) => t.to_string(),
        None => return textwrap::fill(&format!("{fallback_val}"), cell_width),
    };

    // 兜底:即使自然宽度把关通过了,wrap 之后如果内容本身仍然超宽
    // (例如单个超长 token),仍然放弃表格形式
    if visible_width(&sub) > cell_width {
        return textwrap::fill(&format!("{fallback_val}"), cell_width);
    }

    sub
}

/// 判断一个 List 是否是"记录列表"(每个元素都是 Map/HMap)
fn is_list_of_records(items: &[Expression]) -> bool {
    !items.is_empty()
        && items
            .iter()
            .all(|e| matches!(e, Expression::Map(_) | Expression::HMap(_)))
}

fn print_table_with_tabled(
    table: &TableData,
    with_color: bool,
    max_width: usize,
    nested: bool,
) -> Option<Table> {
    let group_idx = table.groups(); // 新增的访问器,已按降序排列
    let all_headers = table.headers();

    // 1. 剔除分组列后的表头(顺序与 swap_remove 语义一致)
    let mut headers = all_headers.to_vec();
    for &g in group_idx {
        headers.swap_remove(g);
    }
    let cols = headers.len();

    let mut rows_iter = table.rows().iter();
    let first_row: Vec<String> = match rows_iter.next() {
        Some(row) => row.iter().map(|x| x.to_string()).collect(),
        None => Vec::new(),
    };
    let first_row_len: usize = first_row.iter().map(|c| visible_width(c)).sum();
    let max_wraped_width: usize = first_row.iter().map(|c| max_token_width(c)).sum();
    // +3 splitter
    if nested && quick_reject(cols, first_row_len, max_width, max_wraped_width) {
        return None;
    }

    let mut current_group: Vec<String> = vec![];
    let mut panels: Vec<(usize, String)> = vec![];
    let mut builder = Builder::with_capacity(table.row_count(), cols);
    builder.push_record(&headers);

    for row in table.rows() {
        let mut row = row.clone();
        let labels: Vec<String> = group_idx
            .iter()
            .map(|&g| row.swap_remove(g).to_string())
            .collect();

        if !group_idx.is_empty() && labels != current_group {
            // 此刻 builder 里已有的记录数(含表头)就是这一分组标签应插入的行号
            panels.push((builder.count_records(), labels.join(" ")));
            current_group = labels;
        }
        builder.push_record(row.iter().map(|x| x.to_string()));
    }

    let mut built = builder.build();
    if with_color {
        built.modify(Rows::first(), Color::FG_BLUE);
    }

    if table.is_grouped() {
        for (idx, label) in panels.into_iter().rev() {
            built.with(HorizontalPanel::new(idx, format!("───── {} ─────", label)));
            // built.modify(Rows::one(idx), Border::new().bottom('─'));
        }
    }
    apply_table_style(&mut built, false, nested);

    finalize_table(built, max_width, nested)
}

/// 类型擦除后的 (key, value) 迭代器。
/// 用 Box<dyn Iterator<...>> 而不是 `impl Iterator<Item=...>` 泛型参数,
/// 是为了打断 pprint_map_internal -> render_field -> render_value -> pprint_map_internal 的
/// 递归单态化:泛型版本每递归一层都会为一个新的具体迭代器类型重新实例化
/// 一份函数体,嵌套深度在类型层面无界,会导致编译期"无限展开"
/// (reached the recursion limit while instantiating)。装箱后签名固定为
/// 同一个具体类型,递归调用不再产生新的单态化实例。
type KvIter<'a> = Box<dyn Iterator<Item = (String, Expression)> + 'a>;

fn pprint_map_internal<'a>(
    items: KvIter<'a>,
    is_hmap: bool,
    with_color: bool,
    max_width: usize,
    nested: bool,
) -> Option<Table> {
    // is_hmap 排序、以及"首元素结构判断"都需要拿到全部数据,这次 Vec 物化无法避免。
    let mut entries: Vec<(String, Expression)> = items.collect();
    if is_hmap {
        entries.sort_by(|a, b| a.0.cmp(&b.0));
    }

    // 顶层 + 首元素的值是"记录列表"(如 {directory: [{...}, {...}], file: [...]})
    // => 模仿 group 面板样式:外层 key 当 panel 标题,内层记录展开为多行、共用同一套表头
    let use_panel = !nested
        && entries
            .first()
            .map(|(_, v)| matches!(v, Expression::List(items) if is_list_of_records(items)))
            .unwrap_or(false);

    if use_panel {
        if let Some(t) =
            pprint_map_of_record_lists_as_panels(&entries, is_hmap, with_color, max_width)
        {
            return Some(t);
        }
        // 表头提取失败等极端情况,回退到原有两列逻辑
    }

    const COLS: usize = 2;
    let table_padding = COLS * 3 + 1 + 5;
    let available_width = max_width.saturating_sub(table_padding);

    let key_column_width = 12.min(available_width / 4);
    let value_budget = available_width.saturating_sub(key_column_width);

    let rows: Vec<KeyValueRow> = entries
        .into_iter()
        .map(|(key, val)| {
            let value = render_field(&val, value_budget);
            KeyValueRow { key, value }
        })
        .collect();

    if nested {
        if let Some(first) = rows.first() {
            let first_row_len = visible_width(&first.key) + visible_width(&first.value);
            let max_wraped_width = max_token_width(&first.key) + max_token_width(&first.value);
            if quick_reject(COLS, first_row_len, max_width, max_wraped_width) {
                return None;
            }
        }
    }

    let mut table = Table::new(rows);

    if is_hmap {
        if with_color {
            table.modify(Columns::first(), Color::FG_BLUE);
        }
        table.modify(
            Columns::first(),
            Width::truncate(key_column_width).suffix(""),
        );
    } else if with_color {
        table.modify(Columns::first(), Color::FG_GREEN);
    }

    apply_table_style(&mut table, is_hmap, nested);
    finalize_table(table, max_width, nested)
}

/// 顶层 map 中第一个值是"记录列表"(每个元素都是 Map/HMap,即 is_list_of_records)时使用:
/// 用第一条记录的 key 顺序作为整张表的公共表头,
/// 外层 key(如 directory/file/symlink)作为 panel 标题,
/// 该 key 对应的记录列表逐条展开为多行,字段按表头对齐、缺失留空。
/// 若某个顶层条目的值不是记录列表(混合结构),退化成单独一行(首列放值,其余列留空),
/// 同样打 panel 标签以维持结构一致。
fn pprint_map_of_record_lists_as_panels(
    entries: &[(String, Expression)],
    is_hmap: bool,
    with_color: bool,
    max_width: usize,
) -> Option<Table> {
    // 表头只看"第一个顶层条目"的第一条记录,符合"只检测第一个元素"的要求
    let headers: Vec<String> = match entries.first() {
        Some((_, Expression::List(items))) => match items.first() {
            Some(Expression::Map(m)) => m.keys().cloned().collect(),
            Some(Expression::HMap(m)) => {
                let mut ks: Vec<String> = m.keys().cloned().collect();
                ks.sort();
                ks
            }
            _ => return None,
        },
        _ => return None,
    };

    let cols = headers.len();
    if cols == 0 {
        return None;
    }

    let col_budget = (max_width.saturating_sub(cols * 3 + 1)) / cols.max(1);

    let mut builder = Builder::with_capacity(entries.len() * 4, cols);
    builder.push_record(headers.clone());

    // (插入点行号, panel 标题),插入点 = 该分组第一行落地前 builder 已有的记录数(含表头)
    let mut panels: Vec<(usize, String)> = vec![];

    for (key, val) in entries {
        match val {
            Expression::List(items) if is_list_of_records(items) => {
                panels.push((builder.count_records(), key.clone()));
                for item in items.iter() {
                    let row: Vec<String> = headers
                        .iter()
                        .map(|h| {
                            let field = match item {
                                Expression::Map(m) => m.get(h),
                                Expression::HMap(m) => m.get(h),
                                _ => None,
                            };
                            field
                                .map(|v| render_field(v, col_budget))
                                .unwrap_or_default()
                        })
                        .collect();
                    builder.push_record(row);
                }
            }
            other => {
                // 混合结构:该顶层条目不是记录列表,退化成单独一行
                panels.push((builder.count_records(), key.clone()));
                let mut row = vec![render_field(other, col_budget)];
                row.resize(cols, String::new());
                builder.push_record(row);
            }
        }
    }

    let mut table = builder.build();

    if with_color {
        table.modify(Rows::first(), Color::FG_BLUE);
    }
    table.with(
        Modify::new(Rows::first()).with(tabled::settings::format::Format::content(|s| {
            s.to_uppercase()
        })),
    );
    if is_hmap {
        // HMap 场景仍保留 key 列(此处即表头列本身不需要单独截断,
        // 因为列内容已是有限字段名而非任意长 key)
    }

    // 倒序插入,避免前面插入点被后面 panel 顶行下移
    for (idx, label) in panels.into_iter().rev() {
        table.with(HorizontalPanel::new(idx, format!("───── {} ─────", label)));
    }

    apply_table_style(&mut table, is_hmap, false);
    finalize_table(table, max_width, false)
}

/// 只有当表格自然宽度超过预算时才强制 wrap;
/// 否则不设置 Width,让 tabled 按内容自身大小渲染(避免被拉伸出空白)。
fn fit_width(table: &mut Table, max_width: usize) {
    table.with(
        Width::wrap(max_width)
            .keep_words(true)
            .priority(PriorityMax::right()),
    );
}

/// 顶层表格保留完整边框;嵌套表格去掉四周边框(只留表头分隔线),
/// 一是视觉上避免"表格套表格"的拥挤感,二是省下两侧竖线占用的宽度,
/// 缓解嵌套时外层单元格里的空白间隙问题。
fn apply_table_style(table: &mut Table, use_markdown: bool, nested: bool) {
    if nested {
        // Style::psql():无外框、无竖线,仅表头下一条横线,足够区分表头/数据
        table.with(Style::psql());
    } else if use_markdown {
        table.with(Style::markdown());
    } else {
        table.with(Style::rounded());
    }
}

fn pprint_map(
    exprs: &BTreeMap<String, Expression>,
    with_color: bool,
    max_width: usize,
) -> Option<Table> {
    pprint_map_internal(
        Box::new(exprs.iter().map(|(k, v)| (k.clone(), v.clone()))),
        false,
        with_color,
        max_width,
        false,
    )
}

pub fn pprint_hmap(
    exprs: &HashMap<String, Expression>,
    with_color: bool,
    max_width: usize,
) -> Option<Table> {
    pprint_map_internal(
        Box::new(exprs.iter().map(|(k, v)| (k.clone(), v.clone()))),
        true,
        with_color,
        max_width,
        false,
    )
}

/// 记录中的单个字段:复合类型(可能需要递归成子表格)才用 render_value
/// 的宽度预算逻辑;标量值原样输出完整文本,交给最终 Width::wrap
/// 按列实际内容统一决定是否换行/如何分配宽度,避免"提前按平均值
/// 切碎"导致某些列被过度换行、另一些列却有富余空间。
fn render_field(val: &Expression, cell_width: usize) -> String {
    match val {
        Expression::HMap(_) | Expression::Map(_) => render_value(val, cell_width, false, true),
        Expression::List(items) if is_list_of_records(items) => {
            render_value(val, cell_width, false, true)
        }
        Expression::Table(_) => render_value(val, cell_width, false, true),
        _ => format!("{val}"),
    }
}

fn render_value(val: &Expression, cell_width: usize, with_color: bool, nested: bool) -> String {
    match val {
        Expression::HMap(m) => try_render_sub_table(
            || {
                pprint_map_internal(
                    Box::new(m.iter().map(|(k, v)| (k.clone(), v.clone()))),
                    true,
                    with_color,
                    cell_width,
                    nested,
                )
            },
            val,
            cell_width,
        ),
        Expression::Map(m) => try_render_sub_table(
            || {
                pprint_map_internal(
                    Box::new(m.iter().map(|(k, v)| (k.clone(), v.clone()))),
                    false,
                    with_color,
                    cell_width,
                    nested,
                )
            },
            val,
            cell_width,
        ),
        Expression::List(items) if is_list_of_records(items) => try_render_sub_table(
            || pprint_list(items, with_color, cell_width, nested),
            val,
            cell_width,
        ),
        Expression::Table(t) => try_render_sub_table(
            || print_table_with_tabled(t, false, cell_width, nested),
            val,
            cell_width,
        ),
        _ => textwrap::fill(&format!("{val}"), cell_width),
    }
}

fn pprint_list(
    exprs: &[Expression],
    with_color: bool,
    max_width: usize,
    nested: bool,
) -> Option<Table> {
    let (rows, heads_opt) = TableRow {
        rows: exprs,
        max_width,
        col_padding: 5,
    }
    .split_into_rows();

    if rows.is_empty() {
        return Some(Table::default());
    }

    // 廉价预筛:列数 + 首行长度
    if nested {
        let cols = heads_opt.as_ref().map(|h| h.len()).unwrap_or(rows[0].len());
        let first_row_len: usize = rows[0].iter().map(|c| visible_width(c)).sum();
        let max_wraped_width: usize = rows[0].iter().map(|c| max_token_width(c)).sum();

        if quick_reject(cols, first_row_len, max_width, max_wraped_width) {
            return None;
        }
    }

    let mut builder;

    let has_header = match heads_opt {
        Some(heads) => {
            builder = Builder::with_capacity(rows.len(), heads.len());
            builder.insert_record(0, heads);
            true
        }
        _ => {
            builder = Builder::with_capacity(rows.len(), rows[0].len());
            false
        }
    };
    for row in rows {
        builder.push_record(row);
    }

    let mut table = builder.build();

    if has_header {
        if with_color {
            table.modify(Rows::first(), Color::FG_BLUE);
        }
        table.with(
            Modify::new(Rows::first()).with(tabled::settings::format::Format::content(|s| {
                s.to_uppercase()
            })),
        );
    }

    apply_table_style(&mut table, false, nested);
    finalize_table(table, max_width, nested)
}

struct TableRow<'a> {
    rows: &'a [Expression],
    max_width: usize,
    col_padding: usize,
}

impl<'a> TableRow<'a> {
    fn split_into_rows(&self) -> (Vec<Vec<String>>, Option<Vec<String>>) {
        let mut result = Vec::with_capacity(self.rows.len());

        let heads = match self.rows.first() {
            Some(Expression::List(a)) => {
                Some(a.iter().enumerate().map(|(i, _)| format!("C{i}")).collect())
            }
            Some(Expression::HMap(a)) => Some(a.keys().cloned().collect::<Vec<String>>()),
            Some(Expression::Map(a)) => Some(a.keys().cloned().collect::<Vec<String>>()),
            _ => None,
        };
        let mut cols = heads.as_ref().map_or(0, |h| h.len());
        let mut current_row = Vec::with_capacity(cols);

        if cols > 0 {
            // per_cell_width 仅用作"复合值需要递归建子表时"的预算上限,
            // 不再用来提前截断标量字段——标量字段的实际宽度应由最终的
            // Width::wrap(max_width) 统一、按列实际内容智能分配,而不是
            // 建表前就被平均切分打断。
            let score_sum = self
                .rows
                .iter()
                .map(|x| {
                    if matches!(
                        x,
                        Expression::List(_) | Expression::Map(_) | Expression::HMap(_)
                    ) {
                        3
                    } else {
                        1
                    }
                })
                .sum::<usize>();

            let per_cell_width =
                ((self.max_width / score_sum) * 3).saturating_sub(self.col_padding);

            for expr in self.rows.iter() {
                match expr {
                    Expression::List(a) => {
                        for c in a.iter() {
                            current_row.push(render_field(c, per_cell_width));
                        }
                    }
                    Expression::HMap(a) => {
                        for (_, v) in a.iter() {
                            current_row.push(render_field(v, per_cell_width));
                        }
                    }
                    Expression::Map(a) => {
                        for (_, v) in a.iter() {
                            current_row.push(render_field(v, per_cell_width));
                        }
                    }
                    other => current_row.push(other.to_string()),
                };
                if !current_row.is_empty() {
                    result.push(current_row);
                    current_row = vec![];
                }
            }
            return (result, heads);
        }

        // 一维表格
        let mut current_len = 0;
        for (i, expr) in self.rows.iter().enumerate() {
            let col = match expr {
                Expression::List(a) => a
                    .as_ref()
                    .iter()
                    .map(|f| f.to_string())
                    .collect::<Vec<String>>()
                    .join(", "),
                Expression::HMap(a) => a
                    .as_ref()
                    .values()
                    .map(|v| v.to_string())
                    .collect::<Vec<String>>()
                    .join("\t"),
                Expression::Map(a) => a
                    .as_ref()
                    .values()
                    .map(|v| v.to_string())
                    .collect::<Vec<String>>()
                    .join("\t"),
                other => other.to_string(),
            };
            let col_width = strip_ansi_escapes(&col).chars().count() + self.col_padding;

            // 两种情况需要换行:
            // 1. 当前行已有内容且加入新列会超限
            // 2. 单列宽度已超过总限制(需强制拆分列)
            if cols == 0 {
                if !current_row.is_empty() && current_len + col_width > self.max_width {
                    cols = i;
                    result.push(current_row);
                    current_row = vec![];
                    current_len = 0;
                }
            } else if i % cols == 0 {
                result.push(current_row);
                current_row = vec![];
                current_len = 0;
            }
            // 处理超宽列(需拆分成多段)
            if col_width > self.max_width {
                let chunks = self.split_column(&col);
                for chunk in chunks {
                    if !current_row.is_empty() {
                        result.push(current_row);
                        current_row = vec![];
                    }
                    current_row.push(chunk);
                }
                current_len = current_row.last().map(|s| s.len()).unwrap_or(0);
            } else {
                current_row.push(col);
                current_len += col_width;
            }
        }

        if !current_row.is_empty() {
            result.push(current_row);
        }
        (result, None)
    }

    fn split_column(&self, text: &str) -> Vec<String> {
        let max_chunk = self.max_width.saturating_sub(self.col_padding);
        if max_chunk == 0 {
            return vec![text.to_string()];
        }

        // 使用textwrap进行智能换行,考虑单词边界
        textwrap::wrap(text, max_chunk)
            .into_iter()
            .map(|s| s.to_string())
            .collect()
    }
}