Subject: bug#52237: 29.0.50; [PATCH 2] Doubled separators in context-menu-mode

From: Jim Porter <[email-masked]>
Date: Thu, 2 Dec 2021 20:46:28 -0800

On 12/2/2021 9:44 AM, Juri Linkov wrote:
>>> I've only tested this on Emacs 29 so far, but it may occur on Emacs 28
>>> as well.
>>
>> Thanks; applied to Emacs 29.
> 
> Why not to Emacs 28?

I got a chance to check this under Emacs 28, and the bug exists there 
too, so it'd be nice to backport.

>>> Also, I noticed that separators can appear at the beginning
>>> and/or end of the context menu. Should they be removed too?
>>
>> Hm...  I think that might make sense, but I'm not sure.  Anybody got an
>> opinion?
> 
> Removing leading/trailing separators would be nice too.

Ok, here's a patch to do it. There might be a better way to do this, but 
it should work reliably.

Note: this patch doesn't fix the duplicated separators in the help-mode 
context menu. I haven't had time to look into the right way to fix that 
yet (there may be other mode-specific context menu functions that have 
this bug too).
From c76d753b46199da04863f19f75faf100d8e9e773 Mon Sep 17 00:00:00 2001
From: Jim Porter <[email-masked]>
Date: Thu, 2 Dec 2021 20:39:33 -0800
Subject: [PATCH] Remove separators at the beginning and end of the context
 menu

* lisp/mouse.el (context-menu-map): Remove beginning/end seperators.
---
 lisp/mouse.el | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/lisp/mouse.el b/lisp/mouse.el
index ec43aecdd0..b5ca80a446 100644
--- a/lisp/mouse.el
+++ b/lisp/mouse.el
@@ -327,12 +327,21 @@ context-menu-map
                           (setq menu (funcall fun menu click))
                           nil)))
 
-    ;; Remove duplicate separators
-    (let ((l menu))
-      (while (consp l)
-        (if (and (equal (cdr-safe (car l)) menu-bar-separator)
-                 (equal (cdr-safe (cadr l)) menu-bar-separator))
+    ;; Remove duplicate separators as well as ones at the beginning or
+    ;; end of the menu.
+    (let ((l menu) saw-first-item)
+      (while (consp (cdr l))
+        ;; If the next item is a separator, remove it if 1) we haven't
+        ;; seen any other items yet, or 2) it's followed by either
+        ;; another separator or the end of the list.
+        (if (and (equal (cdr-safe (cadr l)) menu-bar-separator)
+                 (or (not saw-first-item)
+                     (null (caddr l))
+                     (equal (cdr-safe (caddr l)) menu-bar-separator)))
             (setcdr l (cddr l))
+          ;; The "first item" is any cons cell; this excludes the
+          ;; `keymap' symbol and the menu name.
+          (when (consp (cadr l)) (setq saw-first-item t))
           (setq l (cdr l)))))
 
     (when (functionp context-menu-filter-function)
-- 
2.25.1