patch 9.1.1159: $MYVIMDIR may not always be set

Problem:  $MYVIMDIR may not always be set (after 9.1.0718)
          (sandwm)
Solution: always set $MYVIMDIR to first item in runtimepath
          (except when using --clean), update it when changing &rtp

fixes: #16609
closes: #16709

Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/option.c b/src/option.c
index 60e1cf0..fa34546 100644
--- a/src/option.c
+++ b/src/option.c
@@ -8418,55 +8418,6 @@
 	    if (p != NULL)
 	    {
 		vim_setenv(envname, p);
-		if (vim_getenv((char_u *)"MYVIMDIR", &dofree) == NULL)
-		{
-		    size_t  usedlen = 0;
-		    size_t  len = 0;
-		    char_u  *fbuf = NULL;
-
-		    if (STRNCMP(gettail(fname), ".vimrc", 6) == 0)
-		    {
-			len = STRLEN(p) - 2;
-			p[len] = '/';
-		    }
-		    else if (STRNCMP(gettail(fname), ".gvimrc", 7) == 0)
-		    {
-			len = STRLEN(p);
-			char_u  *buf = alloc(len);
-			if (buf != NULL)
-			{
-			    mch_memmove(buf, fname, len - 7);
-			    mch_memmove(buf + len - 7, (char_u *)".vim/", 5);
-			    len -= 2;  // decrement len, so that we can set len+1 = NUL below
-			    vim_free(p);
-			    p = buf;
-			}
-		    }
-#ifdef MSWIN
-		    else if (STRNCMP(gettail(fname), "_vimrc", 6) == 0)
-		    {
-			len = STRLEN(p) + 4; // remove _vimrc, add vimfiles/
-			char_u  *buf = alloc(len);
-			if (buf != NULL)
-			{
-			    mch_memmove(buf, fname, len - 10);
-			    mch_memmove(buf + len - 10, (char_u *)"vimfiles\\", 9);
-			    len -= 2;  // decrement len, so that we can set len+1 = NUL below
-			    vim_free(p);
-			    p = buf;
-			}
-		    }
-#endif
-		    else
-			(void)modify_fname((char_u *)":h", FALSE, &usedlen, &p, &fbuf, &len);
-
-		    if (p != NULL)
-		    {
-			// keep the directory separator
-			p[len + 1] = NUL;
-			vim_setenv((char_u *)"MYVIMDIR", p);
-		    }
-		}
 		vim_free(p);
 	    }
 	}
diff --git a/src/optionstr.c b/src/optionstr.c
index f912e30..02806b6 100644
--- a/src/optionstr.c
+++ b/src/optionstr.c
@@ -135,6 +135,7 @@
 
 static int check_opt_strings(char_u *val, char **values, int list);
 static int opt_strings_flags(char_u *val, char **values, unsigned *flagp, int list);
+static void export_myvimdir(void);
 
 /*
  * After setting various option values: recompute variables that depend on
@@ -4652,10 +4653,13 @@
 	    setmouse();		    // in case 'mouse' changed
     }
 
-#if defined(FEAT_LUA) || defined(PROTO)
     if (varp == &p_rtp)
+    {
+	export_myvimdir();
+#if defined(FEAT_LUA) || defined(PROTO)
 	update_package_paths_in_lua();
 #endif
+    }
 
 #if defined(FEAT_LINEBREAK)
     // Changing Formatlistpattern when briopt includes the list setting:
@@ -4809,3 +4813,37 @@
 	vim_memset(shm_buf, 0, SHM_LEN);
     }
 }
+
+/*
+ * Export the environment variable $MYVIMDIR to the first item in runtimepath
+ */
+    static void
+export_myvimdir()
+{
+    int		dofree = FALSE;
+    char_u	*p;
+    char_u	*q = p_rtp;
+    char_u	*buf = alloc(MAXPATHL);
+
+    if (buf == NULL)
+	return;
+
+    (void)copy_option_part(&q, buf, MAXPATHL, ",");
+
+    p = vim_getenv((char_u *)"MYVIMDIR", &dofree);
+
+    if (p == NULL || STRCMP(p, buf) != 0)
+    {
+	add_pathsep(buf);
+#ifdef MSWIN
+	// normalize path separators
+	for (q = buf; *q != NUL; q++)
+	    if (*q == '/')
+		*q = '\\';
+#endif
+	vim_setenv((char_u *)"MYVIMDIR", buf);
+    }
+    if (dofree)
+	vim_free(p);
+    vim_free(buf);
+}
diff --git a/src/testdir/test_xdg.vim b/src/testdir/test_xdg.vim
index d4c1d22..15f82e2 100644
--- a/src/testdir/test_xdg.vim
+++ b/src/testdir/test_xdg.vim
@@ -150,6 +150,19 @@
   call system($'{vimcmd} -S Xscript')
   call assert_equal([], readfile('Xresult'))
 
