git-delta 0.11.1

A syntax-highlighting pager for git
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
use syntect::highlighting::Style as SyntectStyle;
use unicode_segmentation::UnicodeSegmentation;

use crate::config::INLINE_SYMBOL_WIDTH_1;

use crate::config::Config;
use crate::delta::DiffType;
use crate::delta::State;
use crate::features::line_numbers::{self, SideBySideLineWidth};
use crate::features::side_by_side::{available_line_width, line_is_too_long, Left, Right};
use crate::minusplus::*;
use crate::paint::LineSections;
use crate::style::Style;

/// See [`wrap_line`] for documentation.
#[derive(Clone, Debug)]
pub struct WrapConfig {
    pub left_symbol: String,
    pub right_symbol: String,
    pub right_prefix_symbol: String,
    // In fractions of 1000 so that a >100 wide panel can
    // still be configured down to a single character.
    pub use_wrap_right_permille: usize,
    // This value is --wrap-max-lines + 1, and unlimited is 0, see
    // adapt_wrap_max_lines_argument()
    pub max_lines: usize,
    pub inline_hint_syntect_style: SyntectStyle,
}

#[derive(PartialEq)]
enum Stop {
    StackEmpty,
    LineLimit,
}

/// Wrap the given `line` if it is longer than `line_width`. Wrap to at most
/// [Config::WrapConfig::max_lines](WrapConfig::max_lines) lines,
/// then truncate again - but never truncate if it is `0`. Place
/// [left_symbol](WrapConfig::left_symbol) at the end of wrapped lines.
/// If wrapping results in only *one* extra line and if the width of the wrapped
/// line is less than [use_wrap_right_permille](WrapConfig::use_wrap_right_permille)
/// then right-align the second line and use the symbols
/// [right_symbol](WrapConfig::right_symbol) and
/// on the next line [right_prefix_symbol](WrapConfig::right_prefix_symbol).
/// The inserted characters will follow the
/// [inline_hint_syntect_style](WrapConfig::inline_hint_syntect_style).
pub fn wrap_line<'a, I, S>(
    config: &'a Config,
    line: I,
    line_width: usize,
    fill_style: &S,
    inline_hint_style: &Option<S>,
) -> Vec<LineSections<'a, S>>
where
    I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug,
    <I as IntoIterator>::IntoIter: DoubleEndedIterator,
    S: Copy + Default + std::fmt::Debug,
{
    let mut result = Vec::new();

    let wrap_config = &config.wrap_config;

    // The current line being assembled from the input to fit exactly into the given width.
    // A somewhat leaky abstraction as the fields are also accessed directly.
    struct CurrLine<'a, S: Default> {
        line_segments: LineSections<'a, S>,
        len: usize,
    }
    impl<'a, S: Default> CurrLine<'a, S> {
        fn reset() -> Self {
            CurrLine {
                line_segments: Vec::new(),
                len: 0,
            }
        }
        fn push_and_set_len(&mut self, text: (S, &'a str), len: usize) {
            self.line_segments.push(text);
            self.len = len;
        }
        fn has_text(&self) -> bool {
            self.len > 0
        }
        fn text_len(&self) -> usize {
            self.len
        }
    }

    let mut curr_line = CurrLine::reset();

    // Determine the background (diff) and color (syntax) of an inserted symbol.
    let symbol_style = match inline_hint_style {
        Some(style) => *style,
        None => *fill_style,
    };

    let mut stack = line.into_iter().rev().collect::<Vec<_>>();

    // If only the wrap symbol and no extra text fits, then wrapping is not possible.
    let max_lines = if line_width <= INLINE_SYMBOL_WIDTH_1 {
        1
    } else {
        wrap_config.max_lines
    };

    let line_limit_reached = |result: &Vec<_>| max_lines > 0 && result.len() + 1 >= max_lines;

    let stop = loop {
        if stack.is_empty() {
            break Stop::StackEmpty;
        } else if line_limit_reached(&result) {
            break Stop::LineLimit;
        }

        let (style, text, graphemes) = stack
            .pop()
            .map(|(style, text)| (style, text, text.grapheme_indices(true).collect::<Vec<_>>()))
            .unwrap();

        let new_len = curr_line.len + graphemes.len();

        let must_split = if new_len < line_width {
            curr_line.push_and_set_len((style, text), new_len);
            false
        } else if new_len == line_width {
            match stack.last() {
                // Perfect fit, no need to make space for a `wrap_symbol`.
                None => {
                    curr_line.push_and_set_len((style, text), new_len);
                    false
                }
                #[allow(clippy::identity_op)]
                // A single '\n' left on the stack can be pushed onto the current line.
                Some((next_style, nl)) if stack.len() == 1 && *nl == "\n" => {
                    curr_line.push_and_set_len((style, text), new_len);
                    // Do not count the '\n': + 0
                    curr_line.push_and_set_len((*next_style, *nl), new_len + 0);
                    stack.pop();
                    false
                }
                _ => true,
            }
        } else if new_len == line_width + 1 && stack.is_empty() {
            // If the one overhanging char is '\n' then keep it on the current line.
            if text.ends_with('\n') {
                // Do not count the included '\n': - 1
                curr_line.push_and_set_len((style, text), new_len - 1);
                false
            } else {
                true
            }
        } else {
            true
        };

        // Text must be split, one part (or just `wrap_symbol`) is added to the
        // current line, the other is pushed onto the stack.
        if must_split {
            let grapheme_split_pos = graphemes.len() - (new_len - line_width) - 1;

            // The length does not matter anymore and `curr_line` will be reset
            // at the end, so move the line segments out.
            let mut line_segments = curr_line.line_segments;

            let next_line = if grapheme_split_pos == 0 {
                text
            } else {
                let byte_split_pos = graphemes[grapheme_split_pos].0;
                let this_line = &text[..byte_split_pos];
                line_segments.push((style, this_line));
                &text[byte_split_pos..]
            };
            stack.push((style, next_line));

            line_segments.push((symbol_style, &wrap_config.left_symbol));
            result.push(line_segments);

            curr_line = CurrLine::reset();
        }
    };

    // Right-align wrapped line:
    // Done if wrapping adds exactly one line and this line is less than the given
    // permille wide. Also change the wrap symbol at the end of the previous (first) line.
    if result.len() == 1 && curr_line.has_text() {
        let current_permille = (curr_line.text_len() * 1000) / line_width;

        let pad_len = line_width.saturating_sub(curr_line.text_len());

        if wrap_config.use_wrap_right_permille > current_permille && pad_len > 0 {
            // The inserted spaces, which align a line to the right, point into this string.
            const SPACES: &str = "                                                                ";

            match result.last_mut() {
                Some(ref mut vec) if !vec.is_empty() => {
                    vec.last_mut().unwrap().1 = &wrap_config.right_symbol
                }
                _ => unreachable!("wrap result must not be empty"),
            }

            let mut right_aligned_line = Vec::new();

            for _ in 0..(pad_len / SPACES.len()) {
                right_aligned_line.push((*fill_style, SPACES));
            }

            match pad_len % SPACES.len() {
                0 => (),
                n => right_aligned_line.push((*fill_style, &SPACES[0..n])),
            }

            right_aligned_line.push((symbol_style, &wrap_config.right_prefix_symbol));

            right_aligned_line.extend(curr_line.line_segments.into_iter());

            curr_line.line_segments = right_aligned_line;

            // curr_line.len not updated, as only 0 / >0 for `has_text()` is required.
        }
    }

    if curr_line.has_text() {
        result.push(curr_line.line_segments);
    }

    if stop == Stop::LineLimit && result.len() != max_lines {
        result.push(Vec::new());
    }

    // Anything that is left will be added to the (last) line. If this is too long it will
    // be truncated later.
    if !stack.is_empty() {
        if result.is_empty() {
            result.push(Vec::new());
        }

        // unwrap: previous `if` ensures result can not be empty
        result.last_mut().unwrap().extend(stack.into_iter().rev());
    }

    result
}

