Skip to content

Commit

Permalink
ed: simplify edInsert() (#550)
Browse files Browse the repository at this point in the history
* Rewrite edInsert() without @tmplines2 and $tmp_chars
* Use splice() to add @tmp_lines into @lines directly
* Use scalar(@tmp_lines) instead of $tmp_chars to indicate whether @lines needs to be updated (early return added)
* Input address normally counts from 1 so handles the placeholder at $lines[0]
* Input address 0 is allowed for 'a' and 'i' commands, so be careful not to move $lines[0] placeholder
* In edEdit() be more careful to reset @lines if no file is being read; the array needs to have one element
* test1: start ed on empty buffer and run '0i' or '0a', enter text terminated with '.' line
* test2: start ed with text file with 9 lines and run '9a'; text is appended starting from line 10
* test3: apply an ed patch containing 'a' commands (below)

%perl diff -e ed.new ed > patch.ed
%echo w >> patch.ed 
%perl ed ed.new < patch.ed 
30368
29383
%perl sum -a md5 ed ed.new 
e5748aef0ba835feb1daba4a99778b9c  ed
e5748aef0ba835feb1daba4a99778b9c  ed.new
  • Loading branch information
mknos committed Apr 12, 2024
1 parent b2d07d5 commit 8c09f7e
Showing 1 changed file with 10 additions and 18 deletions.
28 changes: 10 additions & 18 deletions bin/ed
Expand Up @@ -693,6 +693,7 @@ sub edEdit {
$filename = $RememberedFilename;
} else {
$CurrentLineNum = 0;
@lines = (0);
return 1;
}

Expand Down Expand Up @@ -761,7 +762,7 @@ sub edEdit {

sub edInsert {
my($Mode) = @_;
my(@tmp_lines,@tmp_lines2,$tmp_chars);
my(@tmp_lines);

if (defined($adrs[1])) {
edWarn(E_ADDREXT);
Expand All @@ -776,31 +777,22 @@ sub edInsert {
}

# suck the text into a temp array

@tmp_lines = ();
$tmp_chars = 0;

while (<>) {
last if (/^\.$/);
push(@tmp_lines,$_);
$tmp_chars += length;
}
if (scalar(@tmp_lines) == 0) {
return 1;
}

my $src = $adrs[0];
$src-- if ($src && $Mode == $INSERT_MODE);
$src++ if ($src && $Mode == $APPEND_MODE);
$src++ if $src == 0; # 0a == 0i == 1i

shift @lines; # get rid of 0 line
@tmp_lines2 = splice @lines, 0, $src;
unshift @lines, @tmp_lines;
unshift @lines, @tmp_lines2;
$CurrentLineNum = $src + scalar(@tmp_lines);
unshift @lines, undef; # put 0 line back

if ($tmp_chars) {
$NeedToSave = 1;
$UserHasBeenWarned = 0;
}
splice @lines, $src, 0, @tmp_lines;

$NeedToSave = 1;
$UserHasBeenWarned = 0;
return 1;
}

Expand Down

0 comments on commit 8c09f7e

Please sign in to comment.