Debian Codegraph @

src/features/line_numbers.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use std::cmp::max;
2
3 use lazy_static::lazy_static;
4 use regex::Regex;
5
6 use crate::color::ColorMode::*;
7 use crate::config;
8 use crate::delta::State;
9 use crate::features::hyperlinks;
10 use crate::features::side_by_side::ansifill::{self, ODD_PAD_CHAR};
11 use crate::features::side_by_side::{Left, PanelSide, Right};
12 use crate::features::OptionValueFunction;
13 use crate::format::{self, Align, Placeholder};
14 use crate::minusplus::*;
15 use crate::style::Style;
16 use crate::utils;
17
18 pub fn make_feature() -> Vec<(String, OptionValueFunction)> {
19 builtin_feature!([
20 (
21 "line-numbers",
22 bool,
23 None,
24 _opt => true
25 ),
26 (
27 "line-numbers-left-style",
28 String,
29 None,
30 _opt => "blue"
31 ),
32 (
33 "line-numbers-right-style",
34 String,
35 None,
36 _opt => "blue"
37 ),
38 (
39 "line-numbers-minus-style",
40 String,
41 None,
42 opt => match opt.computed.color_mode {
43 Light => "red",
44 Dark => "88",
45 }
46 ),
47 (
48 "line-numbers-zero-style",
49 String,
50 None,
51 opt => match opt.computed.color_mode {
52 Light => "#dddddd",
53 Dark => "#444444",
54 }
55 ),
56 (
57 "line-numbers-plus-style",
58 String,
59 None,
60 opt => match opt.computed.color_mode {
61 Light => "green",
62 Dark => "28",
63 }
64 )
65 ])
66 }
67
68 pub fn linenumbers_and_styles<'a>(
69 line_numbers_data: &'a mut LineNumbersData,
70 state: &State,
71 config: &'a config::Config,
72 increment: bool,
73 ) -> Option<(MinusPlus<Option<usize>>, MinusPlus<Style>)> {
74 let nr_left = line_numbers_data.line_number[Left];
75 let nr_right = line_numbers_data.line_number[Right];
76 let (minus_style, zero_style, plus_style) = (
77 config.line_numbers_style_minusplus[Minus],
78 config.line_numbers_zero_style,
79 config.line_numbers_style_minusplus[Plus],
80 );
81 let ((minus_number, plus_number), (minus_style, plus_style)) = match state {
82 State::HunkMinus(_, _) => {
83 line_numbers_data.line_number[Left] += increment as usize;
84 ((Some(nr_left), None), (minus_style, plus_style))
85 }
86 State::HunkMinusWrapped => ((None, None), (minus_style, plus_style)),
87 State::HunkZero(_, _) => {
88 line_numbers_data.line_number[Left] += increment as usize;
89 line_numbers_data.line_number[Right] += increment as usize;
90 ((Some(nr_left), Some(nr_right)), (zero_style, zero_style))
91 }
92 State::HunkZeroWrapped => ((None, None), (zero_style, zero_style)),
93 State::HunkPlus(_, _) => {
94 line_numbers_data.line_number[Right] += increment as usize;
95 ((None, Some(nr_right)), (minus_style, plus_style))
96 }
97 State::HunkPlusWrapped => ((None, None), (minus_style, plus_style)),
98 _ => return None,
99 };
100 Some((
101 MinusPlus::new(minus_number, plus_number),
102 MinusPlus::new(minus_style, plus_style),
103 ))
104 }
105
106 /// Return a vec of `ansi_term::ANSIGenericString`s representing the left and right fields of the
107 /// two-column line number display.
108 pub fn format_and_paint_line_numbers<'a>(
109 line_numbers_data: &'a LineNumbersData,
110 side_by_side_panel: Option<PanelSide>,
111 styles: MinusPlus<Style>,
112 line_numbers: MinusPlus<Option<usize>>,
113 config: &'a config::Config,
114 ) -> Vec<ansi_term::ANSIGenericString<'a, str>> {
115 let mut formatted_numbers = Vec::new();
116
117 let (emit_left, emit_right) = match (config.side_by_side, side_by_side_panel) {
118 (false, _) => (true, true),
119 (true, Some(Left)) => (true, false),
120 (true, Some(Right)) => (false, true),
121 (true, None) => unreachable!(),
122 };
123
124 if emit_left {
125 formatted_numbers.extend(format_and_paint_line_number_field(
126 line_numbers_data,
127 Minus,
128 &styles,
129 &line_numbers,
130 config,
131 ));
132 }
133
134 if emit_right {
135 formatted_numbers.extend(format_and_paint_line_number_field(
136 line_numbers_data,
137 Plus,
138 &styles,
139 &line_numbers,
140 config,
141 ));
142 }
143 formatted_numbers
144 }
145
146 lazy_static! {
147 static ref LINE_NUMBERS_PLACEHOLDER_REGEX: Regex =
148 format::make_placeholder_regex(&["nm", "np"]);
149 }
150
151 #[derive(Default, Debug)]
152 pub struct LineNumbersData<'a> {
153 pub format_data: MinusPlus<format::FormatStringData<'a>>,
154 pub line_number: MinusPlus<usize>,
155 pub hunk_max_line_number_width: usize,
156 pub plus_file: String,
157 }
158
159 pub type SideBySideLineWidth = MinusPlus<usize>;
160
161 // Although it's probably unusual, a single format string can contain multiple placeholders. E.g.
162 // line-numbers-right-format = "{nm} {np}|"
163 impl<'a> LineNumbersData<'a> {
164 pub fn from_format_strings(
165 format: &'a MinusPlus<String>,
166 use_full_width: ansifill::UseFullPanelWidth,
167 ) -> LineNumbersData<'a> {
168 let insert_center_space_on_odd_width = use_full_width.pad_width();
169 Self {
170 format_data: MinusPlus::new(
171 format::parse_line_number_format(
172 &format[Left],
173 &LINE_NUMBERS_PLACEHOLDER_REGEX,
174 false,
175 ),
176 format::parse_line_number_format(
177 &format[Right],
178 &LINE_NUMBERS_PLACEHOLDER_REGEX,
179 insert_center_space_on_odd_width,
180 ),
181 ),
182 ..Self::default()
183 }
184 }
185
186 /// Initialize line number data for a hunk.
187 pub fn initialize_hunk(&mut self, line_numbers: &[(usize, usize)], plus_file: String) {
188 // Typically, line_numbers has length 2: an entry for the minus file, and one for the plus
189 // file. In the case of merge commits, it may be longer.
190 self.line_number =
191 MinusPlus::new(line_numbers[0].0, line_numbers[line_numbers.len() - 1].0);
192 let hunk_max_line_number = line_numbers.iter().map(|(n, d)| n + d).max().unwrap();
193 self.hunk_max_line_number_width =
194 1 + (hunk_max_line_number as f64).log10().floor() as usize;
195 self.plus_file = plus_file;
196 }
197
198 pub fn empty_for_sbs(use_full_width: ansifill::UseFullPanelWidth) -> LineNumbersData<'a> {
199 let insert_center_space_on_odd_width = use_full_width.pad_width();
200 Self {
201 format_data: if insert_center_space_on_odd_width {
202 let format_left = vec![format::FormatStringPlaceholderData::default()];
203 let format_right = vec![format::FormatStringPlaceholderData {
204 prefix: format!("{ODD_PAD_CHAR}").into(),
205 prefix_len: 1,
206 ..Default::default()
207 }];
208 MinusPlus::new(format_left, format_right)
209 } else {
210 MinusPlus::default()
211 },
212 ..Self::default()
213 }
214 }
215
216 pub fn formatted_width(&self) -> SideBySideLineWidth {
217 let format_data_width = |format_data: &format::FormatStringData<'a>| {
218 // Provide each Placeholder with the max_line_number_width to calculate the
219 // actual width. Only use prefix and suffix of the last element, otherwise
220 // only the prefix (as the suffix also contains the following prefix).
221 format_data
222 .last()
223 .map(|last| {
224 let (prefix_width, suffix_width) = last.width(self.hunk_max_line_number_width);
225 format_data
226 .iter()
227 .rev()
228 .skip(1)
229 .map(|p| p.width(self.hunk_max_line_number_width).0)
230 .sum::<usize>()
231 + prefix_width
232 + suffix_width
233 })
234 .unwrap_or(0)
235 };
236 MinusPlus::new(
237 format_data_width(&self.format_data[Left]),
238 format_data_width(&self.format_data[Right]),
239 )
240 }
241 }
242
243 #[allow(clippy::too_many_arguments)]
244 fn format_and_paint_line_number_field<'a>(
245 line_numbers_data: &'a LineNumbersData,
246 side: MinusPlusIndex,
247 styles: &MinusPlus<Style>,
248 line_numbers: &MinusPlus<Option<usize>>,
249 config: &config::Config,
250 ) -> Vec<ansi_term::ANSIGenericString<'a, str>> {
251 let min_field_width = line_numbers_data.hunk_max_line_number_width;
252
253 let format_data = &line_numbers_data.format_data[side];
254 let plus_file = &line_numbers_data.plus_file;
255 let style = &config.line_numbers_style_leftright[side];
256
257 let mut ansi_strings = Vec::new();
258 let mut suffix = "";
259 for placeholder in format_data {
260 ansi_strings.push(style.paint(placeholder.prefix.as_str()));
261
262 let width = if let Some(placeholder_width) = placeholder.width {
263 max(placeholder_width, min_field_width)
264 } else {
265 min_field_width
266 };
267
268 let alignment_spec = placeholder.alignment_spec.unwrap_or(Align::Center);
269 match placeholder.placeholder {
270 Some(Placeholder::NumberMinus) => {
271 ansi_strings.push(styles[Minus].paint(format_line_number(
272 line_numbers[Minus],
273 alignment_spec,
274 width,
275 placeholder.precision,
276 None,
277 config,
278 )))
279 }
280 Some(Placeholder::NumberPlus) => {
281 ansi_strings.push(styles[Plus].paint(format_line_number(
282 line_numbers[Plus],
283 alignment_spec,
284 width,
285 placeholder.precision,
286 Some(plus_file),
287 config,
288 )))
289 }
290 None => {}
291 _ => unreachable!("Invalid placeholder"),
292 }
293 suffix = placeholder.suffix.as_str();
294 }
295 ansi_strings.push(style.paint(suffix));
296 ansi_strings
297 }
298
299 /// Return line number formatted according to `alignment` and `width`.
300 fn format_line_number(
301 line_number: Option<usize>,
302 alignment: Align,
303 width: usize,
304 precision: Option<usize>,
305 plus_file: Option<&str>,
306 config: &config::Config,
307 ) -> String {
308 let pad = |n| format::pad(n, width, alignment, precision);
309 match (line_number, config.hyperlinks, plus_file) {
310 (None, _, _) => " ".repeat(width),
311 (Some(n), true, Some(file)) => match utils::path::absolute_path(file, config) {
312 Some(absolute_path) => {
313 hyperlinks::format_osc8_file_hyperlink(absolute_path, line_number, &pad(n), config)
314 .to_string()
315 }
316 None => pad(n),
317 },
318 (Some(n), _, _) => pad(n),
319 }
320 }
321
322 #[cfg(test)]
323 pub mod tests {
324 use regex::Captures;
325
326 use crate::ansi::strip_ansi_codes;
327 use crate::features::side_by_side::ansifill::ODD_PAD_CHAR;
328 use crate::format::FormatStringData;
329 use crate::tests::integration_test_utils::{make_config_from_args, run_delta, DeltaTest};
330
331 use super::*;
332
333 pub fn parse_line_number_format_with_default_regex(
334 format_string: &str,
335 ) -> FormatStringData<'_> {
336 format::parse_line_number_format(format_string, &LINE_NUMBERS_PLACEHOLDER_REGEX, false)
337 }
338
339 #[test]
340 fn test_line_number_format_regex_1() {
341 assert_eq!(
342 parse_line_number_format_with_default_regex("{nm}"),
343 vec![format::FormatStringPlaceholderData {
344 prefix: "".into(),
345 placeholder: Some(Placeholder::NumberMinus),
346 ..Default::default()
347 }]
348 )
349 }
350
351 #[test]
352 fn test_line_number_format_regex_2() {
353 assert_eq!(
354 parse_line_number_format_with_default_regex("{np:4}"),
355 vec![format::FormatStringPlaceholderData {
356 prefix: "".into(),
357 placeholder: Some(Placeholder::NumberPlus),
358 alignment_spec: None,
359 width: Some(4),
360 ..Default::default()
361 }]
362 )
363 }
364
365 #[test]
366 fn test_line_number_format_regex_3() {
367 assert_eq!(
368 parse_line_number_format_with_default_regex("{np:>4}"),
369 vec![format::FormatStringPlaceholderData {
370 prefix: "".into(),
371 placeholder: Some(Placeholder::NumberPlus),
372 alignment_spec: Some(Align::Right),
373 width: Some(4),
374 precision: None,
375 ..Default::default()
376 }]
377 )
378 }
379
380 #[test]
381 fn test_line_number_format_regex_4() {
382 assert_eq!(
383 parse_line_number_format_with_default_regex("{np:_>4}"),
384 vec![format::FormatStringPlaceholderData {
385 prefix: "".into(),
386 placeholder: Some(Placeholder::NumberPlus),
387 alignment_spec: Some(Align::Right),
388 width: Some(4),
389 ..Default::default()
390 }]
391 )
392 }
393
394 #[test]
395 fn test_line_number_format_regex_5() {
396 assert_eq!(
397 parse_line_number_format_with_default_regex("__{np:_>4}@@"),
398 vec![format::FormatStringPlaceholderData {
399 prefix: "__".into(),
400 placeholder: Some(Placeholder::NumberPlus),
401 alignment_spec: Some(Align::Right),
402 width: Some(4),
403 precision: None,
404 suffix: "@@".into(),
405 prefix_len: 2,
406 suffix_len: 2,
407 ..Default::default()
408 }]
409 )
410 }
411
412 #[test]
413 fn test_line_number_format_regex_6() {
414 assert_eq!(
415 parse_line_number_format_with_default_regex("__{nm:<3}@@---{np:_>4}**"),
416 vec![
417 format::FormatStringPlaceholderData {
418 prefix: "__".into(),
419 placeholder: Some(Placeholder::NumberMinus),
420 alignment_spec: Some(Align::Left),
421 width: Some(3),
422 precision: None,
423 suffix: "@@---{np:_>4}**".into(),
424 prefix_len: 2,
425 suffix_len: 15,
426 ..Default::default()
427 },
428 format::FormatStringPlaceholderData {
429 prefix: "@@---".into(),
430 placeholder: Some(Placeholder::NumberPlus),
431 alignment_spec: Some(Align::Right),
432 width: Some(4),
433 precision: None,
434 suffix: "**".into(),
435 prefix_len: 5,
436 suffix_len: 2,
437 ..Default::default()
438 }
439 ]
440 )
441 }
442
443 #[test]
444 fn test_line_number_format_regex_7() {
445 assert_eq!(
446 parse_line_number_format_with_default_regex("__@@---**",),
447 vec![format::FormatStringPlaceholderData {
448 prefix: "".into(),
449 placeholder: None,
450 alignment_spec: None,
451 width: None,
452 precision: None,
453 suffix: "__@@---**".into(),
454 prefix_len: 0,
455 suffix_len: 9,
456 ..Default::default()
457 },]
458 )
459 }
460
461 #[test]
462 fn test_line_number_format_odd_width_one() {
463 assert_eq!(
464 format::parse_line_number_format("|{nm:<4}|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true),
465 vec![format::FormatStringPlaceholderData {
466 prefix: format!("{ODD_PAD_CHAR}|").into(),
467 placeholder: Some(Placeholder::NumberMinus),
468 alignment_spec: Some(Align::Left),
469 width: Some(4),
470 precision: None,
471 suffix: "|".into(),
472 prefix_len: 2,
473 suffix_len: 1,
474 ..Default::default()
475 }]
476 );
477 }
478
479 #[test]
480 fn test_line_number_format_odd_width_two() {
481 assert_eq!(
482 format::parse_line_number_format(
483 "|{nm:<4}+{np:<4}|",
484 &LINE_NUMBERS_PLACEHOLDER_REGEX,
485 true
486 ),
487 vec![
488 format::FormatStringPlaceholderData {
489 prefix: format!("{ODD_PAD_CHAR}|").into(),
490 placeholder: Some(Placeholder::NumberMinus),
491 alignment_spec: Some(Align::Left),
492 width: Some(4),
493 precision: None,
494 suffix: "+{np:<4}|".into(),
495 prefix_len: 2,
496 suffix_len: 9,
497 ..Default::default()
498 },
499 format::FormatStringPlaceholderData {
500 prefix: "+".into(),
501 placeholder: Some(Placeholder::NumberPlus),
502 alignment_spec: Some(Align::Left),
503 width: Some(4),
504 precision: None,
505 suffix: "|".into(),
506 prefix_len: 1,
507 suffix_len: 1,
508 ..Default::default()
509 }
510 ]
511 );
512 }
513 #[test]
514 fn test_line_number_format_odd_width_none() {
515 assert_eq!(
516 format::parse_line_number_format("|++|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true),
517 vec![format::FormatStringPlaceholderData {
518 prefix: format!("{ODD_PAD_CHAR}").into(),
519 placeholder: None,
520 alignment_spec: None,
521 width: None,
522 precision: None,
523 suffix: "|++|".into(),
524 prefix_len: 1,
525 suffix_len: 4,
526 ..Default::default()
527 }]
528 );
529 }
530
531 #[test]
532 fn test_line_number_format_long() {
533 let long = "line number format which is too large for SSO";
534 assert!(long.len() > std::mem::size_of::<smol_str::SmolStr>());
535 assert_eq!(
536 parse_line_number_format_with_default_regex(&format!("{long}{{nm}}{long}")),
537 vec![format::FormatStringPlaceholderData {
538 prefix: long.into(),
539 prefix_len: long.len(),
540 placeholder: Some(Placeholder::NumberMinus),
541 alignment_spec: None,
542 width: None,
543 precision: None,
544 suffix: long.into(),
545 suffix_len: long.len(),
546 ..Default::default()
547 },]
548 )
549 }
550
551 #[test]
552 fn test_line_number_placeholder_width_one() {
553 let data = parse_line_number_format_with_default_regex("");
554 assert_eq!(data[0].width(0), (0, 0));
555
556 let data = parse_line_number_format_with_default_regex("");
557 assert_eq!(data[0].width(4), (0, 0));
558
559 let data = parse_line_number_format_with_default_regex("│+│");
560 assert_eq!(data[0].width(4), (0, 3));
561
562 let data = parse_line_number_format_with_default_regex("{np}");
563 assert_eq!(data[0].width(4), (4, 0));
564
565 let data = parse_line_number_format_with_default_regex("│{np}│");
566 assert_eq!(data[0].width(4), (5, 1));
567
568 let data = parse_line_number_format_with_default_regex("│{np:2}│");
569 assert_eq!(data[0].width(4), (5, 1));
570
571 let data = parse_line_number_format_with_default_regex("│{np:6}│");
572 assert_eq!(data[0].width(4), (7, 1));
573 }
574
575 #[test]
576 fn test_line_number_placeholder_width_two() {
577 let data = parse_line_number_format_with_default_regex("│{nm}│{np}│");
578 assert_eq!(data[0].width(1), (2, 6));
579 assert_eq!(data[1].width(1), (2, 1));
580
581 let data = parse_line_number_format_with_default_regex("│{nm:_>5}│{np:1}│");
582 assert_eq!(data[0].width(1), (6, 8));
583 assert_eq!(data[1].width(1), (2, 1));
584
585 let data = parse_line_number_format_with_default_regex("│{nm}│{np:5}│");
586 assert_eq!(data[0].width(7), (8, 8));
587 assert_eq!(data[1].width(7), (8, 1));
588 }
589
590 #[test]
591 fn test_line_numbers_data() {
592 use crate::features::side_by_side::ansifill;
593 let w = ansifill::UseFullPanelWidth(false);
594 let format = MinusPlus::new("".into(), "".into());
595 let mut data = LineNumbersData::from_format_strings(&format, w.clone());
596 data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
597 assert_eq!(data.formatted_width(), MinusPlus::new(0, 0));
598
599 let format = MinusPlus::new("│".into(), "│+│".into());
600 let mut data = LineNumbersData::from_format_strings(&format, w.clone());
601
602 data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
603 assert_eq!(data.formatted_width(), MinusPlus::new(1, 3));
604
605 let format = MinusPlus::new("│{nm:^3}│".into(), "│{np:^3}│".into());
606 let mut data = LineNumbersData::from_format_strings(&format, w.clone());
607
608 data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
609 assert_eq!(data.formatted_width(), MinusPlus::new(8, 8));
610
611 let format = MinusPlus::new("│{nm:^3}│ │{np:<12}│ │{nm}│".into(), "".into());
612 let mut data = LineNumbersData::from_format_strings(&format, w.clone());
613
614 data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
615 assert_eq!(data.formatted_width(), MinusPlus::new(32, 0));
616
617 let format = MinusPlus::new("│{np:^3}│ │{nm:<12}│ │{np}│".into(), "".into());
618 let mut data = LineNumbersData::from_format_strings(&format, w);
619
620 data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
621 assert_eq!(data.formatted_width(), MinusPlus::new(32, 0));
622 }
623
624 fn _get_capture<'a>(i: usize, j: usize, caps: &'a [Captures]) -> &'a str {
625 caps[i].get(j).map_or("", |m| m.as_str())
626 }
627
628 #[test]
629 fn test_two_minus_lines() {
630 DeltaTest::with_args(&[
631 "--line-numbers",
632 "--line-numbers-left-format",
633 "{nm:^4}⋮",
634 "--line-numbers-right-format",
635 "{np:^4}│",
636 "--line-numbers-left-style",
637 "0 1",
638 "--line-numbers-minus-style",
639 "0 2",
640 "--line-numbers-right-style",
641 "0 3",
642 "--line-numbers-plus-style",
643 "0 4",
644 ])
645 .with_input(TWO_MINUS_LINES_DIFF)
646 .expect_after_header(
647 r#"
648 #indent_mark
649 1 ⋮ │a = 1
650 2 ⋮ │b = 23456"#,
651 );
652 }
653
654 #[test]
655 fn test_two_plus_lines() {
656 DeltaTest::with_args(&[
657 "--line-numbers",
658 "--line-numbers-left-format",
659 "{nm:^4}⋮",
660 "--line-numbers-right-format",
661 "{np:^4}│",
662 "--line-numbers-left-style",
663 "0 1",
664 "--line-numbers-minus-style",
665 "0 2",
666 "--line-numbers-right-style",
667 "0 3",
668 "--line-numbers-plus-style",
669 "0 4",
670 ])
671 .with_input(TWO_PLUS_LINES_DIFF)
672 .expect_after_header(
673 r#"
674 #indent_mark
675 ⋮ 1 │a = 1
676 ⋮ 2 │b = 234567"#,
677 );
678 }
679
680 #[test]
681 fn test_one_minus_one_plus_line() {
682 let config = make_config_from_args(&[
683 "--line-numbers",
684 "--line-numbers-left-format",
685 "{nm:^4}⋮",
686 "--line-numbers-right-format",
687 "{np:^4}│",
688 "--line-numbers-left-style",
689 "0 1",
690 "--line-numbers-minus-style",
691 "0 2",
692 "--line-numbers-right-style",
693 "0 3",
694 "--line-numbers-plus-style",
695 "0 4",
696 ]);
697 let output = run_delta(ONE_MINUS_ONE_PLUS_LINE_DIFF, &config);
698 let output = strip_ansi_codes(&output);
699 let mut lines = output.lines().skip(crate::config::HEADER_LEN);
700 assert_eq!(lines.next().unwrap(), " 1 ⋮ 1 │a = 1");
701 assert_eq!(lines.next().unwrap(), " 2 ⋮ │b = 2");
702 assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2");
703 }
704
705 #[test]
706 fn test_repeated_placeholder() {
707 let config = make_config_from_args(&[
708 "--line-numbers",
709 "--line-numbers-left-format",
710 "{nm:^4} {nm:^4}⋮",
711 "--line-numbers-right-format",
712 "{np:^4}│",
713 "--line-numbers-left-style",
714 "0 1",
715 "--line-numbers-minus-style",
716 "0 2",
717 "--line-numbers-right-style",
718 "0 3",
719 "--line-numbers-plus-style",
720 "0 4",
721 ]);
722 let output = run_delta(ONE_MINUS_ONE_PLUS_LINE_DIFF, &config);
723 let output = strip_ansi_codes(&output);
724 let mut lines = output.lines().skip(crate::config::HEADER_LEN);
725 assert_eq!(lines.next().unwrap(), " 1 1 ⋮ 1 │a = 1");
726 assert_eq!(lines.next().unwrap(), " 2 2 ⋮ │b = 2");
727 assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2");
728 }
729
730 #[test]
731 fn test_five_digit_line_number() {
732 let config = make_config_from_args(&["--line-numbers"]);
733 let output = run_delta(FIVE_DIGIT_LINE_NUMBER_DIFF, &config);
734 let output = strip_ansi_codes(&output);
735 let mut lines = output.lines().skip(crate::config::HEADER_LEN);
736 assert_eq!(lines.next().unwrap(), "10000⋮10000│a = 1");
737 assert_eq!(lines.next().unwrap(), "10001⋮ │b = 2");
738 assert_eq!(lines.next().unwrap(), " ⋮10001│bb = 2");
739 }
740
741 #[test]
742 fn test_unequal_digit_line_number() {
743 let config = make_config_from_args(&["--line-numbers"]);
744 let output = run_delta(UNEQUAL_DIGIT_DIFF, &config);
745 let output = strip_ansi_codes(&output);
746 let mut lines = output.lines().skip(crate::config::HEADER_LEN);
747 assert_eq!(lines.next().unwrap(), "10000⋮ 9999│a = 1");
748 assert_eq!(lines.next().unwrap(), "10001⋮ │b = 2");
749 assert_eq!(lines.next().unwrap(), " ⋮10000│bb = 2");
750 }
751
752 #[test]
753 fn test_color_only() {
754 let config = make_config_from_args(&["--line-numbers", "--color-only"]);
755 let output = run_delta(TWO_MINUS_LINES_DIFF, &config);
756 let mut lines = output.lines().skip(5);
757 let (line_1, line_2) = (lines.next().unwrap(), lines.next().unwrap());
758 assert_eq!(strip_ansi_codes(line_1), " 1 ⋮ │-a = 1");
759 assert_eq!(strip_ansi_codes(line_2), " 2 ⋮ │-b = 23456");
760 }
761
762 #[test]
763 fn test_hunk_header_style_is_omit() {
764 let config = make_config_from_args(&["--line-numbers", "--hunk-header-style", "omit"]);
765 let output = run_delta(TWO_LINE_DIFFS, &config);
766 let output = strip_ansi_codes(&output);
767 let mut lines = output.lines().skip(4);
768 assert_eq!(lines.next().unwrap(), " 1 ⋮ 1 │a = 1");
769 assert_eq!(lines.next().unwrap(), " 2 ⋮ │b = 2");
770 assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2");
771 assert_eq!(lines.next().unwrap(), "");
772 assert_eq!(lines.next().unwrap(), " 499⋮ 499│a = 3");
773 assert_eq!(lines.next().unwrap(), " 500⋮ │b = 4");
774 assert_eq!(lines.next().unwrap(), " ⋮ 500│bb = 4");
775 }
776
777 #[test]
778 fn test_line_numbers_continue_correctly() {
779 DeltaTest::with_args(&["--side-by-side", "--width", "44", "--line-fill-method=ansi"])
780 .with_input(DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF)
781 .expect_after_header(
782 r#"
783 │ 1 │abc │ 1 │abc
784 │ 2 │a = left side │ 2 │a = right side
785 │ 3 │xyz │ 3 │xyz"#,
786 );
787 }
788
789 #[test]
790 fn test_line_numbers_continue_correctly_after_wrapping() {
791 DeltaTest::with_args(&[
792 "--side-by-side",
793 "--width",
794 "32",
795 "--line-fill-method=ansi",
796 "--wrap-left-symbol",
797 "@",
798 "--wrap-right-symbol",
799 "@",
800 "--wrap-right-prefix-symbol",
801 ">",
802 ])
803 .with_input(DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF)
804 .expect_after_header(
805 r#"
806 │ 1 │abc │ 1 │abc
807 │ 2 │a = left @│ 2 │a = right@
808 │ │side │ │ side
809 │ 3 │xyz │ 3 │xyz"#,
810 );
811
812 let cfg = &[
813 "--side-by-side",
814 "--width",
815 "42",
816 "--line-fill-method=ansi",
817 "--wrap-left-symbol",
818 "@",
819 "--wrap-right-symbol",
820 "@",
821 "--wrap-right-prefix-symbol",
822 ">",
823 ];
824
825 DeltaTest::with_args(cfg)
826 .with_input(DIFF_WITH_LONGER_MINUS_1_CONTEXT)
827 .expect_after_header(
828 r#"
829 │ 1 │abc │ 1 │abc
830 │ 2 │a = one side │ 2 │a = one longer@
831 │ │ │ │ > side
832 │ 3 │xyz │ 3 │xyz"#,
833 );
834
835 DeltaTest::with_args(cfg)
836 .with_input(DIFF_WITH_LONGER_PLUS_1_CONTEXT)
837 .expect_after_header(
838 r#"
839 │ 1 │abc │ 1 │abc
840 │ 2 │a = one longer@│ 2 │a = one side
841 │ │ > side│ │
842 │ 3 │xyz │ 3 │xyz"#,
843 );
844
845 DeltaTest::with_args(cfg)
846 .with_input(DIFF_MISMATCH_LONGER_MINUS_1_CONTEXT)
847 .expect_after_header(
848 r#"
849 │ 1 │abc │ 1 │abc
850 │ 2 │a = left side @│ │
851 │ │which is longer│ │
852 │ │ │ 2 │a = other one
853 │ 3 │xyz │ 3 │xyz"#,
854 );
855
856 DeltaTest::with_args(cfg)
857 .with_input(DIFF_MISMATCH_LONGER_PLUS_1_CONTEXT)
858 .expect_after_header(
859 r#"
860 │ 1 │abc │ 1 │abc
861 │ 2 │a = other one │ │
862 │ │ │ 2 │a = right side@
863 │ │ │ │ which is long@
864 │ │ │ │er
865 │ 3 │xyz │ 3 │xyz"#,
866 );
867 }
868
869 pub const TWO_MINUS_LINES_DIFF: &str = "\
870 diff --git i/a.py w/a.py
871 index 223ca50..e69de29 100644
872 --- i/a.py
873 +++ w/a.py
874 @@ -1,2 +0,0 @@
875 -a = 1
876 -b = 23456
877 ";
878
879 pub const TWO_PLUS_LINES_DIFF: &str = "\
880 diff --git c/a.py i/a.py
881 new file mode 100644
882 index 0000000..223ca50
883 --- /dev/null
884 +++ i/a.py
885 @@ -0,0 +1,2 @@
886 +a = 1
887 +b = 234567
888 ";
889
890 pub const ONE_MINUS_ONE_PLUS_LINE_DIFF: &str = "\
891 diff --git i/a.py w/a.py
892 index 223ca50..367a6f6 100644
893 --- i/a.py
894 +++ w/a.py
895 @@ -1,2 +1,2 @@
896 a = 1
897 -b = 2
898 +bb = 2
899 ";
900
901 const TWO_LINE_DIFFS: &str = "\
902 diff --git i/a.py w/a.py
903 index 223ca50..367a6f6 100644
904 --- i/a.py
905 +++ w/a.py
906 @@ -1,2 +1,2 @@
907 a = 1
908 -b = 2
909 +bb = 2
910 @@ -499,2 +499,2 @@
911 a = 3
912 -b = 4
913 +bb = 4
914 ";
915
916 const FIVE_DIGIT_LINE_NUMBER_DIFF: &str = "\
917 diff --git i/a.py w/a.py
918 index 223ca50..367a6f6 100644
919 --- i/a.py
920 +++ w/a.py
921 @@ -10000,2 +10000,2 @@
922 a = 1
923 -b = 2
924 +bb = 2
925 ";
926
927 const UNEQUAL_DIGIT_DIFF: &str = "\
928 diff --git i/a.py w/a.py
929 index 223ca50..367a6f6 100644
930 --- i/a.py
931 +++ w/a.py
932 @@ -10000,2 +9999,2 @@
933 a = 1
934 -b = 2
935 +bb = 2
936 ";
937
938 const DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF: &str = "\
939 --- a/a.py
940 +++ b/b.py
941 @@ -1,3 +1,3 @@
942 abc
943 -a = left side
944 +a = right side
945 xyz";
946
947 const DIFF_WITH_LONGER_MINUS_1_CONTEXT: &str = "\
948 --- a/a.py
949 +++ b/b.py
950 @@ -1,3 +1,3 @@
951 abc
952 -a = one side
953 +a = one longer side
954 xyz";
955
956 const DIFF_WITH_LONGER_PLUS_1_CONTEXT: &str = "\
957 --- a/a.py
958 +++ b/b.py
959 @@ -1,3 +1,3 @@
960 abc
961 -a = one longer side
962 +a = one side
963 xyz";
964
965 const DIFF_MISMATCH_LONGER_MINUS_1_CONTEXT: &str = "\
966 --- a/a.py
967 +++ b/b.py
968 @@ -1,3 +1,3 @@
969 abc
970 -a = left side which is longer
971 +a = other one
972 xyz";
973
974 const DIFF_MISMATCH_LONGER_PLUS_1_CONTEXT: &str = "\
975 --- a/a.py
976 +++ b/b.py
977 @@ -1,3 +1,3 @@
978 abc
979 -a = other one
980 +a = right side which is longer
981 xyz";
982
983 pub const TWO_MINUS_LINES_UNICODE_DIFF: &str = "\
984 diff --git a/a.py b/a.py
985 index 8b0d958..e69de29 100644
986 --- a/a.txt
987 +++ b/b.txt
988 @@ -1,1 +0,0 @@
989 -一二三
990 ";
991 }