monothink 0.7.0

A totally non-agentic coding assistant
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
/*
* This file is part of monothink.
*
* monothink is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* monothink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with monothink.
* If not, see <https://www.gnu.org/licenses/>.

*/

use crate::{
    common::conversation::{Block, Inline, ListItem, ListItemMarker, TableRow},
    config::Symbols,
    ui::style::{
        DARK_GRAY2, DARK_GRAY3, GUTTER, GUTTER_WIDTH, HighlightConfig, METALLIC_BLUE, NEAR_BLACK,
        SyntectStyle, TextStyle,
    },
};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use std::{cmp::max, iter};
use syntect::{easy::HighlightLines, highlighting::FontStyle};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedTableCell {
    content: Vec<Line<'static>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedTableRow {
    content: Vec<RenderedTableCell>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedTable {
    content: Vec<RenderedTableRow>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InlineFragment {
    Text(Span<'static>),
    LineBreak,
}
// #[derive(Debug, Clone, Default)]
// pub struct RenderState {
//     pub highlight_cfg: HighlightConfig,
//     pub style: TextStyle,
// }

#[derive(Debug, Clone, Default)]
pub struct RenderConfig {
    pub highlight_cfg: HighlightConfig,
    pub style: TextStyle,
    pub symbols: Symbols,
    pub width: u16,
}
impl RenderConfig {
    pub fn new() -> Self {
        RenderConfig {
            highlight_cfg: HighlightConfig::new(),
            style: TextStyle::default(),
            symbols: Symbols::default(),
            width: 0,
        }
    }

    pub fn with_style(mut self, style: TextStyle) -> Self {
        self.style = style;

        self
    }
}

pub fn render_block(
    block: &Block,
    config: &RenderConfig,
    //render_state: Option<&mut RenderState>,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    match block {
        Block::Code {
            lang,
            content,
            copy_id,
        } => lines.extend(render_code(content, lang, *copy_id, config)),
        Block::Heading { depth, content } => lines.extend(render_heading(content, *depth, config)),
        Block::List { content } => lines.extend(render_list(content, config)),
        Block::Paragraph(inlines) => lines.extend(render_paragraph(inlines, config)),
        Block::Quote(blocks) => lines.extend(render_quote(blocks, config)),
        Block::Table { content } => lines.extend(render_table(content, config)),
        Block::ThematicBreak => {
            let delim_style = TextStyle {
                fg_color: DARK_GRAY2,
                ..config.style
            };
            lines.push(Line::styled("────────────────", delim_style))
        }
        Block::Unsupported(s) => {
            // @todo render warning only if requested by user in config
            let warning_style = TextStyle {
                fg_color: Color::Red,
                ..config.style
            };
            lines.push(Line::from(Span::styled(
                format!("Warning: Unsupported block in markdown: {s}"),
                warning_style,
            )))
        }
    }
    // @todo do not render empty line after a block but only between two blocks
    // maybe have a render_blocks function that splits before the last block to achieve that
    lines.push(Line::raw(" "));

    lines
}

pub fn render_inline(inline: &Inline, config: &RenderConfig) -> Vec<InlineFragment> {
    let mut fragments = Vec::new();
    match inline {
        Inline::Code(code) => {
            let mut s = config.style.clone();
            s.bg_color = NEAR_BLACK;
            fragments.push(InlineFragment::Text(Span::styled(code.to_owned(), s)))
        }
        Inline::Emphasis(inlines) => {
            let mut config = config.clone();
            config.style.italic = true;
            fragments.extend(
                inlines
                    .iter()
                    .flat_map(|inline| render_inline(inline, &config))
                    .collect::<Vec<InlineFragment>>(),
            )
        }
        Inline::StrongEmphasis(inlines) => {
            let mut config = config.clone();
            config.style.bold = true;
            fragments.extend(
                inlines
                    .iter()
                    .flat_map(|inline| render_inline(inline, &config))
                    .collect::<Vec<InlineFragment>>(),
            )
        }
        Inline::Link { url, title, label } => fragments.push(InlineFragment::Text(Span::styled(
            url.to_owned(),
            Style::from(config.style.clone()),
        ))),
        Inline::Image(_) => {}
        Inline::LineBreak => fragments.push(InlineFragment::LineBreak),
        Inline::Text(text) => fragments.push(InlineFragment::Text(Span::styled(
            text.to_owned(),
            Style::from(config.style.clone()),
        ))),
        Inline::Unsupported(_) => {
            // @todo render warning if requested by user in config
        }
    }
    // Block::Paragraph(text) => Self::wrap_paragraph(text, width)
    //     .into_iter()
    //     .map(Line::raw)
    //     .collect(), //render_paragraph(text),
    // Block::Quote(text) => Self::wrap_paragraph(text, width)
    //     .into_iter()
    //     .map(Line::raw)
    //     .collect(), // render_quote(text),
    // MessageElement::Code { language, source } => vec![], //render_code(language, source), //
    fragments
}

pub fn render_heading(content: &[Inline], depth: u8, config: &RenderConfig) -> Vec<Line<'static>> {
    let mut lines = Vec::new();

    // marker
    let marker = match depth {
        0 => "█ ",
        1 => "▊ ",
        2 => "▌ ",
        _ => "▎ ",
    };

    // header content
    let mut fragments = Vec::new();
    let mut new_config = config.clone();
    new_config.style.bold = true;
    new_config.style.fg_color = METALLIC_BLUE;
    for inline in content {
        fragments.extend(render_inline(inline, &new_config));
    }
    let mut content_lines = wrap_lines(fragments_to_lines(&fragments), config.width, None);

    // add marker
    if let Some(first) = content_lines.get_mut(0) {
        first
            .spans
            .insert(0, Span::styled(marker, new_config.style.clone()));
    }
    for line in content_lines.iter_mut().skip(1) {
        line.spans.insert(
            0,
            Span::styled(" ".repeat(marker.width()), new_config.style.clone()),
        );
    }

    // add delimiter
    if let Some(last) = content_lines.last_mut() {
        // let width = last.spans.iter().fold(0, |l, s| l + s.content.width());
        let delim_style = TextStyle {
            fg_color: DARK_GRAY2,
            ..config.style
        };
        last.push_span(Span::styled(
            // " ".to_owned() + &"─".repeat(remaining_width.saturating_sub(width)),
            " ".to_owned() + &"─".repeat(7),
            delim_style,
        ));
    }

    lines.extend(content_lines);
    lines
}

pub fn render_list(content: &[ListItem], config: &RenderConfig) -> Vec<Line<'static>> {
    // get indend
    let marker_indend = content.iter().fold(2, |current, item| {
        let candidate = match item.marker {
            ListItemMarker::Bullet => 2,      // @todo depends on string width
            ListItemMarker::Checkbox(_) => 2, // @todo depends on string width
            ListItemMarker::Number(index) => index.to_string().len() + 2,
        };
        max(current, candidate)
    });

    // render item content
    content
        .iter()
        .flat_map(|item| render_list_item(item, marker_indend, config))
        .collect()
}

