Commit 05e5d6a38 (vi: Ensure that the edit buffer ends in a newline)
fixed the initial opening of files without a terminating newline. This
commit also fixes it for the `:r` command.

function                                             old     new   delta
file_insert                                          392     431     +39
init_text_buffer                                     162     156      -6

Signed-off-by: Petja Patjas <[email protected]>
---
 editors/vi.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/editors/vi.c b/editors/vi.c
index 3382df0bf..6988e118b 100644
--- a/editors/vi.c
+++ b/editors/vi.c
@@ -556,6 +556,7 @@ static int crashme = 0;
 
 static void show_status_line(void);    // put a message on the bottom line
 static void status_line_bold(const char *, ...);
+static uintptr_t stupid_insert(char *, char);
 
 static void show_help(void)
 {
@@ -2020,6 +2021,11 @@ static int file_insert(const char *fn, char *p, int 
initial)
                        text_hole_delete(p + cnt, p + size - 1, NO_UNDO);
                        status_line_bold("can't read '%s'", fn);
                }
+               // If the data didn't end in a newline, pretend that it did
+               if (cnt > 0 && *(p + cnt - 1) != '\n') {
+                       p += stupid_insert(p + cnt, '\n');
+                       cnt++;
+               }
 # if ENABLE_FEATURE_VI_UNDO
                // Use `p - 1` to go to the previous line on undo.
                // Using `p - 1` when `initial == 1` would be incorrect,
@@ -2321,9 +2327,8 @@ static int init_text_buffer(char *fn)
 
        update_filename(fn);
        rc = file_insert(fn, text, 1);
-       if (rc <= 0 || *(end - 1) != '\n') {
-               // file doesn't exist or doesn't end in a newline.
-               // insert a newline to the end
+       if (rc <= 0) {
+               // file doesn't exist or is empty, start empty buffer
                char_insert(end, '\n', NO_UNDO);
        }
 
-- 
2.51.0

_______________________________________________
busybox mailing list
[email protected]
https://lists.busybox.net/mailman/listinfo/busybox

Reply via email to