Subject: Missing imenu entries with eglot

From: Sebastian Poeplau <[email-masked]>
Date: Fri, 08 Mar 2024 21:01:24 +0100

For language servers that reply to the textDocument/documentSymbol
request with instances of DocumentSymbol rather than SymbolInformation,
eglot's imenu builder omits symbols containing other symbols. This
applies to eglot 1.17 from ELPA as well as the version in Emacs master
as of today.

You can use clangd to reproduce the problem:

1. Put this code in a C++ source file, e.g., test.cpp:

   class Foo {
     void bar() {}
   };

2. Start eglot with clangd.
3. Invoke imenu; there will be a single entry "bar", nested under "Foo".
   In particular, there is no entry that lets you jump to Foo.

This is inconsistent with how eglot handles language servers that return
SymbolInformation (e.g., pylsp), and I would argue that it's not what
users expect. The attached patch fixes the behavior by inserting a
dedicated entry for each symbol in addition to entries for its children.

>From 953372f4cb1eea435a21a66e72226c7b2a6be51b Mon Sep 17 00:00:00 2001
From: Sebastian Poeplau <[email-masked]>
Date: Fri, 8 Mar 2024 16:29:25 +0100
Subject: [PATCH] Eglot: include containers in imenu

When the language server provides symbols as instances of
DocumentSymbol, eglot now includes containers (i.e., symbols with
children) in the imenu listing. This is consistent with eglot's behavior
when symbols are given as SymbolInformation objects.

* lisp/progmodes/eglot.el (eglot--imenu-DocumentSymbol): Include an
entry for symbols with children.
---
 lisp/progmodes/eglot.el | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/lisp/progmodes/eglot.el b/lisp/progmodes/eglot.el
index f341428cac3..87366811efd 100644
--- a/lisp/progmodes/eglot.el
+++ b/lisp/progmodes/eglot.el
@@ -3454,10 +3454,13 @@ for which LSP on-type-formatting should be requested."
                                          'breadcrumb-region reg
                                          'breadcrumb-kind kind)))
                   (if (seq-empty-p children)
-                      (cons name (car reg))
-                    (cons name
-                            (mapcar (lambda (c) (apply #'dfs c)) children))))))
-    (mapcar (lambda (s) (apply #'dfs s)) res)))
+                      (list (cons name (car reg)))
+                    (list (cons name (car reg))
+                          (cons name
+                                (mapcan (lambda (c)
+                                          (apply #'dfs c))
+                                        children)))))))
+    (mapcan (lambda (s) (apply #'dfs s)) res)))
 
 (cl-defun eglot-imenu ()
   "Eglot's `imenu-create-index-function'.
-- 
2.43.2