pub fn render_list_item(
    item: &ListItem,
    marker_indend: usize,
    config: &RenderConfig,
) -> Vec<Line<'static>> {
    let config = RenderConfig {
        highlight_cfg: config.highlight_cfg.clone(),
        style: config.style.clone(),
        symbols: config.symbols.clone(),
        width: config.width.saturating_sub(marker_indend as u16),
    };

    // render blocks
    let mut lines: Vec<Line<'static>> = item
        .content
        .iter()
        .flat_map(|block| render_block(block, &config))
        .collect();

    // add marker
    if let Some(first_line) = lines.first_mut() {
        let marker = match &item.marker {
            ListItemMarker::Bullet => {
                let marker = "• ".to_string();
                Span::styled(
                    format!(
                        "{}{}",
                        marker,
                        " ".repeat(marker_indend.saturating_sub(marker.width()))
                    ),
                    config.style.clone(),
                )
            }
            ListItemMarker::Checkbox(checked) => {
                let marker = (if *checked { "☑ " } else { "☐ " }).to_string();
                Span::styled(
                    format!(
                        "{}{}",
                        marker,
                        " ".repeat(marker_indend.saturating_sub(marker.width()))
                    ),
                    config.style.clone(),
                )
            }
            ListItemMarker::Number(n) => Span::styled(
                format!(
                    "{}. {}",
                    n,
                    " ".repeat(marker_indend.saturating_sub(*n as usize + 1))
                ),
                config.style.clone(),
            ),
        };
        first_line.spans.insert(0, marker);
    }

    // indend remaining lines
    for line in &mut lines.iter_mut().skip(1) {
        line.spans.insert(
            0,
            Span::styled(" ".repeat(marker_indend), config.style.clone()),
        );
    }

    lines
}

