From 6046aded8da002b08d380db29de2ba0268b6616e Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Wed, 22 Jun 2022 13:51:54 +0100
Subject: [PATCH] patch 8.2.5148: invalid memory access when using expression
 on command line

Problem:    Invalid memory access when using an expression on the command line.
Solution:   Make sure the position does not go negative.
---
 src/ex_getln.c               | 6 ++++--
 src/testdir/test_cmdline.vim | 5 +++++
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/ex_getln.c b/src/ex_getln.c
index aa01f80..887b47d 100644
--- a/src/ex_getln.c
+++ b/src/ex_getln.c
@@ -820,6 +820,7 @@ getcmdline_int(
     cmdline_info_T save_ccline;
     int		did_save_ccline = FALSE;
     int		cmdline_type;
+    int		save_new_cmdpos;
 
     // one recursion level deeper
     ++depth;
@@ -1757,6 +1758,7 @@ getcmdline_int(
 		goto returncmd;		// back to cmd mode
 
 	case Ctrl_R:			// insert register
+		save_new_cmdpos = new_cmdpos;
 #ifdef USE_ON_FLY_SCROLL
 		dont_scroll = TRUE;	// disallow scrolling here
 #endif
@@ -1774,8 +1776,6 @@ getcmdline_int(
 #ifdef FEAT_EVAL
 		/*
 		 * Insert the result of an expression.
-		 * Need to save the current command line, to be able to enter
-		 * a new one...
 		 */
 		new_cmdpos = -1;
 		if (c == '=')
@@ -1816,6 +1816,8 @@ getcmdline_int(
 		    }
 #endif
 		}
+		new_cmdpos = save_new_cmdpos;
+
 		redrawcmd();
 		goto cmdline_changed;
 
diff --git a/src/testdir/test_cmdline.vim b/src/testdir/test_cmdline.vim
index 4665c75..2588a0d 100644
--- a/src/testdir/test_cmdline.vim
+++ b/src/testdir/test_cmdline.vim
@@ -925,4 +925,9 @@ func Test_recursive_register()
   call assert_equal('yes', caught)
 endfunc
 
+" This was making the insert position negative
+func Test_cmdline_expr_register()
+  exe "sil! norm! ?\<C-\>e0\<C-R>0\<Esc>?\<C-\>e0\<CR>"
+endfunc
+
 " vim: shiftwidth=2 sts=2 expandtab
-- 
1.8.3.1

