To configure imenu in my major mode, I need to set imenu-generic-expression to have regexps for functions.

However, this is incorrectly detects things inside comments and strings that look like functions.

How do I prevent this? imenu isn't confused by the following elisp, but I can't see what emacs-lisp-mode is doing differently.

;; imenu detects this.
(defun foo () (foo))

;; imenu correctly ignores this, even though it's at
;; the beginning of the line.
(defun bar () (bar))

;; imenu correctly ignores this.
;; (defun baz () (baz))

;; imenu correctly detects this, even though it's not
;; at the beginning of the line.
 (defun boz () (boz))
  • Can you simply anchor your expression at the beginning of the line? That's what the default value appears to do. Commented Aug 26, 2015 at 20:51
  • @TreborRude that doesn't help with multiline comments, and in the elisp example it's not confused by the string even though it's not at the beginning of the line. Commented Aug 26, 2015 at 20:57

1 Answer 1


The interesting function here is imenu--generic-function which by skips comments and string by inspecting the value of syntax-ppss. So it should have worked out of the box for you. Looking at the code it seems to jumps to the start of the before checking for output of syntax-ppss, I guess that is screwing up things for you (since it might move out the comment/string by moving to start of line).

I cannot suggest any workarounds since I am not aware of the major-mode you are taking about.

  • Thanks, that's really helpful, and I'll investigate further. The major mode I'm looking at is rust-mode. Commented Aug 28, 2015 at 17:07
  • @WilfredHughes I am not sure I understand why anchoring the imenu expressions to beginning of line, would break in presence of multiline comments. syntax-ppss would return that the point is in a string/comment and imenu--generic-function would discard the corresponding match wouldn't it? Commented Aug 30, 2015 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.