pub fn render_paragraph(inlines: &[Inline], config: &RenderConfig) -> Vec<Line<'static>> {
    let mut lines = fragments_to_lines(
        &inlines
            .iter()
            .flat_map(|inline| render_inline(inline, config))
            .collect::<Vec<InlineFragment>>(),
    );
    lines = wrap_lines(lines, config.width, None);

    lines
}

pub fn render_quote(content: &[Block], config: &RenderConfig) -> Vec<Line<'static>> {
    // @todo line wrapping with indend (like psalms)
    let config = RenderConfig {
        highlight_cfg: config.highlight_cfg.clone(),
        style: config.style.clone(),
        symbols: config.symbols.clone(),
        width: config.width.saturating_sub(*GUTTER_WIDTH),
    };
    let lines = content
        .iter()
        .flat_map(|block| render_block(block, &config))
        .collect();

    add_gutter(lines, DARK_GRAY2, None)
}

// first row is treated as the header
// https://drafts.csswg.org/css3-tables-algorithms/Overview.src.htm
pub fn render_table(content: &[TableRow], config: &RenderConfig) -> Vec<Line<'static>> {
    let separator_prefill = 1;
    let separator_postfill = 1;
    let separator = format!(
        "{}│{}",
        " ".repeat(separator_prefill),
        " ".repeat(separator_postfill)
    );

    let mut prerendered_table = prerender_table(content, config);

    let num_columns = content
        .iter()
        .fold(0, |count, row| max(count, row.content.len()));

    let prefered_column_widths = prefered_column_width(&prerendered_table, num_columns);

    render_table_when_within_constraints(
        &mut prerendered_table,
        prefered_column_widths.clone(),
        &prefered_column_widths,
        &separator,
        separator_prefill,
        config,
    )
    .or_else(|| {
        let min_column_widths =
            min_column_width(&prerendered_table, num_columns, char::is_whitespace);
        render_table_when_within_constraints(
            &mut prerendered_table,
            min_column_widths,
            &prefered_column_widths,
            &separator,
            separator_prefill,
            config,
        )
    })
    .or_else(|| {
        let min_column_widths = min_column_width(&prerendered_table, num_columns, |c| {
            !char::is_alphanumeric(c)
        });
        render_table_when_within_constraints(
            &mut prerendered_table,
            min_column_widths,
            &prefered_column_widths,
            &separator,
            separator_prefill,
            config,
        )
    })
    .unwrap_or_else(|| {
        tracing::debug!("Rendering table breaking at fixed positions.");
        // @todo if this still is to large, assign column width based on preferred width ratio and hard break
        let column_widths =
            column_widths_by_ratio(&prefered_column_widths, &separator, config.width.into());
        render_table_with_constraints(
            &mut prerendered_table,
            &column_widths,
            &separator,
            separator_prefill,
            config,
        )
    })
}

fn column_widths_by_ratio(
    prefered_column_widths: &[usize],
    separator: &str,
    max_width: usize,
) -> Vec<usize> {
    let available_width = max_width
        .saturating_sub(separator.width() * prefered_column_widths.len().saturating_sub(1))
        as f64;
    let total_requested_width = prefered_column_widths.iter().max().unwrap_or(&0).to_owned() as f64;

    let mut column_widths: Vec<usize> = prefered_column_widths
        .iter()
        .map(|w| (*w as f64) / total_requested_width * available_width)
        .map(|w| w.round() as usize)
        .collect();

    // rouding might result in a table larger than max_width
    // simply fix that by reducing the largest columns width
    while required_row_width(&column_widths, separator) > max_width {
        let max_width = column_widths
            .iter_mut()
            .max()
            .expect("min_column_width should not be empty after check at start of function");
        *max_width -= 1;
    }

    column_widths
}

