patch 9.1.0617: Cursor moves beyond first line of folded end of buffer

Problem:  Cursor moves beyond start of a folded range at the end of a buffer.
Solution: Move cursor to start of fold when going beyond end of buffer.
          Check that cursor moved to detect FAIL in outer cursor function.
          (Luuk van Baal)

closes: #15344

Signed-off-by: Luuk van Baal <luukvbaal@gmail.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/edit.c b/src/edit.c
index e75a1cf..8a37a61 100644
--- a/src/edit.c
+++ b/src/edit.c
@@ -2849,7 +2849,6 @@
 	// count each sequence of folded lines as one logical line
 	while (n--)
 	{
-	    // Move to last line of fold, will fail if it's the end-of-file.
 	    if (hasFoldingWin(wp, lnum, NULL, &last, TRUE, NULL))
 		lnum = last + 1;
 	    else
@@ -2877,8 +2876,11 @@
 {
     linenr_T	lnum = curwin->w_cursor.lnum;
     linenr_T	line_count = curwin->w_buffer->b_ml.ml_line_count;
-    // This fails if the cursor is already in the last line or would move
-    // beyond the last line and '-' is in 'cpoptions'
+    // This fails if the cursor is already in the last (folded) line, or would
+    // move beyond the last line and '-' is in 'cpoptions'.
+#ifdef FEAT_FOLDING
+    hasFoldingWin(curwin, lnum, NULL, &lnum, TRUE, NULL);
+#endif
     if (n > 0
 	    && (lnum >= line_count
 		|| (lnum + n > line_count