diff --git a/src/ex_getln.c b/src/ex_getln.c
index e37ebe2c9..66d07abc2 100644
--- a/src/ex_getln.c
+++ b/src/ex_getln.c
@@ -394,6 +394,11 @@ do_incsearch_highlighting(int firstc, incsearch_state_T *is_state,
 	    search_first_line = ea.line1;
 	    search_last_line = ea.line2;
 	}
+	if (search_first_line > curbuf->b_ml.ml_line_count)
+	{
+	    search_first_line = curbuf->b_ml.ml_line_count;
+	    search_last_line = search_first_line;
+	}
     }
     else if (cmd[0] == 's' && cmd[1] != 'o')
     {
diff --git a/src/quickfix.c b/src/quickfix.c
index b899612d8..9b1922025 100644
--- a/src/quickfix.c
+++ b/src/quickfix.c
@@ -5217,7 +5217,7 @@ vgr_match_buflines(
 	char_u	    *fname,
 	buf_T	    *buf,
 	regmmatch_T *regmatch,
-	long	    tomatch,
+	long	    *tomatch,
 	int	    duplicate_name,
 	int	    flags)
 {
@@ -5225,7 +5225,7 @@ vgr_match_buflines(
     long	lnum;
     colnr_T	col;
 
-    for (lnum = 1; lnum <= buf->b_ml.ml_line_count && tomatch > 0; ++lnum)
+    for (lnum = 1; lnum <= buf->b_ml.ml_line_count && *tomatch > 0; ++lnum)
     {
 	col = 0;
 	while (vim_regexec_multi(regmatch, curwin, buf, lnum,
@@ -5255,7 +5255,7 @@ vgr_match_buflines(
 		break;
 	    }
 	    found_match = TRUE;
-	    if (--tomatch == 0)
+	    if (--*tomatch == 0)
 		break;
 	    if ((flags & VGR_GLOBAL) == 0
 		    || regmatch->endpos[0].lnum > 0)
@@ -5464,7 +5464,7 @@ ex_vimgrep(exarg_T *eap)
 	    // Try for a match in all lines of the buffer.
 	    // For ":1vimgrep" look for first match only.
 	    found_match = vgr_match_buflines(qi, fname, buf, &regmatch,
-		    tomatch, duplicate_name, flags);
+		    &tomatch, duplicate_name, flags);
 
 	    if (using_dummy)
 	    {
diff --git a/src/testdir/test_quickfix.vim b/src/testdir/test_quickfix.vim
index 01a950f34..b779e2806 100644
--- a/src/testdir/test_quickfix.vim
+++ b/src/testdir/test_quickfix.vim
@@ -2364,6 +2364,21 @@ func Test_vimgrep()
   call XvimgrepTests('l')
 endfunc
 
+" Test for incsearch highlighting of the :vimgrep pattern
+" This test used to cause "E315: ml_get: invalid lnum" errors.
+func Test_vimgrep_incsearch()
+  enew
+  set incsearch
+  call test_override("char_avail", 1)
+
+  call feedkeys(":2vimgrep assert test_quickfix.vim test_cdo.vim\<CR>", "ntx")
+  let l = getqflist()
+  call assert_equal(2, len(l))
+
+  call test_override("ALL", 0)
+  set noincsearch
+endfunc
+
 func XfreeTests(cchar)
   call s:setup_commands(a:cchar)
 
