Skip to content

Commit 022a86a

Browse files
Attempt to calculate context lines for #460
1 parent e2d91b2 commit 022a86a

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

diff-so-fancy

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ my $use_unicode_dash_for_ruler = git_config_boolean("diff-so-fancy.useUnicodeRul
2626
my $ruler_width = git_config("diff-so-fancy.rulerWidth", undef);
2727
my $git_strip_prefix = git_config_boolean("diff.noprefix","false");
2828
my $has_stdin = has_stdin();
29+
my $CONTEXT_LINES = undef; # Number of lines of context diff used
2930

3031
my $ansi_regex = qr/\e\[([0-9]{1,3}(;[0-9]{1,3}){0,10})[mK]/;
3132
my $ansi_color_regex = qr/(${ansi_regex})?/;
@@ -139,6 +140,11 @@ do_dsf_stuff(\@lines);
139140
sub do_dsf_stuff {
140141
my $input = shift();
141142

143+
# Calculate the context lines the first time
144+
if (!defined $CONTEXT_LINES) {
145+
$CONTEXT_LINES = calculate_context_lines(@lines);
146+
}
147+
142148
#print STDERR "START -------------------------------------------------\n";
143149
#print STDERR join("",@$input);
144150
#print STDERR "END ---------------------------------------------------\n";
@@ -534,16 +540,14 @@ sub start_line_calc {
534540
return 1;
535541
}
536542

537-
# Git defaults to three lines of context
538-
my $default_context_lines = 3;
539543
# Three lines on either side, and the line itself = 7
540-
my $expected_context = ($default_context_lines * 2 + 1);
544+
my $expected_context = ($CONTEXT_LINES * 2 + 1);
541545

542546
# The first three lines
543547
if ($line_num == 1 && $diff_context < $expected_context) {
544-
$ret = $diff_context - $default_context_lines;
548+
$ret = $diff_context - $CONTEXT_LINES;
545549
} else {
546-
$ret = $line_num + $default_context_lines;
550+
$ret = $line_num + $CONTEXT_LINES;
547551
}
548552

549553
if ($ret < 1) {
@@ -1081,6 +1085,27 @@ sub debug_log {
10811085
return 1;
10821086
}
10831087

1088+
sub calculate_context_lines {
1089+
my @lines = @_;
1090+
my $count = 0;
1091+
my $hunk_line = 0;
1092+
1093+
foreach my $line (@lines) {
1094+
if ($line =~ /^${ansi_color_regex}(@@@* .+? @@@*)(.*)/) {
1095+
$hunk_line = $count;
1096+
} elsif ($hunk_line && $line =~ /^${ansi_color_regex}[+-]/) {
1097+
my $diff = $count - $hunk_line - 1;
1098+
#print "Hunk: $hunk_line, ChangedLine: $count ($diff context)\n";
1099+
return $diff;
1100+
}
1101+
1102+
$count++;
1103+
};
1104+
1105+
# If for some reason we can't figure it out, assume 3
1106+
return 3;
1107+
}
1108+
10841109
# Borrowed from: https://www.perturb.org/display/1097_Perl_detect_if_a_module_is_installed_before_using_it.html
10851110
sub AUTOLOAD {
10861111
our $AUTOLOAD; # keep 'use strict' happy

0 commit comments

Comments
 (0)