From 6f185d30228e8c982bb91ff62ce45c5776f197db Mon Sep 17 00:00:00 2001
From: Benno Schulenberg <bensberg@justemail.net>
Date: Sun, 17 Apr 2016 13:02:04 +0200
Subject: [PATCH] inserting: strip a carriage return before copying the line

Also, store the input character earlier, so we don't have to use len - 1.
Furthermore, len increments in steps of 1, so it cannot pass the value of
bufx unnoticed, so use a comparison for equality.
---
 src/files.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/src/files.c b/src/files.c
index e59a038a..1687a57f 100644
--- a/src/files.c
+++ b/src/files.c
@@ -689,15 +689,14 @@ filestruct *read_line(char *buf, size_t buf_len, filestruct *prevnode)
 
     assert(openfile->fileage != NULL && strlen(buf) == buf_len);
 
-    freshline->data = mallocstrcpy(NULL, buf);
-
 #ifndef NANO_TINY
-    /* If it's a DOS file ("\r\n"), and file conversion isn't disabled,
-     * strip the '\r' part from the data. */
-    if (!ISSET(NO_CONVERT) && buf_len > 0 && buf[buf_len - 1] == '\r')
-	freshline->data[buf_len - 1] = '\0';
+    /* If file conversion isn't disabled, strip a '\r' from the line. */
+    if (buf_len > 0 && buf[buf_len - 1] == '\r' && !ISSET(NO_CONVERT))
+	buf[buf_len - 1] = '\0';
 #endif
 
+    freshline->data = mallocstrcpy(NULL, buf);
+
 #ifndef DISABLE_COLOR
     freshline->multidata = NULL;
 #endif
@@ -803,18 +802,19 @@ void read_file(FILE *f, int fd, const char *filename, bool undoable, bool checkw
 	    len = 1;
 #endif
 	} else {
+	    /* Store the character. */
+	    buf[len] = input;
+
 	    /* Keep track of the total length of the line.  It might have
 	     * nulls in it, so we can't just use strlen() later. */
 	    len++;
 
 	    /* If needed, increase the buffer size, MAX_BUF_SIZE characters at
 	     * a time.  Don't bother decreasing it; it is freed at the end. */
-	    if (len >= bufx) {
+	    if (len == bufx) {
 		bufx += MAX_BUF_SIZE;
 		buf = charealloc(buf, bufx);
 	    }
-
-	    buf[len - 1] = input;
 	}
     }
 
-- 
GitLab