From 395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Sat, 14 May 2022 21:29:44 +0100
Subject: [PATCH] patch 8.2.4956: reading past end of line with "gf" in Visual
 block mode

Problem:    Reading past end of line with "gf" in Visual block mode.
Solution:   Do not include the NUL in the length.
---
 src/normal.c            | 13 ++++++++++---
 src/testdir/test_gf.vim | 15 +++++++++++++++
 2 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/src/normal.c b/src/normal.c
index d33a56a..898c836 100644
--- a/src/normal.c
+++ b/src/normal.c
@@ -3791,9 +3791,16 @@ get_visual_text(
 	}
 	if (**pp == NUL)
 	    *lenp = 0;
-	if (has_mbyte && *lenp > 0)
-	    // Correct the length to include all bytes of the last character.
-	    *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
+	if (*lenp > 0)
+	{
+	    if (has_mbyte)
+		// Correct the length to include all bytes of the last
+		// character.
+		*lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
+	    else if ((*pp)[*lenp - 1] == NUL)
+		// Do not include a trailing NUL.
+		*lenp -= 1;
+	}
     }
     reset_VIsual_and_resel();
     return OK;
diff --git a/src/testdir/test_gf.vim b/src/testdir/test_gf.vim
index d301874..596f3e8 100644
--- a/src/testdir/test_gf.vim
+++ b/src/testdir/test_gf.vim
@@ -106,6 +106,21 @@ func Test_gf_visual()
   call setline(1, 'XXXtest_gf_visualXXX')
   set hidden
 
+  " do not include the NUL at the end 
+  call writefile(['x'], 'X')
+  let save_enc = &enc
+  for enc in ['latin1', 'utf-8']
+    exe "set enc=" .. enc
+    new
+    call setline(1, 'X')
+    set nomodified
+    exe "normal \<C-V>$gf"
+    call assert_equal('X', bufname())
+    bwipe!
+  endfor
+  let &enc = save_enc
+  call delete('X')
+
   " Visually select Xtest_gf_visual and use gf to go to that file
   norm! ttvtXgf
   call assert_equal('Xtest_gf_visual', bufname('%'))
-- 
1.8.3.1

