Debian Codegraph @

src/wrapping.rs

raw symbols SCIP
1 use syntect::highlighting::Style as SyntectStyle;
2 use unicode_segmentation::UnicodeSegmentation;
3 use unicode_width::UnicodeWidthStr;
4
5 use crate::cli;
6 use crate::config::INLINE_SYMBOL_WIDTH_1;
7 use crate::fatal;
8
9 use crate::config::Config;
10 use crate::delta::DiffType;
11 use crate::delta::State;
12 use crate::features::line_numbers::{self, SideBySideLineWidth};
13 use crate::features::side_by_side::{available_line_width, line_is_too_long, Left, Right};
14 use crate::minusplus::*;
15 use crate::paint::LineSections;
16 use crate::style::Style;
17 use crate::utils::syntect::FromDeltaStyle;
18
19 /// See [`wrap_line`] for documentation.
20 #[derive(Clone, Debug)]
21 pub struct WrapConfig {
22 pub left_symbol: String,
23 pub right_symbol: String,
24 pub right_prefix_symbol: String,
25 // In fractions of 1000 so that a >100 wide panel can
26 // still be configured down to a single character.
27 pub use_wrap_right_permille: usize,
28 // This value is --wrap-max-lines + 1, and unlimited is 0, see
29 // adapt_wrap_max_lines_argument()
30 pub max_lines: usize,
31 pub inline_hint_syntect_style: SyntectStyle,
32 }
33
34 impl WrapConfig {
35 pub fn from_opt(opt: &cli::Opt, inline_hint_style: Style) -> Self {
36 Self {
37 left_symbol: ensure_display_width_1("wrap-left-symbol", opt.wrap_left_symbol.clone()),
38 right_symbol: ensure_display_width_1(
39 "wrap-right-symbol",
40 opt.wrap_right_symbol.clone(),
41 ),
42 right_prefix_symbol: ensure_display_width_1(
43 "wrap-right-prefix-symbol",
44 opt.wrap_right_prefix_symbol.clone(),
45 ),
46 use_wrap_right_permille: {
47 let arg = &opt.wrap_right_percent;
48 let percent = remove_percent_suffix(arg)
49 .parse::<f64>()
50 .unwrap_or_else(|err| {
51 fatal(format!(
52 "Could not parse wrap-right-percent argument {}: {}.",
53 &arg, err
54 ))
55 });
56 if percent.is_finite() && percent > 0.0 && percent < 100.0 {
57 (percent * 10.0).round() as usize
58 } else {
59 fatal("Invalid value for wrap-right-percent, not between 0 and 100.")
60 }
61 },
62 max_lines: adapt_wrap_max_lines_argument(opt.wrap_max_lines.clone()),
63 inline_hint_syntect_style: SyntectStyle::from_delta_style(inline_hint_style),
64 }
65 }
66
67 // Compute value of `max_line_length` field in the main `Config` struct.
68 pub fn config_max_line_length(
69 &self,
70 max_line_length: usize,
71 available_terminal_width: usize,
72 ) -> usize {
73 match self.max_lines {
74 1 => max_line_length,
75 // Ensure there is enough text to wrap, either don't truncate the input at all (0)
76 // or ensure there is enough for the requested number of lines.
77 // The input can contain ANSI sequences, so round up a bit. This is enough for
78 // normal `git diff`, but might not be with ANSI heavy input.
79 0 => 0,
80 wrap_max_lines => {
81 let single_pane_width = available_terminal_width / 2;
82 let add_25_percent_or_term_width =
83 |x| x + std::cmp::max((x * 250) / 1000, single_pane_width);
84 std::cmp::max(
85 max_line_length,
86 add_25_percent_or_term_width(single_pane_width * wrap_max_lines),
87 )
88 }
89 }
90 }
91 }
92
93 fn remove_percent_suffix(arg: &str) -> &str {
94 match &arg.strip_suffix('%') {
95 Some(s) => s,
96 None => arg,
97 }
98 }
99
100 fn ensure_display_width_1(what: &str, arg: String) -> String {
101 match arg.grapheme_indices(true).count() {
102 INLINE_SYMBOL_WIDTH_1 => arg,
103 width => fatal(format!(
104 "Invalid value for {what}, display width of \"{arg}\" must be {INLINE_SYMBOL_WIDTH_1} but is {width}",
105 )),
106 }
107 }
108
109 fn adapt_wrap_max_lines_argument(arg: String) -> usize {
110 if arg == "∞" || arg == "unlimited" || arg.starts_with("inf") {
111 0
112 } else {
113 arg.parse::<usize>()
114 .unwrap_or_else(|err| fatal(format!("Invalid wrap-max-lines argument: {err}")))
115 + 1
116 }
117 }
118
119 #[derive(PartialEq)]
120 enum Stop {
121 StackEmpty,
122 LineLimit,
123 }
124
125 /// Wrap the given `line` if it is longer than `line_width`. Wrap to at most
126 /// [Config::WrapConfig::max_lines](WrapConfig::max_lines) lines,
127 /// then truncate again - but never truncate if it is `0`. Place
128 /// [left_symbol](WrapConfig::left_symbol) at the end of wrapped lines.
129 /// If wrapping results in only *one* extra line and if the width of the wrapped
130 /// line is less than [use_wrap_right_permille](WrapConfig::use_wrap_right_permille)
131 /// then right-align the second line and use the symbols
132 /// [right_symbol](WrapConfig::right_symbol) and
133 /// on the next line [right_prefix_symbol](WrapConfig::right_prefix_symbol).
134 /// The inserted characters will follow the
135 /// [inline_hint_syntect_style](WrapConfig::inline_hint_syntect_style).
136 pub fn wrap_line<'a, I, S>(
137 config: &'a Config,
138 line: I,
139 line_width: usize,
140 fill_style: &S,
141 inline_hint_style: &Option<S>,
142 ) -> Vec<LineSections<'a, S>>
143 where
144 I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug,
145 <I as IntoIterator>::IntoIter: DoubleEndedIterator,
146 S: Copy + Default + std::fmt::Debug,
147 {
148 let mut result = Vec::new();
149
150 let wrap_config = &config.wrap_config;
151
152 // The current line being assembled from the input to fit exactly into the given width.
153 // A somewhat leaky abstraction as the fields are also accessed directly.
154 struct CurrLine<'a, S: Default> {
155 line_segments: LineSections<'a, S>,
156 len: usize,
157 }
158 impl<'a, S: Default> CurrLine<'a, S> {
159 fn reset() -> Self {
160 CurrLine {
161 line_segments: Vec::new(),
162 len: 0,
163 }
164 }
165 fn push_and_set_len(&mut self, text: (S, &'a str), len: usize) {
166 self.line_segments.push(text);
167 self.len = len;
168 }
169 fn has_text(&self) -> bool {
170 self.len > 0
171 }
172 fn text_len(&self) -> usize {
173 self.len
174 }
175 }
176
177 let mut curr_line = CurrLine::reset();
178
179 // Determine the background (diff) and color (syntax) of an inserted symbol.
180 let symbol_style = match inline_hint_style {
181 Some(style) => *style,
182 None => *fill_style,
183 };
184
185 let mut stack = line.into_iter().rev().collect::<Vec<_>>();
186
187 // If only the wrap symbol and no extra text fits, then wrapping is not possible.
188 let max_lines = if line_width <= INLINE_SYMBOL_WIDTH_1 {
189 1
190 } else {
191 wrap_config.max_lines
192 };
193
194 let line_limit_reached = |result: &Vec<_>| max_lines > 0 && result.len() + 1 >= max_lines;
195
196 let stop = loop {
197 if stack.is_empty() {
198 break Stop::StackEmpty;
199 } else if line_limit_reached(&result) {
200 break Stop::LineLimit;
201 }
202
203 let (style, text, graphemes) = stack
204 .pop()
205 .map(|(style, text)| {
206 (
207 style,
208 text,
209 text.graphemes(true)
210 .map(|item| (item.len(), item.width()))
211 .collect::<Vec<_>>(),
212 )
213 })
214 .unwrap();
215
216 let graphemes_width: usize = graphemes.iter().map(|(_, w)| w).sum();
217 let new_len = curr_line.len + graphemes_width;
218
219 #[allow(clippy::comparison_chain)]
220 let must_split = if new_len < line_width {
221 curr_line.push_and_set_len((style, text), new_len);
222 false
223 } else if new_len == line_width {
224 match stack.last() {
225 // Perfect fit, no need to make space for a `wrap_symbol`.
226 None => {
227 curr_line.push_and_set_len((style, text), new_len);
228 false
229 }
230 #[allow(clippy::identity_op)]
231 // A single '\n' left on the stack can be pushed onto the current line.
232 Some((next_style, nl)) if stack.len() == 1 && *nl == "\n" => {
233 curr_line.push_and_set_len((style, text), new_len);
234 // Do not count the '\n': + 0
235 curr_line.push_and_set_len((*next_style, *nl), new_len + 0);
236 stack.pop();
237 false
238 }
239 _ => true,
240 }
241 } else {
242 true
243 };
244
245 // Text must be split, one part (or just `wrap_symbol`) is added to the
246 // current line, the other is pushed onto the stack.
247 if must_split {
248 let mut width_left = graphemes_width
249 .saturating_sub(new_len - line_width)
250 .saturating_sub(wrap_config.left_symbol.width());
251
252 // The length does not matter anymore and `curr_line` will be reset
253 // at the end, so move the line segments out.
254 let mut line_segments = curr_line.line_segments;
255
256 let next_line = if width_left == 0 {
257 text
258 } else {
259 let mut byte_split_pos = 0;
260 // After loop byte_split_pos may still equal to 0. If width_left
261 // is less than the width of first character, We can't display it.
262 for &(item_len, item_width) in graphemes.iter() {
263 if width_left >= item_width {
264 byte_split_pos += item_len;
265 width_left -= item_width;
266 } else {
267 break;
268 }
269 }
270
271 let this_line = &text[..byte_split_pos];
272 line_segments.push((style, this_line));
273 &text[byte_split_pos..]
274 };
275 stack.push((style, next_line));
276
277 line_segments.push((symbol_style, &wrap_config.left_symbol));
278 result.push(line_segments);
279
280 curr_line = CurrLine::reset();
281 }
282 };
283
284 // Right-align wrapped line:
285 // Done if wrapping adds exactly one line and this line is less than the given
286 // permille wide. Also change the wrap symbol at the end of the previous (first) line.
287 if result.len() == 1 && curr_line.has_text() {
288 let current_permille = (curr_line.text_len() * 1000) / line_width;
289
290 // pad line will add a wrap_config.right_prefix_symbol
291 let pad_len = line_width
292 .saturating_sub(curr_line.text_len() + wrap_config.right_prefix_symbol.width());
293
294 if wrap_config.use_wrap_right_permille > current_permille && pad_len > 0 {
295 // The inserted spaces, which align a line to the right, point into this string.
296 const SPACES: &str = " ";
297
298 match result.last_mut() {
299 Some(ref mut vec) if !vec.is_empty() => {
300 vec.last_mut().unwrap().1 = &wrap_config.right_symbol
301 }
302 _ => unreachable!("wrap result must not be empty"),
303 }
304
305 let mut right_aligned_line = Vec::new();
306
307 for _ in 0..(pad_len / SPACES.len()) {
308 right_aligned_line.push((*fill_style, SPACES));
309 }
310
311 match pad_len % SPACES.len() {
312 0 => (),
313 n => right_aligned_line.push((*fill_style, &SPACES[0..n])),
314 }
315
316 right_aligned_line.push((symbol_style, &wrap_config.right_prefix_symbol));
317
318 right_aligned_line.extend(curr_line.line_segments);
319
320 curr_line.line_segments = right_aligned_line;
321
322 // curr_line.len not updated, as only 0 / >0 for `has_text()` is required.
323 }
324 }
325
326 if curr_line.has_text() {
327 result.push(curr_line.line_segments);
328 }
329
330 if stop == Stop::LineLimit && result.len() != max_lines {
331 result.push(Vec::new());
332 }
333
334 // Anything that is left will be added to the (last) line. If this is too long it will
335 // be truncated later.
336 if !stack.is_empty() {
337 if result.is_empty() {
338 result.push(Vec::new());
339 }
340
341 // unwrap: previous `if` ensures result can not be empty
342 result.last_mut().unwrap().extend(stack.into_iter().rev());
343 }
344
345 result
346 }
347
348 fn wrap_if_too_long<'a, S>(
349 config: &'a Config,
350 wrapped: &mut Vec<LineSections<'a, S>>,
351 input_vec: LineSections<'a, S>,
352 must_wrap: bool,
353 line_width: usize,
354 fill_style: &S,
355 inline_hint_style: &Option<S>,
356 ) -> (usize, usize)
357 where
358 S: Copy + Default + std::fmt::Debug,
359 {
360 let size_prev = wrapped.len();
361
362 if must_wrap {
363 wrapped.append(&mut wrap_line(
364 config,
365 input_vec,
366 line_width,
367 fill_style,
368 inline_hint_style,
369 ));
370 } else {
371 wrapped.push(input_vec.to_vec());
372 }
373
374 (size_prev, wrapped.len())
375 }
376
377 /// Call [`wrap_line`] for the `syntax` and the `diff` lines if `wrapinfo` says
378 /// a specific line was longer than `line_width`. Return an adjusted `alignment`
379 /// with regard to the added wrapped lines.
380 #[allow(clippy::comparison_chain, clippy::type_complexity)]
381 pub fn wrap_minusplus_block<'c: 'a, 'a>(
382 config: &'c Config,
383 syntax: MinusPlus<Vec<LineSections<'a, SyntectStyle>>>,
384 diff: MinusPlus<Vec<LineSections<'a, Style>>>,
385 alignment: &[(Option<usize>, Option<usize>)],
386 line_width: &SideBySideLineWidth,
387 wrapinfo: &'a MinusPlus<Vec<bool>>,
388 ) -> (
389 Vec<(Option<usize>, Option<usize>)>,
390 MinusPlus<Vec<State>>,
391 MinusPlus<Vec<LineSections<'a, SyntectStyle>>>,
392 MinusPlus<Vec<LineSections<'a, Style>>>,
393 ) {
394 let mut new_alignment = Vec::new();
395 let mut new_states = MinusPlus::<Vec<State>>::default();
396 let mut new_wrapped_syntax = MinusPlus::default();
397 let mut new_wrapped_diff = MinusPlus::default();
398
399 // Turn all these into pairs of iterators so they can be advanced according
400 // to the alignment and independently.
401 let mut syntax = MinusPlus::new(syntax.minus.into_iter(), syntax.plus.into_iter());
402 let mut diff = MinusPlus::new(diff.minus.into_iter(), diff.plus.into_iter());
403 let mut wrapinfo = MinusPlus::new(wrapinfo[Left].iter(), wrapinfo[Right].iter());
404
405 let fill_style = MinusPlus::new(&config.minus_style, &config.plus_style);
406
407 // Internal helper function to perform wrapping for both the syntax and the
408 // diff highlighting (SyntectStyle and Style).
409 #[allow(clippy::too_many_arguments)]
410 pub fn wrap_syntax_and_diff<'a, ItSyn, ItDiff, ItWrap>(
411 config: &'a Config,
412 wrapped_syntax: &mut Vec<LineSections<'a, SyntectStyle>>,
413 wrapped_diff: &mut Vec<LineSections<'a, Style>>,
414 syntax_iter: &mut ItSyn,
415 diff_iter: &mut ItDiff,
416 wrapinfo_iter: &mut ItWrap,
417 line_width: usize,
418 fill_style: &Style,
419 errhint: &'a str,
420 ) -> (usize, usize)
421 where
422 ItSyn: Iterator<Item = LineSections<'a, SyntectStyle>>,
423 ItDiff: Iterator<Item = LineSections<'a, Style>>,
424 ItWrap: Iterator<Item = &'a bool>,
425 {
426 let must_wrap = *wrapinfo_iter
427 .next()
428 .unwrap_or_else(|| panic!("bad wrap info {}", errhint));
429
430 let (start, extended_to) = wrap_if_too_long(
431 config,
432 wrapped_syntax,
433 syntax_iter
434 .next()
435 .unwrap_or_else(|| panic!("bad syntax alignment {}", errhint)),
436 must_wrap,
437 line_width,
438 &config.null_syntect_style,
439 &Some(config.wrap_config.inline_hint_syntect_style),
440 );
441
442 // TODO: Why is the background color set to white when
443 // ansi_term_style.background is None?
444 let inline_hint_style = if config
445 .inline_hint_style
446 .ansi_term_style
447 .background
448 .is_some()
449 {
450 Some(config.inline_hint_style)
451 } else {
452 None
453 };
454
455 let (start2, extended_to2) = wrap_if_too_long(
456 config,
457 wrapped_diff,
458 diff_iter
459 .next()
460 .unwrap_or_else(|| panic!("bad diff alignment {}", errhint)),
461 must_wrap,
462 line_width,
463 fill_style,
464 &inline_hint_style,
465 );
466
467 // The underlying text is the same for the style and diff, so
468 // the length of the wrapping should be identical:
469 assert_eq!(
470 (start, extended_to),
471 (start2, extended_to2),
472 "syntax and diff wrapping differs {errhint}",
473 );
474
475 (start, extended_to)
476 }
477
478 // This macro avoids having the same code block 4x in the alignment processing
479 macro_rules! wrap_and_assert {
480 ($side:tt, $errhint:tt, $have:tt, $expected:tt) => {{
481 assert_eq!(*$have, $expected, "bad alignment index {}", $errhint);
482 $expected += 1;
483
484 wrap_syntax_and_diff(
485 &config,
486 &mut new_wrapped_syntax[$side],
487 &mut new_wrapped_diff[$side],
488 &mut syntax[$side],
489 &mut diff[$side],
490 &mut wrapinfo[$side],
491 line_width[$side],
492 &fill_style[$side],
493 $errhint,
494 )
495 }};
496 }
497
498 let mut m_expected = 0;
499 let mut p_expected = 0;
500
501 // Process blocks according to the alignment and build a new alignment.
502 // If lines get added via wrapping these are assigned the state HunkMinusWrapped/HunkPlusWrapped.
503 for (minus, plus) in alignment {
504 let (minus_extended, plus_extended) = match (minus, plus) {
505 (Some(m), None) => {
506 let (minus_start, extended_to) = wrap_and_assert!(Left, "[*l*] (-)", m, m_expected);
507
508 for i in minus_start..extended_to {
509 new_alignment.push((Some(i), None));
510 }
511
512 (extended_to - minus_start, 0)
513 }
514 (None, Some(p)) => {
515 let (plus_start, extended_to) = wrap_and_assert!(Right, "(-) [*r*]", p, p_expected);
516
517 for i in plus_start..extended_to {
518 new_alignment.push((None, Some(i)));
519 }
520
521 (0, extended_to - plus_start)
522 }
523 (Some(m), Some(p)) => {
524 let (minus_start, m_extended_to) =
525 wrap_and_assert!(Left, "[*l*] (r)", m, m_expected);
526 let (plus_start, p_extended_to) =
527 wrap_and_assert!(Right, "(l) [*r*]", p, p_expected);
528
529 for (new_m, new_p) in (minus_start..m_extended_to).zip(plus_start..p_extended_to) {
530 new_alignment.push((Some(new_m), Some(new_p)));
531 }
532
533 // This Some(m):Some(p) alignment might have become uneven, so fill
534 // up the shorter side with None.
535
536 let minus_extended = m_extended_to - minus_start;
537 let plus_extended = p_extended_to - plus_start;
538
539 let plus_minus = (minus_extended as isize) - (plus_extended as isize);
540
541 if plus_minus > 0 {
542 for m in (m_extended_to as isize - plus_minus) as usize..m_extended_to {
543 new_alignment.push((Some(m), None));
544 }
545 } else if plus_minus < 0 {
546 for p in (p_extended_to as isize + plus_minus) as usize..p_extended_to {
547 new_alignment.push((None, Some(p)));
548 }
549 }
550
551 (minus_extended, plus_extended)
552 }
553 _ => unreachable!("None-None alignment"),
554 };
555
556 if minus_extended > 0 {
557 new_states[Left].push(State::HunkMinus(DiffType::Unified, None));
558 for _ in 1..minus_extended {
559 new_states[Left].push(State::HunkMinusWrapped);
560 }
561 }
562 if plus_extended > 0 {
563 new_states[Right].push(State::HunkPlus(DiffType::Unified, None));
564 for _ in 1..plus_extended {
565 new_states[Right].push(State::HunkPlusWrapped);
566 }
567 }
568 }
569
570 (
571 new_alignment,
572 new_states,
573 new_wrapped_syntax,
574 new_wrapped_diff,
575 )
576 }
577
578 #[allow(clippy::comparison_chain, clippy::type_complexity)]
579 pub fn wrap_zero_block<'c: 'a, 'a>(
580 config: &'c Config,
581 line: &str,
582 mut states: Vec<State>,
583 syntax_style_sections: Vec<LineSections<'a, SyntectStyle>>,
584 diff_style_sections: Vec<LineSections<'a, Style>>,
585 line_numbers_data: &Option<&mut line_numbers::LineNumbersData>,
586 ) -> (
587 Vec<State>,
588 Vec<LineSections<'a, SyntectStyle>>,
589 Vec<LineSections<'a, Style>>,
590 ) {
591 // The width is the minimum of the left/right side. The panels should be equally sized,
592 // but in rare cases the remaining panel width might differ due to the space the line
593 // numbers take up.
594 let line_width = if let Some(line_numbers_data) = line_numbers_data {
595 let width = available_line_width(config, line_numbers_data);
596 std::cmp::min(width[Left], width[Right])
597 } else {
598 std::cmp::min(
599 config.side_by_side_data[Left].width,
600 config.side_by_side_data[Right].width,
601 )
602 };
603
604 // Called with a single line, so no need to use the 1-sized bool vector.
605 // If that changes the wrapping logic should be updated as well.
606 debug_assert_eq!(diff_style_sections.len(), 1);
607
608 let should_wrap = line_is_too_long(line, line_width);
609
610 if should_wrap {
611 let syntax_style = wrap_line(
612 config,
613 syntax_style_sections.into_iter().flatten(),
614 line_width,
615 &SyntectStyle::default(),
616 &Some(config.wrap_config.inline_hint_syntect_style),
617 );
618
619 // TODO: Why is the background color set to white when
620 // ansi_term_style.background is None?
621 let inline_hint_style = if config
622 .inline_hint_style
623 .ansi_term_style
624 .background
625 .is_some()
626 {
627 Some(config.inline_hint_style)
628 } else {
629 None
630 };
631 let diff_style = wrap_line(
632 config,
633 diff_style_sections.into_iter().flatten(),
634 line_width,
635 // To actually highlight inline hint characters:
636 &Style {
637 is_syntax_highlighted: true,
638 ..config.null_style
639 },
640 &inline_hint_style,
641 );
642
643 states.resize_with(syntax_style.len(), || State::HunkZeroWrapped);
644
645 (states, syntax_style, diff_style)
646 } else {
647 (states, syntax_style_sections, diff_style_sections)
648 }
649 }
650
651 #[cfg(test)]
652 mod tests {
653 use lazy_static::lazy_static;
654 use syntect::highlighting::Style as SyntectStyle;
655
656 use super::wrap_line;
657 use super::WrapConfig;
658 use crate::config::Config;
659 use crate::paint::LineSections;
660 use crate::style::Style;
661 use crate::tests::integration_test_utils::{make_config_from_args, DeltaTest};
662
663 lazy_static! {
664 static ref S1: Style = Style {
665 is_syntax_highlighted: true,
666 ..Default::default()
667 };
668 }
669 lazy_static! {
670 static ref S2: Style = Style {
671 is_emph: true,
672 ..Default::default()
673 };
674 }
675 lazy_static! {
676 static ref SY: SyntectStyle = SyntectStyle::default();
677 }
678 lazy_static! {
679 static ref SD: Style = Style::default();
680 }
681
682 const W: &str = "+"; // wrap
683 const WR: &str = "<"; // wrap-right
684 const RA: &str = ">"; // right-align
685
686 lazy_static! {
687 static ref WRAP_DEFAULT_ARGS: Vec<&'static str> = vec![
688 "--wrap-left-symbol",
689 W,
690 "--wrap-right-symbol",
691 WR,
692 "--wrap-right-prefix-symbol",
693 RA,
694 "--wrap-max-lines",
695 "4",
696 "--wrap-right-percent",
697 "37.0%",
698 ];
699 }
700
701 lazy_static! {
702 static ref TEST_WRAP_CFG: WrapConfig =
703 make_config_from_args(&WRAP_DEFAULT_ARGS).wrap_config;
704 }
705
706 fn default_wrap_cfg_plus<'a>(args: &[&'a str]) -> Vec<&'a str> {
707 let mut result = WRAP_DEFAULT_ARGS.clone();
708 result.extend_from_slice(args);
709 result
710 }
711
712 fn mk_wrap_cfg(wrap_cfg: &WrapConfig) -> Config {
713 let mut cfg: Config = make_config_from_args(&[]);
714 cfg.wrap_config = wrap_cfg.clone();
715 cfg
716 }
717
718 fn wrap_test<'a, I, S>(cfg: &'a Config, line: I, line_width: usize) -> Vec<LineSections<'a, S>>
719 where
720 I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug,
721 <I as IntoIterator>::IntoIter: DoubleEndedIterator,
722 S: Copy + Default + std::fmt::Debug,
723 {
724 wrap_line(cfg, line, line_width, &S::default(), &None)
725 }
726
727 #[test]
728 fn test_wrap_line_single() {
729 let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);
730
731 {
732 let line = vec![(*SY, "0")];
733 let lines = wrap_test(&cfg, line, 6);
734 assert_eq!(lines, vec![vec![(*SY, "0")]]);
735 }
736 {
737 let line = vec![(*S1, "012"), (*S2, "34")];
738 let lines = wrap_test(&cfg, line, 6);
739 assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "34")]]);
740 }
741 {
742 let line = vec![(*S1, "012"), (*S2, "345")];
743 let lines = wrap_test(&cfg, line, 6);
744 assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345")]]);
745 }
746 {
747 // Empty input usually does not happen
748 let line = vec![(*S1, "")];
749 let lines = wrap_test(&cfg, line, 6);
750 assert!(lines.is_empty());
751 }
752 {
753 // Partially empty should not happen either
754 let line = vec![(*S1, ""), (*S2, "0")];
755 let lines = wrap_test(&cfg, line, 6);
756 assert_eq!(lines, vec![vec![(*S1, ""), (*S2, "0")]]);
757 }
758 {
759 let line = vec![(*S1, "0"), (*S2, "")];
760 let lines = wrap_test(&cfg, line, 6);
761 assert_eq!(lines, vec![vec![(*S1, "0"), (*S2, "")]]);
762 }
763 {
764 let line = vec![
765 (*S1, "0"),
766 (*S2, ""),
767 (*S1, ""),
768 (*S2, ""),
769 (*S1, ""),
770 (*S2, ""),
771 (*S1, ""),
772 (*S2, ""),
773 (*S1, ""),
774 (*S2, ""),
775 ];
776 let lines = wrap_test(&cfg, line, 6);
777 assert_eq!(
778 lines,
779 vec![vec![
780 (*S1, "0"),
781 (*S2, ""),
782 (*S1, ""),
783 (*S2, ""),
784 (*S1, ""),
785 (*S2, ""),
786 (*S1, ""),
787 (*S2, ""),
788 (*S1, ""),
789 (*S2, "")
790 ]]
791 );
792 }
793 }
794
795 #[test]
796 fn test_wrap_line_align_right_1() {
797 let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);
798
799 let line = vec![(*S1, "0123456789ab")];
800 let lines = wrap_test(&cfg, line, 11);
801 assert_eq!(lines.len(), 2);
802 assert_eq!(lines[0].last().unwrap().1, WR);
803 assert_eq!(lines[1], [(*SD, " "), (*SD, ">"), (*S1, "ab")]);
804 }
805
806 #[test]
807 fn test_wrap_line_align_right_2() {
808 let line = vec![(*S1, "012"), (*S2, "3456")];
809
810 {
811 // Right align lines on the second line
812 let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);
813
814 let lines = wrap_test(&cfg, line.clone(), 6);
815 assert_eq!(
816 lines,
817 vec![
818 vec![(*S1, "012"), (*S2, "34"), (*SD, WR)],
819 vec![(*SD, " "), (*SD, RA), (*S2, "56")]
820 ]
821 );
822 }
823
824 {
825 // Set right align percentage lower, normal wrapping
826 let mut no_align_right = TEST_WRAP_CFG.clone();
827 no_align_right.use_wrap_right_permille = 1; // 0.1%
828 let cfg_no_align_right = mk_wrap_cfg(&no_align_right);
829
830 let lines = wrap_test(&cfg_no_align_right, line, 6);
831 assert_eq!(
832 lines,
833 vec![vec![(*S1, "012"), (*S2, "34"), (*SD, W)], vec![(*S2, "56")]]
834 );
835 }
836 }
837
838 #[test]
839 fn test_wrap_line_newlines() {
840 fn mk_input(len: usize) -> LineSections<'static, Style> {
841 const IN: &str = "0123456789abcdefZ";
842 let v = &[*S1, *S2];
843 let s1s2 = v.iter().cycle();
844 let text: Vec<_> = IN.matches(|_| true).take(len + 1).collect();
845 s1s2.zip(text.iter())
846 .map(|(style, text)| (*style, *text))
847 .collect()
848 }
849 fn mk_input_nl(len: usize) -> LineSections<'static, Style> {
850 const NL: &str = "\n";
851 let mut line = mk_input(len);
852 line.push((*S2, NL));
853 line
854 }
855 fn mk_expected<'a>(
856 vec: &LineSections<'a, Style>,
857 from: usize,
858 to: usize,
859 append: Option<(Style, &'a str)>,
860 ) -> LineSections<'a, Style> {
861 let mut result: Vec<_> = vec[from..to].to_vec();
862 if let Some(val) = append {
863 result.push(val);
864 }
865 result
866 }
867
868 let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);
869
870 {
871 let line = vec![(*S1, "012"), (*S2, "345\n")];
872 let lines = wrap_test(&cfg, line, 6);
873 assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345\n")]]);
874 }
875
876 {
877 for i in 0..=5 {
878 let line = mk_input(i);
879 let lines = wrap_test(&cfg, line, 6);
880 assert_eq!(lines, vec![mk_input(i)]);
881
882 let line = mk_input_nl(i);
883 let lines = wrap_test(&cfg, line, 6);
884 assert_eq!(lines, vec![mk_input_nl(i)]);
885 }
886 }
887
888 {
889 let line = mk_input_nl(9);
890 let lines = wrap_test(&cfg, line, 3);
891 let expected = mk_input_nl(9);
892 let line1 = mk_expected(&expected, 0, 2, Some((*SD, W)));
893 let line2 = mk_expected(&expected, 2, 4, Some((*SD, W)));
894 let line3 = mk_expected(&expected, 4, 6, Some((*SD, W)));
895 let line4 = mk_expected(&expected, 6, 8, Some((*SD, W)));
896 let line5 = mk_expected(&expected, 8, 11, None);
897 assert_eq!(lines, vec![line1, line2, line3, line4, line5]);
898 }
899
900 {
901 let line = mk_input_nl(10);
902 let lines = wrap_test(&cfg, line, 3);
903 let expected = mk_input_nl(10);
904 let line1 = mk_expected(&expected, 0, 2, Some((*SD, W)));
905 let line2 = mk_expected(&expected, 2, 4, Some((*SD, W)));
906 let line3 = mk_expected(&expected, 4, 6, Some((*SD, W)));
907 let line4 = mk_expected(&expected, 6, 8, Some((*SD, W)));
908 let line5 = mk_expected(&expected, 8, 11, Some((*S2, "\n")));
909 assert_eq!(lines, vec![line1, line2, line3, line4, line5]);
910 }
911
912 {
913 let line = vec![(*S1, "abc"), (*S2, "01230123012301230123"), (*S1, "ZZZZZ")];
914
915 let wcfg1 = mk_wrap_cfg(&WrapConfig {
916 max_lines: 1,
917 ..TEST_WRAP_CFG.clone()
918 });
919 let wcfg2 = mk_wrap_cfg(&WrapConfig {
920 max_lines: 2,
921 ..TEST_WRAP_CFG.clone()
922 });
923 let wcfg3 = mk_wrap_cfg(&WrapConfig {
924 max_lines: 3,
925 ..TEST_WRAP_CFG.clone()
926 });
927
928 let lines = wrap_line(&wcfg1, line.clone(), 4, &Style::default(), &None);
929 assert_eq!(lines.len(), 1);
930 assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
931 let lines = wrap_line(&wcfg2, line.clone(), 4, &Style::default(), &None);
932 assert_eq!(lines.len(), 2);
933 assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
934 let lines = wrap_line(&wcfg3, line.clone(), 4, &Style::default(), &None);
935 assert_eq!(lines.len(), 3);
936 assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ");
937 }
938 }
939
940 #[test]
941 fn test_wrap_line_unicode() {
942 let cfg = mk_wrap_cfg(&TEST_WRAP_CFG);
943
944 // from UnicodeSegmentation documentation and the linked
945 // Unicode Standard Annex #29
946 let line = vec![(*S1, "abc"), (*S2, "mnö̲"), (*S1, "xyz")];
947 let lines = wrap_test(&cfg, line, 4);
948 assert_eq!(
949 lines,
950 vec![
951 vec![(*S1, "abc"), (*SD, W)],
952 vec![(*S2, "mnö̲"), (*SD, W)],
953 vec![(*S1, "xyz")]
954 ]
955 );
956
957 // Not working: Tailored grapheme clusters: क्षि = क् + षि
958 //
959 // Difference compare to previous example (even they may look like the
960 // same width in text editor.) :
961 //
962 // width நி: 2
963 // width ö̲: 1
964 let line = vec![(*S1, "abc"), (*S2, "dநி"), (*S1, "ghij")];
965 let lines = wrap_test(&cfg, line, 4);
966 assert_eq!(
967 lines,
968 vec![
969 vec![(*S1, "abc"), (*SD, W)],
970 vec![(*S2, "dநி"), (*SD, W)],
971 vec![(*S1, "ghij")]
972 ]
973 );
974 }
975
976 const HUNK_ZERO_DIFF: &str = "\
977 diff --git i/a.py w/a.py
978 index 223ca50..e69de29 100644
979 --- i/a.py
980 +++ w/a.py
981 @@ -4,3 +15,3 @@
982 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
983 -a = 1
984 +a = 2
985 ";
986
987 const HUNK_ZERO_LARGE_LINENUMBERS_DIFF: &str = "\
988 diff --git i/a.py w/a.py
989 index 223ca50..e69de29 100644
990 --- i/a.py
991 +++ w/a.py
992 @@ -10,3 +101999,3 @@
993 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
994 -a = 1
995 +a = 2
996 ";
997
998 const HUNK_MP_DIFF: &str = "\
999 diff --git i/a.py w/a.py
1000 index 223ca50..e69de29 100644
1001 --- i/a.py
1002 +++ w/a.py
1003 @@ -4,3 +15,3 @@
1004 abcdefghijklmnopqrstuvwxzy 0123456789 0123456789 0123456789 0123456789 0123456789
1005 -a = 0123456789 0123456789 0123456789 0123456789 0123456789
1006 +b = 0123456789 0123456789 0123456789 0123456789 0123456789
1007 ";
1008
1009 const HUNK_ALIGN_DIFF_HEADER: &str = "--- a\n+++ b\n@@ -1,1 +1,1 @@\n";
1010 const HUNK_ALIGN_DIFF_SHORT: &str = ".........1.........2....\n";
1011 const HUNK_ALIGN_DIFF_LONG: &str =
1012 ".........1.........2.........3.........4.........5.........6\n";
1013
1014 #[test]
1015 fn test_wrap_with_unequal_hunk_zero_width() {
1016 DeltaTest::with_args(&default_wrap_cfg_plus(&[
1017 "--side-by-side",
1018 "--line-numbers-left-format",
1019 "│L│",
1020 "--line-numbers-right-format",
1021 "│RRRR│",
1022 "--width",
1023 "40",
1024 "--line-fill-method",
1025 "spaces",
1026 ]))
1027 .set_config(|cfg| cfg.truncation_symbol = ">".into())
1028 .with_input(HUNK_ZERO_DIFF)
1029 .expect_after_header(
1030 r#"
1031 │L│abcdefghijklm+ │RRRR│abcdefghijklm+
1032 │L│nopqrstuvwxzy+ │RRRR│nopqrstuvwxzy+
1033 │L│ 0123456789 0+ │RRRR│ 0123456789 0+
1034 │L│123456789 012+ │RRRR│123456789 012+
1035 │L│3456789 01234567>│RRRR│3456789 01234>
1036 │L│a = 1 │RRRR│a = 2 "#,
1037 );
1038 }
1039
1040 #[test]
1041 fn test_wrap_with_large_hunk_zero_line_numbers() {
1042 DeltaTest::with_args(&default_wrap_cfg_plus(&[
1043 "--side-by-side",
1044 "--line-numbers-left-format",
1045 "│LLL│",
1046 "--line-numbers-right-format",
1047 "│WW {nm} +- {np:2} WW│",
1048 "--width",
1049 "60",
1050 "--line-fill-method",
1051 "ansi",
1052 ]))
1053 .set_config(|cfg| cfg.truncation_symbol = ">".into())
1054 .with_input(HUNK_ZERO_LARGE_LINENUMBERS_DIFF)
1055 .expect_after_header(
1056 r#"
1057 │LLL│abcde+ │WW 10 +- 101999 WW│abcde+
1058 │LLL│fghij+ │WW +- WW│fghij+
1059 │LLL│klmno+ │WW +- WW│klmno+
1060 │LLL│pqrst+ │WW +- WW│pqrst+
1061 │LLL│uvwxzy 0123456789 012345>│WW +- WW│uvwxz>
1062 │LLL│a = 1 │WW +- 102000 WW│a = 2"#,
1063 );
1064 }
1065
1066 #[test]
1067 fn test_wrap_with_keep_markers() {
1068 use crate::features::side_by_side::ansifill::ODD_PAD_CHAR;
1069 let t = DeltaTest::with_args(&default_wrap_cfg_plus(&[
1070 "--side-by-side",
1071 "--keep-plus-minus-markers",
1072 "--width",
1073 "45",
1074 ]))
1075 .set_config(|cfg| cfg.truncation_symbol = ">".into())
1076 .with_input(HUNK_MP_DIFF)
1077 .expect_after_header(
1078 r#"
1079 │ 4 │ abcdefghijklmn+ │ 15 │ abcdefghijklmn+
1080 │ │ opqrstuvwxzy 0+ │ │ opqrstuvwxzy 0+
1081 │ │ 123456789 0123+ │ │ 123456789 0123+
1082 │ │ 456789 0123456+ │ │ 456789 0123456+
1083 │ │ 789 0123456789> │ │ 789 0123456789>
1084 │ 5 │-a = 0123456789+ │ 16 │+b = 0123456789+
1085 │ │ 0123456789 01+ │ │ 0123456789 01+
1086 │ │ 23456789 01234+ │ │ 23456789 01234+
1087 │ │ 56789 01234567+ │ │ 56789 01234567+
1088 │ │ 89 │ │ 89"#,
1089 // this column here is^ where ODD_PAD_CHAR is inserted due to the odd 45 width
1090 );
1091
1092 assert!(!t.output.is_empty());
1093
1094 for line in t.output.lines().skip(crate::config::HEADER_LEN) {
1095 assert_eq!(line.chars().nth(22), Some(ODD_PAD_CHAR));
1096 }
1097 }
1098
1099 #[test]
1100 fn test_alignment_2_lines_vs_3_lines() {
1101 let config =
1102 make_config_from_args(&default_wrap_cfg_plus(&["--side-by-side", "--width", "55"]));
1103
1104 {
1105 DeltaTest::with_config(&config)
1106 .with_input(&format!(
1107 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_SHORT}+{HUNK_ALIGN_DIFF_LONG}",
1108 ))
1109 .expect_after_header(
1110 r#"
1111 │ 1 │.........1.........2< │ 1 │.........1.........2+
1112 │ │ >.... │ │.........3.........4+
1113 │ │ │ │.........5.........6"#,
1114 );
1115 // the place where ODD_PAD_CHAR^ is inserted due to the odd 55 width
1116 }
1117
1118 {
1119 DeltaTest::with_config(&config)
1120 .with_input(&format!(
1121 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_LONG}+{HUNK_ALIGN_DIFF_SHORT}",
1122 ))
1123 .expect_after_header(
1124 r#"
1125 │ 1 │.........1.........2+ │ 1 │.........1.........2<
1126 │ │.........3.........4+ │ │ >....
1127 │ │.........5.........6 │ │"#,
1128 );
1129 }
1130 }
1131
1132 #[test]
1133 fn test_alignment_1_line_vs_3_lines() {
1134 let config = make_config_from_args(&default_wrap_cfg_plus(&[
1135 "--side-by-side",
1136 "--width",
1137 "61",
1138 "--line-fill-method",
1139 "spaces",
1140 ]));
1141
1142 {
1143 DeltaTest::with_config(&config)
1144 .with_input(&format!(
1145 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_SHORT}+{HUNK_ALIGN_DIFF_LONG}",
1146 ))
1147 .expect_after_header(
1148 r#"
1149 │ 1 │.........1.........2....│ 1 │.........1.........2...+
1150 │ │ │ │......3.........4......+
1151 │ │ │ │...5.........6 "#,
1152 );
1153 }
1154
1155 {
1156 DeltaTest::with_config(&config)
1157 .with_input(&format!(
1158 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_LONG}+{HUNK_ALIGN_DIFF_SHORT}",
1159 ))
1160 .expect_after_header(
1161 r#"
1162 │ 1 │.........1.........2...+│ 1 │.........1.........2....
1163 │ │......3.........4......+│ │
1164 │ │...5.........6 │ │"#,
1165 );
1166 }
1167 }
1168
1169 #[test]
1170 fn test_wrap_max_lines_2() {
1171 // TODO overriding is not possible, need to change config directly
1172 let mut config = make_config_from_args(&default_wrap_cfg_plus(&[
1173 // "--wrap-max-lines",
1174 // "2",
1175 "--side-by-side",
1176 "--width",
1177 "72",
1178 "--line-fill-method",
1179 "spaces",
1180 ]));
1181 config.truncation_symbol = ">".into();
1182
1183 {
1184 DeltaTest::with_config(&config)
1185 .with_input(&format!(
1186 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_SHORT}+{HUNK_ALIGN_DIFF_LONG}",
1187 ))
1188 .expect_after_header(
1189 r#"
1190 │ 1 │.........1.........2.... │ 1 │.........1.........2.........+
1191 │ │ │ │3.........4.........5........+
1192 │ │ │ │.6 "#,
1193 );
1194 }
1195
1196 {
1197 config.wrap_config.max_lines = 2;
1198 DeltaTest::with_config(&config)
1199 .with_input(&format!(
1200 "{HUNK_ALIGN_DIFF_HEADER}-{HUNK_ALIGN_DIFF_SHORT}+{HUNK_ALIGN_DIFF_LONG}",
1201 ))
1202 .expect_after_header(
1203 r#"
1204 │ 1 │.........1.........2.... │ 1 │.........1.........2.........+
1205 │ │ │ │3.........4.........5........>"#,
1206 );
1207 }
1208 }
1209 }