From e56b8c2e88c8c5444f66634dbe3c511a5f37a3d6 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 29 Aug 2021 00:28:31 +0200 Subject: incdec.pm: Always return start position when backwards is on Previously, if backwards was on and point was before the first number on the line, the start position would be set to 0 (when it gets set to `$previous_match_start`). This means the start position wouldn't get set to the actual start position of the first number. We want the actual start position of that number so we can move point only if it's on or after the current number when changing between negative and positive numbers. Also, the `\G` pattern didn't work on some of the `sed` tests because it matches a number at that position. Since the position wasn't one that was followed by the number, the regex didn't match a number, and the increment didn't happen. We can get rid of the special handling for start position at 0 now. --- incdec.pm | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'incdec.pm') diff --git a/incdec.pm b/incdec.pm index a1e88a6..4508068 100644 --- a/incdec.pm +++ b/incdec.pm @@ -28,7 +28,9 @@ sub incdec { $is_backward ||= 0; my $start_position = 0; + # my $previous_match_start = $point_position; my $previous_match_start = 0; + my $i = 0; while ($line =~ /(-?\d+)/g) { if ($is_backward) { # Set start position to the current match start. This gives us the @@ -36,6 +38,12 @@ sub incdec { # line. $start_position = $-[0]; + # Keep the start position of the first number if point is before + # the first number. + if ($i == 0 && $point_position < $-[0]) { + last; + } + # If point is not at the end, set start position to the number # closest to the point position. if ($point_position < $-[0]) { @@ -45,6 +53,7 @@ sub incdec { } $previous_match_start = $-[0]; + $i++; } else { if ($point_position < $+[0]) { @@ -56,13 +65,13 @@ sub incdec { } # Using `\G` when `pos` is 0 seems to cause occasional missed substitutions. - if ($start_position > 0) { + # if ($start_position > 0) { pos($line) = $start_position; $line =~ s/\G(-?\d+)/$1 + $increment_by/e; - } - else { - $line =~ s/(-?\d+)/$1 + $increment_by/e; - } + # } + # else { + # $line =~ s/(-?\d+)/$1 + $increment_by/e; + # } return ($line, $start_position); } -- cgit v1.2.3