fn wrap_if_too_long<'a, S>(
    config: &'a Config,
    wrapped: &mut Vec<LineSections<'a, S>>,
    input_vec: LineSections<'a, S>,
    must_wrap: bool,
    line_width: usize,
    fill_style: &S,
    inline_hint_style: &Option<S>,
) -> (usize, usize)
where
    S: Copy + Default + std::fmt::Debug,
{
    let size_prev = wrapped.len();

    if must_wrap {
        wrapped.append(&mut wrap_line(
            config,
            input_vec.into_iter(),
            line_width,
            fill_style,
            inline_hint_style,
        ));
    } else {
        wrapped.push(input_vec.to_vec());
    }

    (size_prev, wrapped.len())
}

/// Call [`wrap_line`] for the `syntax` and the `diff` lines if `wrapinfo` says
/// a specific line was longer than `line_width`. Return an adjusted `alignment`
/// with regard to the added wrapped lines.
#[allow(clippy::comparison_chain, clippy::type_complexity)]
pub fn wrap_minusplus_block<'c: 'a, 'a>(
    config: &'c Config,
    syntax: MinusPlus<Vec<LineSections<'a, SyntectStyle>>>,
    diff: MinusPlus<Vec<LineSections<'a, Style>>>,
    alignment: &[(Option<usize>, Option<usize>)],
    line_width: &SideBySideLineWidth,
    wrapinfo: &'a MinusPlus<Vec<bool>>,
) -> (
    Vec<(Option<usize>, Option<usize>)>,
    MinusPlus<Vec<State>>,
    MinusPlus<Vec<LineSections<'a, SyntectStyle>>>,
    MinusPlus<Vec<LineSections<'a, Style>>>,
) {
    let mut new_alignment = Vec::new();
    let mut new_states = MinusPlus::<Vec<State>>::default();
    let mut new_wrapped_syntax = MinusPlus::default();
    let mut new_wrapped_diff = MinusPlus::default();

    // Turn all these into pairs of iterators so they can be advanced according
    // to the alignment and independently.
    let mut syntax = MinusPlus::new(syntax.minus.into_iter(), syntax.plus.into_iter());
    let mut diff = MinusPlus::new(diff.minus.into_iter(), diff.plus.into_iter());
    let mut wrapinfo = MinusPlus::new(wrapinfo[Left].iter(), wrapinfo[Right].iter());

    let fill_style = MinusPlus::new(&config.minus_style, &config.plus_style);

    // Internal helper function to perform wrapping for both the syntax and the
    // diff highlighting (SyntectStyle and Style).
    #[allow(clippy::too_many_arguments)]
    pub fn wrap_syntax_and_diff<'a, ItSyn, ItDiff, ItWrap>(
        config: &'a Config,
        wrapped_syntax: &mut Vec<LineSections<'a, SyntectStyle>>,
        wrapped_diff: &mut Vec<LineSections<'a, Style>>,
        syntax_iter: &mut ItSyn,
        diff_iter: &mut ItDiff,
        wrapinfo_iter: &mut ItWrap,
        line_width: usize,
        fill_style: &Style,
        errhint: &'a str,
    ) -> (usize, usize)
    where
        ItSyn: Iterator<Item = LineSections<'a, SyntectStyle>>,
        ItDiff: Iterator<Item = LineSections<'a, Style>>,
        ItWrap: Iterator<Item = &'a bool>,
    {
        let must_wrap = *wrapinfo_iter
            .next()
            .unwrap_or_else(|| panic!("bad wrap info {}", errhint));

        let (start, extended_to) = wrap_if_too_long(
            config,
            wrapped_syntax,
            syntax_iter
                .next()
                .unwrap_or_else(|| panic!("bad syntax alignment {}", errhint)),
            must_wrap,
            line_width,
            &config.null_syntect_style,
            &Some(config.wrap_config.inline_hint_syntect_style),
        );

        // TODO: Why is the background color set to white when
        // ansi_term_style.background is None?
        let inline_hint_style = if config
            .inline_hint_style
            .ansi_term_style
            .background
            .is_some()
        {
            Some(config.inline_hint_style)
        } else {
            None
        };

        let (start2, extended_to2) = wrap_if_too_long(
            config,
            wrapped_diff,
            diff_iter
                .next()
                .unwrap_or_else(|| panic!("bad diff alignment {}", errhint)),
            must_wrap,
            line_width,
            fill_style,
            &inline_hint_style,
        );

        // The underlying text is the same for the style and diff, so
        // the length of the wrapping should be identical:
        assert_eq!(
            (start, extended_to),
            (start2, extended_to2),
            "syntax and diff wrapping differs {}",
            errhint
        );

        (start, extended_to)
    }

    // This macro avoids having the same code block 4x in the alignment processing
    macro_rules! wrap_and_assert {
        ($side:tt, $errhint:tt, $have:tt, $expected:tt) => {{
            assert_eq!(*$have, $expected, "bad alignment index {}", $errhint);
            $expected += 1;

            wrap_syntax_and_diff(
                &config,
                &mut new_wrapped_syntax[$side],
                &mut new_wrapped_diff[$side],
                &mut syntax[$side],
                &mut diff[$side],
                &mut wrapinfo[$side],
                line_width[$side],
                &fill_style[$side],
                $errhint,
            )
        }};
    }

    let mut m_expected = 0;
    let mut p_expected = 0;

    // Process blocks according to the alignment and build a new alignment.
    // If lines get added via wrapping these are assigned the state HunkMinusWrapped/HunkPlusWrapped.
    for (minus, plus) in alignment {
        let (minus_extended, plus_extended) = match (minus, plus) {
            (Some(m), None) => {
                let (minus_start, extended_to) = wrap_and_assert!(Left, "[*l*] (-)", m, m_expected);

                for i in minus_start..extended_to {
                    new_alignment.push((Some(i), None));
                }

                (extended_to - minus_start, 0)
            }
            (None, Some(p)) => {
                let (plus_start, extended_to) = wrap_and_assert!(Right, "(-) [*r*]", p, p_expected);

                for i in plus_start..extended_to {
                    new_alignment.push((None, Some(i)));
                }

                (0, extended_to - plus_start)
            }
            (Some(m), Some(p)) => {
                let (minus_start, m_extended_to) =
                    wrap_and_assert!(Left, "[*l*] (r)", m, m_expected);
                let (plus_start, p_extended_to) =
                    wrap_and_assert!(Right, "(l) [*r*]", p, p_expected);

                for (new_m, new_p) in (minus_start..m_extended_to).zip(plus_start..p_extended_to) {
                    new_alignment.push((Some(new_m), Some(new_p)));
                }

                // This Some(m):Some(p) alignment might have become uneven, so fill
                // up the shorter side with None.

                let minus_extended = m_extended_to - minus_start;
                let plus_extended = p_extended_to - plus_start;

                let plus_minus = (minus_extended as isize) - (plus_extended as isize);

                if plus_minus > 0 {
                    for m in (m_extended_to as isize - plus_minus) as usize..m_extended_to {
                        new_alignment.push((Some(m), None));
                    }
                } else if plus_minus < 0 {
                    for p in (p_extended_to as isize + plus_minus) as usize..p_extended_to {
                        new_alignment.push((None, Some(p)));
                    }
                }

                (minus_extended, plus_extended)
            }
            _ => unreachable!("None-None alignment"),
        };

        if minus_extended > 0 {
            new_states[Left].push(State::HunkMinus(DiffType::Unified, None));
            for _ in 1..minus_extended {
                new_states[Left].push(State::HunkMinusWrapped);
            }
        }
        if plus_extended > 0 {
            new_states[Right].push(State::HunkPlus(DiffType::Unified, None));
            for _ in 1..plus_extended {
                new_states[Right].push(State::HunkPlusWrapped);
            }
        }
    }

    (
        new_alignment,
        new_states,
        new_wrapped_syntax,
        new_wrapped_diff,
    )
}

