From 94f3192b03ed27474db80b4d3a409e107140738b Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Thu, 30 Dec 2021 15:29:18 +0000
Subject: [PATCH] patch 8.2.3950: going beyond the end of the line with /\%V
Conflict:NA
Reference:https://github.com/vim/vim/commit/94f3192b03ed27474db80b4d3a409e107140738b

Problem:    Going beyond the end of the line with /\%V.
Solution:   Check for valid column in getvcol().

---
 src/charset.c                     | 13 +++++++++----
 src/testdir/test_regexp_latin.vim |  8 ++++++++
 2 files changed, 17 insertions(+), 4 deletions(-)

diff --git a/src/charset.c b/src/charset.c
index 7505fea..a768c17 100644
--- a/src/charset.c
+++ b/src/charset.c
@@ -1226,10 +1226,15 @@ getvcol(
 	posptr = NULL;  // continue until the NUL
     else
     {
-	// Special check for an empty line, which can happen on exit, when
-	// ml_get_buf() always returns an empty string.
-	if (*ptr == NUL)
-	    pos->col = 0;
+	colnr_T i;
+
+	// In a few cases the position can be beyond the end of the line.
+	for (i = 0; i < pos->col; ++i)
+	    if (ptr[i] == NUL)
+	    {
+		pos->col = i;
+		break;
+	    }
 	posptr = ptr + pos->col;
 	if (has_mbyte)
 	    // always start on the first byte
diff --git a/src/testdir/test_regexp_latin.vim b/src/testdir/test_regexp_latin.vim
index 3168edc..4f52bac 100644
--- a/src/testdir/test_regexp_latin.vim
+++ b/src/testdir/test_regexp_latin.vim
@@ -149,3 +149,11 @@ func Test_using_mark_position()
   call assert_fails("s/\\%')", 'E486:')
   bwipe!
 endfunc
+
+func Test_using_invalid_visual_position()
+  " this was going beyond the end of the line
+  new
+  exe "norm 0o000\<Esc>0\<C-V>$s0"
+  /\%V
+  bwipe!
+endfunc
-- 
2.27.0

