Skip to content

Commit 0ecebca

Browse files
authored
ed: generic search function (#808)
* Reduce duplicated code by rolling edSearchForward() and edSearchBackward() into one function * While here, remove a comment about GNU ed setting current line for '=' command... "/pattern/=" in GNU ed does not set current line
1 parent 87636ea commit 0ecebca

File tree

1 file changed

+10
-50
lines changed

1 file changed

+10
-50
lines changed

bin/ed

Lines changed: 10 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,6 @@ sub edPrintLineNum {
812812
edWarn(E_ARGEXT);
813813
return;
814814
}
815-
816815
my $adr = $adrs[1];
817816
if (!defined($adr)) {
818817
$adr = $adrs[0];
@@ -821,9 +820,6 @@ sub edPrintLineNum {
821820
$adr = maxline();
822821
}
823822
print "$adr\n";
824-
825-
# v7 docs say this does not affect current line. GNU ed sets the line.
826-
# We go with the v7 docs.
827823
}
828824

829825
#
@@ -982,11 +978,7 @@ sub getAddr {
982978
return A_NOPAT unless defined $SearchPat;
983979
$re = $SearchPat;
984980
}
985-
if ($delim eq '/') {
986-
$n = edSearchForward($re);
987-
} else {
988-
$n = edSearchBackward($re);
989-
}
981+
$n = edSearch($re, $delim eq '?');
990982
$n = A_NOMATCH unless $n;
991983
}
992984
return $n;
@@ -1009,50 +1001,18 @@ sub getRe {
10091001
return $re;
10101002
}
10111003

1012-
#
1013-
# Search forward for a pattern...wrap if not found
1014-
#
1015-
# Inputs:
1016-
# pattern - via argument
1017-
# CurrentLineNum - global
1018-
# lines - global
1019-
#
1020-
# Return:
1021-
# 0 - not found
1022-
# >0 - line where first found
1023-
#
1024-
1025-
sub edSearchForward {
1026-
my($pattern) = @_;
1004+
sub edSearch {
1005+
my ($pattern, $backward) = @_;
10271006

10281007
$SearchPat = $pattern;
1029-
for my $line (($CurrentLineNum + 1) .. maxline(), 1 .. $CurrentLineNum) {
1030-
if ($lines[$line] =~ /$pattern/) {
1031-
return $line;
1032-
}
1008+
my $cur = $CurrentLineNum;
1009+
my @idx;
1010+
if ($backward) {
1011+
@idx = reverse ($cur .. maxline(), 1 .. ($cur - 1));
1012+
} else {
1013+
@idx = (($cur + 1) .. maxline(), 1 .. $cur);
10331014
}
1034-
return 0;
1035-
}
1036-
1037-
#
1038-
# Search backward for a pattern...wrap if not found
1039-
#
1040-
# Inputs:
1041-
# pattern - via argument
1042-
# CurrentLineNum - global
1043-
# lines - global
1044-
#
1045-
# Return:
1046-
# 0 - not found
1047-
# >0 - line where first found
1048-
#
1049-
1050-
sub edSearchBackward {
1051-
my($pattern) = @_;
1052-
1053-
$SearchPat = $pattern;
1054-
my @idx = ($CurrentLineNum .. maxline(), 1 .. ($CurrentLineNum - 1));
1055-
foreach my $line (reverse @idx) {
1015+
foreach my $line (@idx) {
10561016
if ($lines[$line] =~ /$pattern/) {
10571017
return $line;
10581018
}

0 commit comments

Comments
 (0)