patch 9.1.0883: message history cleanup is missing some tests

Problem:  message history cleanup is missing some tests
Solution: Add tests, refactor common code into did_set_msghistory()
          (Shougo Matsushita)

closes: #16078

Co-authored-by: zeertzjq <zeertzjq@outlook.com>
Co-authored-by: Milly <milly.ca@gmail.com>
Signed-off-by: Shougo Matsushita <Shougo.Matsu@gmail.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/message.c b/src/message.c
index 95bd726..15eaaae 100644
--- a/src/message.c
+++ b/src/message.c
@@ -1011,10 +1011,6 @@
     if (msg_hist_off || msg_silent != 0)
 	return;
 
-    // Don't let the message history get too big
-    while (msg_hist_len > p_mhi)
-	(void)delete_first_msg();
-
     // allocate an entry and add the message at the end of the history
     p = ALLOC_ONE(struct msg_hist);
     if (p == NULL)
@@ -1039,6 +1035,8 @@
     if (first_msg_hist == NULL)
 	first_msg_hist = last_msg_hist;
     ++msg_hist_len;
+
+    check_msg_hist();
 }
 
 /*
@@ -1062,6 +1060,14 @@
     return OK;
 }
 
+    void
+check_msg_hist(void)
+{
+    // Don't let the message history get too big
+    while (msg_hist_len > 0 && msg_hist_len > p_mhi)
+	(void)delete_first_msg();
+}
+
 /*
  * ":messages" command.
  */