fn enlarge_columns(
    min_column_widths: &mut [usize],
    prefered_column_widths: &[usize],
    infix: &str,
    max_width: usize,
) {
    if min_column_widths.is_empty() {
        return;
    }

    let remaining_width = max_width.saturating_sub(required_row_width(min_column_widths, infix));
    if remaining_width == 0 {
        return;
    }

    let delta_widths: Vec<f64> = prefered_column_widths
        .iter()
        .zip(min_column_widths.iter())
        .map(|(prefered, min)| prefered.saturating_sub(*min) as f64)
        .collect();

    let total_delta: f64 = delta_widths.iter().sum();
    if total_delta == 0.0 {
        return;
    }

    let added_widths: Vec<usize> = delta_widths
        .iter()
        .map(|w| w / total_delta * remaining_width as f64)
        .map(|w| w.round() as usize)
        .collect();

    for (min_col_width, added_width) in min_column_widths.iter_mut().zip(added_widths) {
        *min_col_width += added_width;
    }

    // rouding might result in a table larger than max_width
    // simply fix that by reducing the largest columns width
    while required_row_width(min_column_widths, infix) > max_width {
        let max_width = min_column_widths
            .iter_mut()
            .max()
            .expect("min_column_width should not be empty after check at start of function");
        *max_width -= 1;
    }
}

// transpose a vector of cells containing lines into a vector of lines
pub fn render_table_row(
    cells: &[RenderedTableCell],
    column_widths: &[usize],
    indend: &str,
    separator: &str,
    config: &RenderConfig,
) -> Vec<Line<'static>> {
    let mut sep = indend;
    if let Some(cell) = cells.first() {
        let len = cell.content.len();

        (0..len)
            .map(|i| {
                sep = indend;
                Line::from(
                    cells
                        .iter()
                        .enumerate()
                        .flat_map(|(j, cell)| {
                            let mut line =
                                vec![Span::styled(sep.to_string(), config.style.clone())];
                            sep = separator;
                            let content_width =
                                cell.content[i].spans.iter().fold(0, |l, s| l + s.width());
                            let num_fill_chars = column_widths
                                .get(j)
                                .unwrap_or(&0)
                                .saturating_sub(content_width);
                            line.extend(cell.content[i].spans.clone());
                            line.push(Span::raw(" ".repeat(num_fill_chars)));
                            line
                        })
                        .collect::<Vec<_>>(),
                )
            })
            .collect()
    } else {
        Vec::new()
    }
}

fn render_table_with_constraints(
    prerendered_table: &mut RenderedTable,
    column_widths: &[usize],
    separator: &str,
    separator_prefill: usize,
    config: &RenderConfig,
) -> Vec<Line<'static>> {
    // we want to left align tables but have a little space if they do not need all
    let indend = if (config.width as usize).saturating_sub(column_widths.iter().sum()) > 0 {
        " "
    } else {
        ""
    };

    for row in &mut prerendered_table.content {
        for (col, cell) in row.content.iter_mut().enumerate() {
            cell.content = wrap_lines(cell.content.clone(), column_widths[col] as u16, None);
        }
    }

    // get maximum height of each row and fill all cells to that height
    let mut max_row_height = vec![0; prerendered_table.content.len()];
    for (idx, row) in prerendered_table.content.iter().enumerate() {
        for cell in row.content.iter() {
            let content_height = cell.content.len();
            if content_height > max_row_height[idx] {
                max_row_height[idx] = content_height;
            }
        }
    }
    for (idx, row) in prerendered_table.content.iter_mut().enumerate() {
        for cell in row.content.iter_mut() {
            while cell.content.len() < max_row_height[idx] {
                cell.content.push(Line::raw(""));
            }
        }
    }

    let mut lines = Vec::new();
    // render header
    if let Some(header) = prerendered_table.content.first() {
        lines.extend(render_table_row(
            &header.content,
            column_widths,
            indend,
            separator,
            config,
        ));
    }

    // render separator line
    let mut spans = Vec::new();
    if let Some(column) = column_widths.first() {
        spans.push(Span::styled(
            format!("{}{}", indend, "─".repeat(*column)),
            config.style.clone(),
        ));
    }
    spans.extend(column_widths.iter().skip(1).map(|l| {
        Span::styled(
            format!(
                "{}┼{}",
                "─".repeat(separator_prefill),
                "─".repeat((l + separator.width()).saturating_sub(separator_prefill + 1))
            ),
            config.style.clone(),
        )
    }));
    lines.push(Line::from(spans));

    // render rows
    lines.extend(
        prerendered_table.content.iter().skip(1).flat_map(|row| {
            render_table_row(&row.content, column_widths, indend, separator, config)
        }),
    );

    lines
}

