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/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);
+}