From 35a319b77f897744eec1155b736e9372c9c5575f Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Sat, 9 Oct 2021 13:58:55 +0100
Subject: [PATCH] patch 8.2.3489: ml_get error after search with range

Problem:    ml_get error after search with range.
Solution:   Limit the line number to the buffer line count.
---
 src/ex_docmd.c              |  6 ++++--
 src/testdir/test_search.vim | 14 ++++++++++++++
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/src/ex_docmd.c b/src/ex_docmd.c
index 76daf43..12554fa 100644
--- a/src/ex_docmd.c
+++ b/src/ex_docmd.c
@@ -3586,8 +3586,10 @@ get_address(
 
 		    // When '/' or '?' follows another address, start from
 		    // there.
-		    if (lnum != MAXLNUM)
-			curwin->w_cursor.lnum = lnum;
+		    if (lnum > 0 && lnum != MAXLNUM)
+			curwin->w_cursor.lnum =
+				lnum > curbuf->b_ml.ml_line_count
+					   ? curbuf->b_ml.ml_line_count : lnum;
 
 		    // Start a forward search at the end of the line (unless
 		    // before the first line).
diff --git a/src/testdir/test_search.vim b/src/testdir/test_search.vim
index 1876713..ac0881c 100644
--- a/src/testdir/test_search.vim
+++ b/src/testdir/test_search.vim
@@ -1366,3 +1366,17 @@ func Test_searchdecl()
 
   bwipe!
 endfunc
+
+func Test_search_with_invalid_range()
+  new
+  let lines =<< trim END
+    /\%.v
+    5/
+    c
+  END
+  call writefile(lines, 'Xrangesearch')
+  source Xrangesearch
+
+  bwipe!
+  call delete('Xrangesearch')
+endfunc
-- 
2.27.0

