From 8d02ce1ed75d008c34a5c9aaa51b67cbb9d33baa Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Tue, 25 Jan 2022 18:24:00 +0000
Subject: [PATCH] patch 8.2.4217: illegal memory access when undo makes Visual
 area invalid

Problem:    Illegal memory access when undo makes Visual area invalid.
Solution:   Correct the Visual area after undo.
---
 src/testdir/test_visual.vim | 15 +++++++++++++++
 src/undo.c                  |  2 ++
 2 files changed, 17 insertions(+)

diff --git a/src/testdir/test_visual.vim b/src/testdir/test_visual.vim
index dbc28eb..cf7e351 100644
--- a/src/testdir/test_visual.vim
+++ b/src/testdir/test_visual.vim
@@ -670,6 +670,21 @@ func Test_visual_ex_copy_line()
   bwipe!
 endfunc
 
+" This was leaving the end of the Visual area beyond the end of a line.
+" Set 'undolevels' to start a new undo block.
+func Test_visual_undo_deletes_last_line()
+  new
+  call setline(1, ["aaa", "ccc", "dyd"])
+  set undolevels=100
+  exe "normal obbbbbbbbbxbb\<Esc>"
+  set undolevels=100
+  /y
+  exe "normal ggvjfxO"
+  undo
+  normal gNU
+  bwipe!
+endfunc
+
 
   " linewise select mode: delete middle two lines
   call deletebufline('', 1, '$')
diff --git a/src/undo.c b/src/undo.c
index 54a6e1c..706dee9 100644
--- a/src/undo.c
+++ b/src/undo.c
@@ -2985,6 +2985,8 @@ u_undo_end(
 	}
     }
 #endif
+    if (VIsual_active)
+	check_pos(curbuf, &VIsual);
 
     smsg_attr_keep(0, _("%ld %s; %s #%ld  %s"),
 	    u_oldcount < 0 ? -u_oldcount : u_oldcount,
-- 
1.8.3.1

