From 0b9ee42b57c715bf92e6568653c2336453992076 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sat, 12 Jul 2025 12:47:47 -0700 Subject: [PATCH] insert-file-contents END enforcement MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * src/fileio.c (Finsert_file_contents): When matching text at buffer start, don’t go past END if specified. (cherry picked from commit 535ab2d116c259820e18380336913abc57ac0376) --- src/fileio.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index 9c06fd1d25a..ae6fbb7dc7a 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -4437,11 +4437,27 @@ by calling `format-decode', which see. */) match the text at the beginning of the buffer. */ while (true) { - int nread = emacs_fd_read (fd, read_buf, sizeof read_buf); + off_t bytes_to_read = sizeof read_buf; + off_t curpos = beg_offset + (same_at_start - BEGV_BYTE); + bytes_to_read = min (bytes_to_read, end_offset - curpos); + ptrdiff_t nread = (bytes_to_read <= 0 + ? 0 + : emacs_fd_read (fd, read_buf, bytes_to_read)); if (nread < 0) report_file_error ("Read error", orig_filename); else if (nread == 0) - break; + { + file_size_hint = curpos; + + /* Data inserted from the file match the buffer's leading bytes, + so there's no need to replace anything. */ + emacs_fd_close (fd); + clear_unwind_protect (fd_index); + + /* Truncate the buffer to the size of the file. */ + del_range_1 (same_at_start, same_at_end, 0, 0); + goto handled; + } if (CODING_REQUIRE_DETECTION (&coding)) { @@ -4468,17 +4484,6 @@ by calling `format-decode', which see. */) if (bufpos != nread) break; } - /* If the file matches the buffer completely, - there's no need to replace anything. */ - if (same_at_start - BEGV_BYTE == end_offset - beg_offset) - { - emacs_fd_close (fd); - clear_unwind_protect (fd_index); - - /* Truncate the buffer to the size of the file. */ - del_range_1 (same_at_start, same_at_end, 0, 0); - goto handled; - } /* Count how many chars at the end of the file match the text at the end of the buffer. But, if we have -- 2.39.5