#[allow(clippy::comparison_chain, clippy::type_complexity)]
pub fn wrap_zero_block<'c: 'a, 'a>(
    config: &'c Config,
    raw_line: &str,
    mut states: Vec<State>,
    syntax_style_sections: Vec<LineSections<'a, SyntectStyle>>,
    diff_style_sections: Vec<LineSections<'a, Style>>,
    line_numbers_data: &Option<&mut line_numbers::LineNumbersData>,
) -> (
    Vec<State>,
    Vec<LineSections<'a, SyntectStyle>>,
    Vec<LineSections<'a, Style>>,
) {
    // The width is the minimum of the left/right side. The panels should be equally sized,
    // but in rare cases the remaining panel width might differ due to the space the line
    // numbers take up.
    let line_width = if let Some(line_numbers_data) = line_numbers_data {
        let width = available_line_width(config, line_numbers_data);
        std::cmp::min(width[Left], width[Right])
    } else {
        std::cmp::min(
            config.side_by_side_data[Left].width,
            config.side_by_side_data[Right].width,
        )
    };

    // Called with a single line, so no need to use the 1-sized bool vector.
    // If that changes the wrapping logic should be updated as well.
    debug_assert_eq!(diff_style_sections.len(), 1);

    let should_wrap = line_is_too_long(raw_line, line_width);

    if should_wrap {
        let syntax_style = wrap_line(
            config,
            syntax_style_sections.into_iter().flatten(),
            line_width,
            &SyntectStyle::default(),
            &Some(config.wrap_config.inline_hint_syntect_style),
        );

        // TODO: Why is the background color set to white when
        // ansi_term_style.background is None?
        let inline_hint_style = if config
            .inline_hint_style
            .ansi_term_style
            .background
            .is_some()
        {
            Some(config.inline_hint_style)
        } else {
            None
        };
        let diff_style = wrap_line(
            config,
            diff_style_sections.into_iter().flatten(),
            line_width,
            // To actually highlight inline hint characters:
            &Style {
                is_syntax_highlighted: true,
                ..config.null_style
            },
            &inline_hint_style,
        );

        states.resize_with(syntax_style.len(), || State::HunkZeroWrapped);

        (states, syntax_style, diff_style)
    } else {
        (states, syntax_style_sections, diff_style_sections)
    }
}

