From f2904bd699351c52d1c27c25998d4942bc2edb14 Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Tue, 20 Feb 2024 10:06:43 +0800 Subject: [PATCH] ed: edInsert() mostly duplicate code * edInsert() handles Append "a" command and Insert "i" command * The special case for address 0 can be removed; the code with tmp_lines2 is general enough to handle this, i.e. for address 0, tmp_lines will be added at start of buffer and tmp_lines2 will be empty * In insert mode the target address is the addressed line; decrement is needed for conversion to correct array index * test1: "0a", "0i" and "1i" --> add input to start of buffer * test2: "1a" and "2i" --> add input after buffer line 1, and at buffer line 2 (equivalent) --- bin/ed | 40 +++++++++------------------------------- 1 file changed, 9 insertions(+), 31 deletions(-) diff --git a/bin/ed b/bin/ed index e7bb26e4..e184bec4 100755 --- a/bin/ed +++ b/bin/ed @@ -780,37 +780,15 @@ sub edInsert { $tmp_chars += length; } - # now that we've got it, figure out what to do with it - - if ($Mode == $INSERT_MODE) { - - shift @lines; # get rid of 0 line - if ($adrs[0] == 0 || $adrs[0] == 1) { - unshift(@lines,@tmp_lines); - $CurrentLineNum = scalar(@tmp_lines); - } else { - @tmp_lines2 = splice(@lines,0,$adrs[0]-1); - unshift(@lines,@tmp_lines); - unshift(@lines,@tmp_lines2); - $CurrentLineNum = $adrs[0] + scalar(@tmp_lines) - 1; - } - unshift @lines, undef; # put 0 line back - - } elsif ($Mode == $APPEND_MODE) { - - shift(@lines); # get rid of 0 line - if ($adrs[0] == 0) { - unshift(@lines,@tmp_lines); - $CurrentLineNum = scalar(@tmp_lines); - } else { - @tmp_lines2 = splice(@lines,0,$adrs[0]); - unshift(@lines,@tmp_lines); - unshift(@lines,@tmp_lines2); - $CurrentLineNum = $adrs[0] + scalar(@tmp_lines); - } - unshift(@lines,undef); # put 0 line back - - } + my $src = $adrs[0]; + $src-- if ($src && $Mode == $INSERT_MODE); + + 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;