pub fn render_code(
    content: &str,
    lang: &str,
    copy_id: u32,
    config: &RenderConfig,
) -> Vec<Line<'static>> {
    // @todo line wrapping with icon
    let config = RenderConfig {
        style: TextStyle {
            bg_color: DARK_GRAY3,
            // fg_color: Color::Yellow,
            ..config.style.clone()
        },
        width: config.width - *GUTTER_WIDTH,
        ..config.clone()
    };
    let mut header_style = config.style.clone();
    header_style.bg_color = DARK_GRAY3;
    header_style.italic = true;

    // this is a case where "everything is a line" is problematic
    // We need a hack to right align the copy symbol and to make the background rectangular
    // let mut content_lines = Self::format_code(content, lang, code_style.clone());
    let mut content_lines = wrap_lines(
        highlight_code(content, lang, &config),
        config.width - 1, // observe the space we add below
        Some(Span::styled(
            config.symbols.line_wrap_indicator.clone(),
            config.style.clone(),
        )),
    );
    let mut max_width = content_lines
        .iter()
        .fold(0, |max_width, line| std::cmp::max(max_width, line.width()));
    max_width += 1; // add some space to the end
    for line in content_lines.iter_mut() {
        line.push_span(Span::styled(
            " ".repeat(max_width.saturating_sub(line.width())),
            config.style.clone(),
        ))
    }

    let lang_marker = format!("{} {}", config.symbols.language_indicator, lang);
    let copy_marker = format!("{} {} ", config.symbols.copy_indicator, copy_id);
    let header = iter::once(Line::from(Span::styled(
        format!(
            "{}{}{}",
            lang_marker,
            " ".repeat(max_width.saturating_sub(lang_marker.width() + copy_marker.width())),
            copy_marker
        ),
        Style::from(header_style),
    )));

    let lines = header.chain(content_lines).collect();

    add_gutter(lines, DARK_GRAY2, Some(DARK_GRAY3))
}

// better add_gutter: render_message(Fn -> Lines, color) { header, body (minus gutter width), gutter)
pub fn add_gutter(
    lines: Vec<Line<'static>>,
    color: Color,
    bg_color: Option<Color>,
) -> Vec<Line<'static>> {
    lines
        .into_iter()
        .map(|line| {
            let mut style = Style::default().fg(color);
            style.bg = bg_color;
            let mut spans = Vec::with_capacity(line.spans.len() + 1);

            spans.push(Span::styled(GUTTER, style));

            spans.extend(line.spans);

            Line::from(spans)
        })
        .collect()
}

fn highlight_code(code: &str, lang: &str, config: &RenderConfig) -> Vec<Line<'static>> {
    let syntax = config
        .highlight_cfg
        .syntax_set
        .find_syntax_by_token(lang)
        .unwrap_or_else(|| config.highlight_cfg.syntax_set.find_syntax_plain_text());
    let mut highlighter = HighlightLines::new(syntax, &config.highlight_cfg.theme);

    code.lines()
        .map(|line| {
            let ranges = highlighter
                .highlight_line(line, &config.highlight_cfg.syntax_set)
                .unwrap();
            Line::from(ranges_to_spans(ranges, config.style.clone()))
        })
        .collect()
}

fn ranges_to_spans(ranges: Vec<(SyntectStyle, &str)>, base_style: TextStyle) -> Vec<Span<'static>> {
    ranges
        .into_iter()
        .map(|(style, text)| {
            Span::styled(
                text.to_string(),
                merge_syntect_style(style, base_style.clone()),
            )
        })
        .collect()
}