#[cfg(test)]
mod tests {
    use lazy_static::lazy_static;
    use syntect::highlighting::Style as SyntectStyle;

    use super::wrap_line;
    use super::WrapConfig;
    use crate::ansi::strip_ansi_codes;
    use crate::config::Config;
    use crate::paint::LineSections;
    use crate::style::Style;
    use crate::tests::integration_test_utils::{make_config_from_args, run_delta};

    lazy_static! {
        static ref S1: Style = Style {
            is_syntax_highlighted: true,
            ..Default::default()
        };
    }
    lazy_static! {
        static ref S2: Style = Style {
            is_emph: true,
            ..Default::default()
        };
    }
    lazy_static! {
        static ref SY: SyntectStyle = SyntectStyle::default();
    }
    lazy_static! {
        static ref SD: Style = Style::default();
    }

    const W: &str = &"+"; // wrap
    const WR: &str = &"<"; // wrap-right
    const RA: &str = &">"; // right-align

    lazy_static! {
        static ref WRAP_DEFAULT_ARGS: Vec<&'static str> = vec![
            "--wrap-left-symbol",
            W,
            "--wrap-right-symbol",
            WR,
            "--wrap-right-prefix-symbol",
            RA,
            "--wrap-max-lines",
            "4",
            "--wrap-right-percent",
            "37.0%",
        ];
    }

    lazy_static! {
        static ref TEST_WRAP_CFG: WrapConfig =
            make_config_from_args(&WRAP_DEFAULT_ARGS).wrap_config;
    }

    fn default_wrap_cfg_plus<'a>(args: &[&'a str]) -> Vec<&'a str> {
        let mut result = WRAP_DEFAULT_ARGS.clone();
        result.extend_from_slice(args);
        result
    }

    fn mk_wrap_cfg(wrap_cfg: &WrapConfig) -> Config {
        let mut cfg: Config = Config::from(make_config_from_args(&[]));
        cfg.wrap_config = wrap_cfg.clone();
        cfg
    }

    fn wrap_test<'a, I, S>(cfg: &'a Config, line: I, line_width: usize) -> Vec<LineSections<'a, S>>
    where
        I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug,
        <I as IntoIterator>::IntoIter: DoubleEndedIterator,
        S: Copy + Default + std::fmt::Debug,
    {
        wrap_line(&cfg, line, line_width, &S::default(), &None)
    }

    #[test]
    fn test_wrap_line_single() {
        let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);

        {
            let line = vec![(*SY, "0")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*SY, "0")]]);
        }
        {
            let line = vec![(*S1, "012"), (*S2, "34")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "34")]]);
        }
        {
            let line = vec![(*S1, "012"), (*S2, "345")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345")]]);
        }
        {
            // Empty input usually does not happen
            let line = vec![(*S1, "")];
            let lines = wrap_test(&cfg, line, 6);
            assert!(lines.is_empty());
        }
        {
            // Partially empty should not happen either
            let line = vec![(*S1, ""), (*S2, "0")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*S1, ""), (*S2, "0")]]);
        }
        {
            let line = vec![(*S1, "0"), (*S2, "")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*S1, "0"), (*S2, "")]]);
        }
        {
            let line = vec![
                (*S1, "0"),
                (*S2, ""),
                (*S1, ""),
                (*S2, ""),
                (*S1, ""),
                (*S2, ""),
                (*S1, ""),
                (*S2, ""),
                (*S1, ""),
                (*S2, ""),
            ];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(
                lines,
                vec![vec![
                    (*S1, "0"),
                    (*S2, ""),
                    (*S1, ""),
                    (*S2, ""),
                    (*S1, ""),
                    (*S2, ""),
                    (*S1, ""),
                    (*S2, ""),
                    (*S1, ""),
                    (*S2, "")
                ]]
            );
        }
    }

    #[test]
    fn test_wrap_line_align_right_1() {
        let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);

        let line = vec![(*S1, "0123456789ab")];
        let lines = wrap_test(&cfg, line, 11);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].last().unwrap().1, WR);
        assert_eq!(lines[1], [(*SD, "         "), (*SD, ">"), (*S1, "ab")]);
    }

    #[test]
    fn test_wrap_line_align_right_2() {
        let line = vec![(*S1, "012"), (*S2, "3456")];

        {
            // Right align lines on the second line
            let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);

            let lines = wrap_test(&cfg, line.clone(), 6);
            assert_eq!(
                lines,
                vec![
                    vec![(*S1, "012"), (*S2, "34"), (*SD, WR)],
                    vec![(*SD, "    "), (*SD, RA), (*S2, "56")]
                ]
            );
        }

        {
            // Set right align percentage lower, normal wrapping
            let mut no_align_right = TEST_WRAP_CFG.clone();
            no_align_right.use_wrap_right_permille = 1; // 0.1%
            let cfg_no_align_right = mk_wrap_cfg(&no_align_right);

            let lines = wrap_test(&cfg_no_align_right, line, 6);
            assert_eq!(
                lines,
                vec![vec![(*S1, "012"), (*S2, "34"), (*SD, W)], vec![(*S2, "56")]]
            );
        }
    }

    #[test]
    fn test_wrap_line_newlines<'a>() {
        fn mk_input(len: usize) -> LineSections<'static, Style> {
            const IN: &str = "0123456789abcdefZ";
            let v = &[*S1, *S2];
            let s1s2 = v.iter().cycle();
            let text: Vec<_> = IN.matches(|_| true).take(len + 1).collect();
            s1s2.zip(text.iter())
                .map(|(style, text)| (style.clone(), *text))
                .collect()
        }
        fn mk_input_nl(len: usize) -> LineSections<'static, Style> {
            const NL: &str = "\n";
            let mut line = mk_input(len);
            line.push((*S2, NL));
            line
        }
        fn mk_expected<'a>(
            vec: &LineSections<'a, Style>,
            from: usize,
            to: usize,
            append: Option<(Style, &'a str)>,
        ) -> LineSections<'a, Style> {
            let mut result: Vec<_> = vec[from..to].iter().cloned().collect();
            if let Some(val) = append {
                result.push(val);
            }
            result
        }

        let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);

        {
            let line = vec![(*S1, "012"), (*S2, "345\n")];
            let lines = wrap_test(&cfg, line, 6);
            assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345\n")]]);
        }

        {
            for i in 0..=5 {
                let line = mk_input(i);
                let lines = wrap_test(&cfg, line, 6);
                assert_eq!(lines, vec![mk_input(i)]);

                let line = mk_input_nl(i);
                let lines = wrap_test(&cfg, line, 6);
                assert_eq!(lines, vec![mk_input_nl(i)]);
            }
        }

        {
            let line = mk_input_nl(9);
            let lines = wrap_test(&cfg, line, 3);
            let expected = mk_input_nl(9);
            let line1 = mk_expected(&expected, 0, 2, Some((*SD, &W)));
            let line2 = mk_expected(&expected, 2, 4, Some((*SD, &W)));
            let line3 = mk_expected(&expected, 4, 6, Some((*SD, &W)));
            let line4 = mk_expected(&expected, 6, 8, Some((*SD, &W)));
            let line5 = mk_expected(&expected, 8, 11, None);
            assert_eq!(lines, vec![line1, line2, line3, line4, line5]);
        }

        {
            let line = mk_input_nl(10);
            let lines = wrap_test(&cfg, line, 3);
            let expected = mk_input_nl(10);
            let line1 = mk_expected(&expected, 0, 2, Some((*SD, &W)));
            let line2 = mk_expected(&expected, 2, 4, Some((*SD, &W)));
            let line3 = mk_expected(&expected, 4, 6, Some((*SD, &W)));
            let line4 = mk_expected(&expected, 6, 8, Some((*SD, &W)));
            let line5 = mk_expected(&expected, 8, 11, Some((*S2, "\n")));
            assert_eq!(lines, vec![line1, line2, line3, line4, line5]);
        }

        {
            let line = vec![(*S1, "abc"), (*S2, "01230123012301230123"), (*S1, "ZZZZZ")];

            let wcfg1 = mk_wrap_cfg(&WrapConfig {
                max_lines: 1,
                ..TEST_WRAP_CFG.clone()
            });
            let wcfg2 = mk_wrap_cfg(&WrapConfig {
                max_lines: 2,
                ..TEST_WRAP_CFG.clone()
            });
            let wcfg3 = mk_wrap_cfg(&WrapConfig {
                max_lines: 3,
                ..TEST_WRAP_CFG.clone()
            });

            let lines = wrap_line(&wcfg1, line.clone(), 4, &Style::default(), &None);
            assert_eq!(lines.len(), 1);
            assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
            let lines = wrap_line(&wcfg2, line.clone(), 4, &Style::default(), &None);
            assert_eq!(lines.len(), 2);
            assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
            let lines = wrap_line(&wcfg3, line.clone(), 4, &Style::default(), &None);
            assert_eq!(lines.len(), 3);
            assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
        }
    }

    #[test]
    fn test_wrap_line_unicode() {
        let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);

        // from UnicodeSegmentation documentation and the linked
        // Unicode Standard Annex #29
        let line = vec![(*S1, "abc"), (*S2, "mnö̲"), (*S1, "xyz")];
        let lines = wrap_test(&cfg, line, 4);
        assert_eq!(
            lines,
            vec![
                vec![(*S1, "abc"), (*SD, &W)],
                vec![(*S2, "mnö̲"), (*SD, &W)],
                vec![(*S1, "xyz")]
            ]
        );

        // Not working: Tailored grapheme clusters: क्षि  = क् + षि
        let line = vec![(*S1, "abc"), (*S2, "deநி"), (*S1, "ghij")];
        let lines = wrap_test(&cfg, line, 4);
        assert_eq!(
            lines,
            vec![
                vec![(*S1, "abc"), (*SD, &W)],
                vec![(*S2, "deநி"), (*SD, &W)],
                vec![(*S1, "ghij")]
            ]
        );
    }

    const HUNK_ZERO_DIFF: &str = "\
diff --git i/a.py w/a.py
index 223ca50..e69de29 100644
--- i/a.py
+++ w/a.py
@@ -4,3 +15,3 @@
 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
