Subject: Re: bug#70846: Imenu flatten

From: Juri Linkov <[email-masked]>
Date: Fri, 10 May 2024 20:06:07 +0300

> +(defcustom imenu-flatten nil
> +  "If non-nil, popup the completion buffer with a flattened menu.
> +The string from `imenu-level-separator' is used to separate names of
> +nested levels while flattening nested indexes with name concatenation."
> +  :type 'boolean

Here is another useful value for `imenu-flatten' that
will show section names as a suffix instead of a prefix:

diff --git a/lisp/imenu.el b/lisp/imenu.el
index 9c0c1ae144e..ccf5a0dc576 100644
--- a/lisp/imenu.el
+++ b/lisp/imenu.el
@@ -147,10 +147,16 @@ imenu-level-separator
 
 (defcustom imenu-flatten nil
   "Whether to flatten the list of sections in an imenu or show it nested.
-If non-nil, popup the completion buffer with a flattened menu.
+If nil, use nested indexes.
+If t, popup the completion buffer with a flattened menu.
+If `annotation', use completion annotation as a suffix
+to append section names after the index names.
+
 The string from `imenu-level-separator' is used to separate names of
 nested levels while flattening nested indexes with name concatenation."
-  :type 'boolean
+  :type '(choice (const :tag "Nested" nil)
+                 (const :tag "By prefix" t)
+                 (const :tag "By suffix" annotation))
   :version "30.1")
 
 (defcustom imenu-generic-skip-comments-and-strings t
@@ -743,7 +749,10 @@ imenu--completion-buffer
     ;; Display the completion buffer.
     (minibuffer-with-setup-hook
         (lambda ()
-          (setq-local completion-extra-properties '(:category imenu))
+          (setq-local completion-extra-properties
+                      `( :category imenu
+                         :annotation-function
+                         ,(lambda (s) (get-text-property 0 'imenu-section s))))
           (unless imenu-eager-completion-buffer
             (minibuffer-completion-help)))
       (setq name (completing-read prompt
@@ -787,7 +796,11 @@ imenu--flatten-index-alist
 			       name))))
        (cond
 	((not (imenu--subalist-p item))
-	 (list (cons new-prefix pos)))
+	 (list (cons (if (and (eq imenu-flatten 'annotation) prefix)
+			 (propertize name 'imenu-section
+				     (format " (%s)" prefix))
+		       name)
+		     pos)))
 	(t
 	 (imenu--flatten-index-alist pos concat-names new-prefix)))))
    index-alist))