fn merge_syntect_style(style: SyntectStyle, base_style: TextStyle) -> Style {
    let mut result = Style::default()
        .fg(Color::Rgb(
            style.foreground.r,
            style.foreground.g,
            style.foreground.b,
        ))
        .bg(base_style.bg_color);

    if style.font_style.contains(FontStyle::BOLD) {
        result = result.add_modifier(Modifier::BOLD);
    }

    if style.font_style.contains(FontStyle::ITALIC) {
        result = result.add_modifier(Modifier::ITALIC);
    }

    if style.font_style.contains(FontStyle::UNDERLINE) {
        result = result.add_modifier(Modifier::UNDERLINED);
    }

    result
}

pub fn fragments_to_lines(fragments: &[InlineFragment]) -> Vec<Line<'static>> {
    fragments
        .split(|fragment| *fragment == InlineFragment::LineBreak)
        .map(|slice| {
            slice
                .iter()
                .filter_map(|f| match f {
                    InlineFragment::Text(span) => Some(span.to_owned()),
                    InlineFragment::LineBreak => None, // should not be there
                })
                .collect::<Vec<Span<'static>>>()
        })
        .map(Line::from)
        .collect()
}

pub fn wrap_lines(
    lines: Vec<Line<'static>>,
    width: u16,
    wrap_indicator: Option<Span<'static>>,
) -> Vec<Line<'static>> {
    lines
        .into_iter()
        .flat_map(|line| wrap_line(line, width, 0, wrap_indicator.clone()))
        .collect()
}

pub fn wrap_line(
    line: Line<'static>,
    width: u16,
    position: usize,
    wrap_indicator: Option<Span<'static>>,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let mut current_line = Vec::new();
    let mut position = position;
    current_line.clear();
    for span in line.spans {
        let mut current_span = Some(span);
        while let Some(s) = current_span {
            match wrap_span(s, width, position) {
                (Some(span), None) => {
                    let increment = span.content.width();
                    current_line.push(span);
                    position += increment;
                    current_span = None; // done, end loop
                }
                (Some(span1), Some(span2)) => {
                    current_line.push(span1);
                    lines.push(Line::from(current_line.clone()));
                    current_line.clear();
                    if let Some(indicator) = wrap_indicator.clone() {
                        position = indicator.width();
                        current_line.push(indicator);
                    } else {
                        position = 0;
                    }
                    current_span = Some(span2);
                }
                (None, Some(span)) => {
                    lines.push(Line::from(current_line.clone()));
                    current_line.clear();
                    if let Some(indicator) = wrap_indicator.clone() {
                        position = indicator.width();
                        current_line.push(indicator);
                    } else {
                        position = 0;
                    }
                    current_span = Some(span);
                }
                (None, None) => {
                    // should never happen
                    // break anyhow
                    tracing::warn!(
                        "Hit a case of breaking spans resulting in both spans being None"
                    );
                    current_span = None;
                }
            }
        }
    }

    if !current_line.is_empty() {
        lines.push(Line::from(current_line));
    }

    lines
}

// handle very long words (larger than width)
fn wrap_span(
    span: Span<'static>,
    width: u16,
    position: usize,
) -> (Option<Span<'static>>, Option<Span<'static>>) {
    let width: usize = width.into();
    let style = span.style;

    let mut pos = position;
    let mut first = Vec::new();
    let mut second = Vec::new();

    // break at word boundary
    for chunk in span.content.split_inclusive(char::is_whitespace) {
        let w = UnicodeWidthStr::width(chunk);
        pos += w;
        if pos <= width {
            first.push(chunk);
        } else {
            second.push(chunk);
        }
    }

    // // check for in-word break and break alphanumeric
    if let Some(w) = second.first().map(ToOwned::to_owned)
        && UnicodeWidthStr::width(w) >= width
    {
        let mut old_second = second;
        second = Vec::new();
        for chunk in w.split_inclusive(|c: char| !c.is_alphanumeric()) {
            let w = UnicodeWidthStr::width(chunk);
            pos += w;
            if pos <= width {
                first.push(chunk);
            } else {
                second.push(chunk);
            }
        }
        second.append(&mut old_second);
    }

    // check for in-word break and fall back to character-width aware hard splitting
    if let Some(w) = second.first()
        && UnicodeWidthStr::width(*w) >= width
    {
        // use character width aware splitting
        let first_width = first.iter().fold(0, |count, text| count + text.width());
        let target_display_width = width.saturating_sub(first_width);
        let mut current_width = 0;
        let mut split_char_index = 0;

        for (byte_idx, ch) in w.char_indices() {
            let ch_width = ch.width().unwrap_or_default();
            if current_width + ch_width > target_display_width {
                break;
            }
            current_width += ch_width;
            split_char_index = byte_idx + ch.len_utf8();
        }
        let (w1, w2) = w.split_at(split_char_index);

        first.push(w1);
        second.insert(0, w2);
    }

    // assemble result
    let res1 = if first.is_empty() {
        None
    } else {
        Some(Span::from(first.join("")).style(style))
    };
    let res2 = if second.is_empty() {
        None
    } else {
        Some(Span::from(second.join("")).style(style))
    };
    (res1, res2)
}