-a = 1
+a = 2
";

    const HUNK_ZERO_LARGE_LINENUMBERS_DIFF: &str = "\
diff --git i/a.py w/a.py
index 223ca50..e69de29 100644
--- i/a.py
+++ w/a.py
@@ -10,3 +101999,3 @@
 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
-a = 1
+a = 2
";

    const HUNK_MP_DIFF: &str = "\
diff --git i/a.py w/a.py
index 223ca50..e69de29 100644
--- i/a.py
+++ w/a.py
@@ -4,3 +15,3 @@
 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
-a = 0123456789 0123456789 0123456789 0123456789 0123456789
+b = 0123456789 0123456789 0123456789 0123456789 0123456789
";

    const HUNK_ALIGN_DIFF_HEADER: &str = "--- a\n+++ b\n@@ -1,1 +1,1 @@\n";
    const HUNK_ALIGN_DIFF_SHORT: &str = ".........1.........2....\n";
    const HUNK_ALIGN_DIFF_LONG: &str =
        ".........1.........2.........3.........4.........5.........6\n";

    #[test]
    fn test_wrap_with_unequal_hunk_zero_width() {
        let mut config = make_config_from_args(&default_wrap_cfg_plus(&[
            "--side-by-side",
            "--line-numbers-left-format",
            "│L│",
            "--line-numbers-right-format",
            "│RRRR│",
            "--width",
            "40",
            "--line-fill-method",
            "spaces",
        ]));
        config.truncation_symbol = ">".into();

        let output = run_delta(HUNK_ZERO_DIFF, &config);
        let output = strip_ansi_codes(&output);
        let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
        let expected = vec![
            "│L│abcdefghijklm+   │RRRR│abcdefghijklm+",
            "│L│nopqrstuvwxzy+   │RRRR│nopqrstuvwxzy+",
            "│L│ 0123456789 0+   │RRRR│ 0123456789 0+",
            "│L│123456789 012+   │RRRR│123456789 012+",
            "│L│3456789 01234567>│RRRR│3456789 01234>",
            "│L│a = 1            │RRRR│a = 2         ",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn test_wrap_with_large_hunk_zero_line_numbers() {
        let mut config = make_config_from_args(&default_wrap_cfg_plus(&[
            "--side-by-side",
            "--line-numbers-left-format",
            "│LLL│",
            "--line-numbers-right-format",
            "│WW {nm} +- {np:2} WW│",
            "--width",
            "60",
            "--line-fill-method",
            "ansi",
        ]));
        config.truncation_symbol = ">".into();

        let output = run_delta(HUNK_ZERO_LARGE_LINENUMBERS_DIFF, &config);
        let output = strip_ansi_codes(&output);
        let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
        let expected = vec![
            "│LLL│abcde+                   │WW   10   +- 101999 WW│abcde+",
            "│LLL│fghij+                   │WW        +-        WW│fghij+",
            "│LLL│klmno+                   │WW        +-        WW│klmno+",
            "│LLL│pqrst+                   │WW        +-        WW│pqrst+",
            "│LLL│uvwxzy 0123456789 012345>│WW        +-        WW│uvwxz>",
            "│LLL│a = 1                    │WW        +- 102000 WW│a = 2",
        ];
        assert_eq!(lines, expected);
    }

    #[test]
    fn test_wrap_with_keep_markers() {
        use crate::features::side_by_side::ansifill::ODD_PAD_CHAR;
        let mut config = make_config_from_args(&default_wrap_cfg_plus(&[
            "--side-by-side",
            "--keep-plus-minus-markers",
            "--width",
            "45",
        ]));
        config.truncation_symbol = ">".into();

        let output = run_delta(HUNK_MP_DIFF, &config);
        let output = strip_ansi_codes(&output);
        let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
        let expected = vec![
            "│ 4  │ abcdefghijklmn+ │ 15 │ abcdefghijklmn+",
            "│    │ opqrstuvwxzy 0+ │    │ opqrstuvwxzy 0+",
            "│    │ 123456789 0123+ │    │ 123456789 0123+",
            "│    │ 456789 0123456+ │    │ 456789 0123456+",
            "│    │ 789 0123456789> │    │ 789 0123456789>",
            "│ 5  │-a = 0123456789+ │ 16 │+b = 0123456789+",
            "│    │  0123456789 01+ │    │  0123456789 01+",
            "│    │ 23456789 01234+ │    │ 23456789 01234+",
            "│    │ 56789 01234567+ │    │ 56789 01234567+",
            "│    │ 89              │    │ 89",
            // this is place where ^ ODD_PAD_CHAR is inserted due to the odd 45 width
        ];
        assert_eq!(lines, expected);

        for line in lines {
            assert_eq!(line.chars().nth(22), Some(ODD_PAD_CHAR));
        }
    }

    #[test]
    fn test_alignment_2_lines_vs_3_lines() {
        let config =
            make_config_from_args(&default_wrap_cfg_plus(&["--side-by-side", "--width", "55"]));
        {
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_SHORT, HUNK_ALIGN_DIFF_LONG
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2< │ 1  │.........1.........2+",
                "│    │                >.... │    │.........3.........4+",
                "│    │                      │    │.........5.........6",
                // place where ODD_PAD_CHAR ^ is inserted due to the odd 55 width
            ];
            assert_eq!(lines, expected);
        }

        {
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_LONG, HUNK_ALIGN_DIFF_SHORT
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2+ │ 1  │.........1.........2<",
                "│    │.........3.........4+ │    │                >....",
                "│    │.........5.........6  │    │",
            ];
            assert_eq!(lines, expected);
        }
    }

    #[test]
    fn test_alignment_1_line_vs_3_lines() {
        let config = make_config_from_args(&default_wrap_cfg_plus(&[
            "--side-by-side",
            "--width",
            "61",
            "--line-fill-method",
            "spaces",
        ]));

        {
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_SHORT, HUNK_ALIGN_DIFF_LONG
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2....│ 1  │.........1.........2...+",
                "│    │                        │    │......3.........4......+",
                "│    │                        │    │...5.........6          ",
            ];
            assert_eq!(lines, expected);
        }

        {
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_LONG, HUNK_ALIGN_DIFF_SHORT
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2...+│ 1  │.........1.........2....",
                "│    │......3.........4......+│    │",
                "│    │...5.........6          │    │",
            ];
            assert_eq!(lines, expected);
        }
    }

    #[test]
    fn test_wrap_max_lines_2() {
        // TODO overriding is not possible, need to change config directly
        let mut config = make_config_from_args(&default_wrap_cfg_plus(&[
            // "--wrap-max-lines",
            // "2",
            "--side-by-side",
            "--width",
            "72",
            "--line-fill-method",
            "spaces",
        ]));
        config.truncation_symbol = ">".into();

        {
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_SHORT, HUNK_ALIGN_DIFF_LONG
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2....      │ 1  │.........1.........2.........+",
                "│    │                              │    │3.........4.........5........+",
                "│    │                              │    │.6                            ",
            ];
            assert_eq!(lines, expected);
        }

        {
            config.wrap_config.max_lines = 2;
            let output = run_delta(
                &format!(
                    "{}-{}+{}",
                    HUNK_ALIGN_DIFF_HEADER, HUNK_ALIGN_DIFF_SHORT, HUNK_ALIGN_DIFF_LONG
                ),
                &config,
            );
            let output = strip_ansi_codes(&output);
            let lines: Vec<_> = output.lines().skip(crate::config::HEADER_LEN).collect();
            let expected = vec![
                "│ 1  │.........1.........2....      │ 1  │.........1.........2.........+",
                "│    │                              │    │3.........4.........5........>",
            ];
            assert_eq!(lines, expected);
        }
    }
}