+  " Test for $MYVIMDIR changes when updating runtimepath
+  let lines =<< trim END
+    let msg = $'HOME="{$HOME}", XDG_CONFIG_HOME="{$XDG_CONFIG_HOME}" rtp-prepend'
+    set rtp^=/non-existing
+    call assert_match('XfakeHOME/xdg/vim/vimrc', $MYVIMRC, msg)
+    call assert_match('/non-existing', $MYVIMDIR, msg)
+    call writefile(v:errors, 'Xresult')
+    quit
+  END
+  call writefile(lines, 'Xscript', 'D')
+  call system($'{vimcmd} -S Xscript')
+  call assert_equal([], readfile('Xresult'))
+
   call delete(rc4)
   unlet $XDG_CONFIG_HOME
 endfunc
@@ -267,13 +280,14 @@
   call delete(rc2)
 
   " Test for ~/.config/vim/gvimrc
+  " MYVIMDIR is only set to ~/config/.vim if ~/.config/vim/vimrc exists!
   let lines =<< trim END
     " Ignore the "failed to create input context" error.
     call test_ignore_error('E285')
     gui -f
     let msg = $'HOME="{$HOME}", ~="{expand("~")}"'
     call assert_match('Xhome/\.config/vim/gvimrc', $MYGVIMRC, msg)
-    call assert_match('Xhome/\.config/vim/', $MYVIMDIR, msg)
+    call assert_match('Xhome/\.vim/', $MYVIMDIR, msg)
     call filter(g:, {idx, _ -> idx =~ '^rc'})
     call assert_equal(#{rc_three: 'three', rc: '.config/vim/gvimrc'}, g:)
     call writefile(v:errors, 'Xresult')
@@ -286,6 +300,7 @@
   call delete(rc3)
 
   " Test for ~/xdg/vim/gvimrc
+  " MYVIMDIR is only set to ~/xdg/vim if ~/xdg/vim/vimrc exists!
   let $XDG_CONFIG_HOME=expand('~/xdg/')
   let lines =<< trim END
     " Ignore the "failed to create input context" error.
@@ -293,7 +308,7 @@
     gui -f
     let msg = $'HOME="{$HOME}", XDG_CONFIG_HOME="{$XDG_CONFIG_HOME}"'
     call assert_match('Xhome/xdg/vim/gvimrc', $MYGVIMRC, msg)
-    call assert_match('Xhome/xdg/vim/', $MYVIMDIR, msg)
+    call assert_match('Xhome/\.vim/', $MYVIMDIR, msg)
     call filter(g:, {idx, _ -> idx =~ '^rc'})
     call assert_equal(#{rc_four: 'four', rc: 'xdg/vim/gvimrc'}, g:)
     call writefile(v:errors, 'Xresult')
diff --git a/src/version.c b/src/version.c
index 3b61cdd..f29e1f3 100644
--- a/src/version.c
+++ b/src/version.c
@@ -705,6 +705,8 @@
 static int included_patches[] =
 {   /* Add new patch number below this line */
 /**/
+    1159,
+/**/
     1158,
 /**/
     1157,