fn min_column_width(
    prerendered_table: &RenderedTable,
    num_columns: usize,
    split_condition: fn(char) -> bool,
) -> Vec<usize> {
    let mut widths = vec![0; num_columns];

    for row in &prerendered_table.content {
        for (col, cell) in row.content.iter().enumerate() {
            let max_cell_width = cell
                .content
                .iter()
                .flat_map(|line| {
                    line.to_string()
                        .split(split_condition)
                        .map(|elem| elem.to_owned())
                        .collect::<Vec<String>>()
                })
                .map(|elem| elem.width())
                .max()
                .unwrap_or(0);
            widths[col] = widths[col].max(max_cell_width);
        }
    }
    widths
}

// num columns is not strictly need but avoids needless recomputation
fn prefered_column_width(prerendered_table: &RenderedTable, num_columns: usize) -> Vec<usize> {
    let prefered_cell_width: Vec<Vec<usize>> = prerendered_table
        .content
        .iter()
        .map(|row| {
            row.content
                .iter()
                .map(|cell| {
                    cell.content
                        .iter()
                        .map(|line| line.width())
                        .max()
                        .unwrap_or_default()
                })
                .collect()
        })
        .collect();

    prefered_cell_width
        .iter()
        .fold(vec![0; num_columns], |widths, row| {
            widths
                .into_iter()
                .zip(row)
                .map(|(current, candidate)| max(current, *candidate))
                .collect()
        })
}

// table is guaranteed to have the same number of columns in every row
fn prerender_table(content: &[TableRow], config: &RenderConfig) -> RenderedTable {
    // calculate number of columns
    let num_columns = content
        .iter()
        .fold(0, |count, row| max(count, row.content.len()));

    // prerender table
    let rows: Vec<_> = content
        .iter()
        .map(|row| {
            let mut cells: Vec<_> = row
                .content
                .iter()
                .map(|cell| {
                    let fragments = cell
                        .content
                        .iter()
                        .flat_map(|inline| render_inline(inline, config))
                        .collect::<Vec<_>>();
                    RenderedTableCell {
                        content: fragments_to_lines(&fragments),
                    }
                })
                .collect();

            // fill missing cells with empty Line
            while cells.len() < num_columns {
                cells.push(RenderedTableCell {
                    content: vec![Line::raw("")],
                });
            }
            RenderedTableRow { content: cells }
        })
        .collect();

    RenderedTable { content: rows }
}

fn render_table_when_within_constraints(
    prerendered_table: &mut RenderedTable,
    mut requested_column_widths: Vec<usize>,
    prefered_column_widths: &[usize],
    separator: &str,
    separator_prefill: usize,
    config: &RenderConfig,
) -> Option<Vec<Line<'static>>> {
    if required_row_width(&requested_column_widths, separator) <= config.width.into() {
        enlarge_columns(
            &mut requested_column_widths,
            prefered_column_widths,
            separator,
            config.width.into(),
        );
        Some(render_table_with_constraints(
            prerendered_table,
            &requested_column_widths,
            separator,
            separator_prefill,
            config,
        ))
    } else {
        None
    }
}

fn required_row_width(column_widths: &[usize], separator: &str) -> usize {
    column_widths.iter().sum::<usize>() + (column_widths.len() - 1) * separator.width()
}