*** empty log message ***
[bpt/emacs.git] / lisp / imenu.el
index 393a196..f4c378a 100644 (file)
@@ -1,6 +1,6 @@
-;;; imenu.el --- Framework for mode-specific buffer indexes.
+;;; imenu.el --- framework for mode-specific buffer indexes
 
-;; Copyright (C) 1994, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
+;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2003 Free Software Foundation, Inc.
 
 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
 ;;         Lars Lindberg <lli@sypro.cap.se>
@@ -59,7 +59,7 @@
 ;;  [christian] - Christian Egli Christian.Egli@hcsd.hac.com
 ;;  [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
 
-;;; Code
+;;; Code:
 
 (eval-when-compile (require 'cl))
 
@@ -104,17 +104,26 @@ This variable is buffer-local."
   :type 'integer
   :group 'imenu)
 
-(defcustom imenu-always-use-completion-buffer-p nil
-  "*Set this to non-nil for displaying the index in a completion buffer.
-
-`never' means never automatically display a listing of any kind.
-A value of nil (the default) means display the index as a mouse menu
-if the mouse was used to invoke `imenu'.
-Another non-nil value means always display the index in a completion buffer."
-  :type '(choice (const :tag "On Mouse" nil)
-                (const :tag "Never" never)
-                (other :tag "Always" t))
-  :group 'imenu)
+(defvar imenu-always-use-completion-buffer-p nil)
+(make-obsolete-variable 'imenu-always-use-completion-buffer-p
+                       'imenu-use-popup-menu "21.4")
+
+(defcustom imenu-use-popup-menu
+  (if imenu-always-use-completion-buffer-p
+      (not (eq imenu-always-use-completion-buffer-p 'never))
+    'on-mouse)
+  "Use a popup menu rather than a minibuffer prompt.
+If nil, always use a minibuffer prompt.
+If t, always use a popup menu,
+If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
+  :type '(choice (const :tag "On Mouse" on-mouse)
+                (const :tag "Never" nil)
+                (other :tag "Always" t)))
+
+(defcustom imenu-eager-completion-buffer
+  (not (eq imenu-always-use-completion-buffer-p 'never))
+  "If non-nil, eagerly popup the completion buffer."
+  :type 'boolean)
 
 (defcustom imenu-after-jump-hook nil
   "*Hooks called after jumping to a place in the buffer.
@@ -164,7 +173,7 @@ which case you might as well set this to nil."
   "*The replacement string for spaces in index names.
 Used when presenting the index in a completion buffer to make the
 names work as tokens."
-  :type 'string
+  :type '(choice string (const nil))
   :group 'imenu)
 
 (defcustom imenu-level-separator ":"
@@ -204,13 +213,13 @@ function, variable or type) that is to appear in the menu.
 The variable is buffer-local.
 
 The variable `imenu-case-fold-search' determines whether or not the
-regexp matches are case sensitive. and `imenu-syntax-alist' can be
+regexp matches are case sensitive, and `imenu-syntax-alist' can be
 used to alter the syntax table for the search.
 
-For example, see the value of `lisp-imenu-generic-expression' used by
-`lisp-mode' and `emacs-lisp-mode' with `imenu-syntax-alist' set
-locally to give the characters which normally have \"punctuation\"
-syntax \"word\" syntax during matching.")
+For example, see the value of `fortran-imenu-generic-expression' used by
+`fortran-mode' with `imenu-syntax-alist' set locally to give the
+characters which normally have \"symbol\" syntax \"word\" syntax
+during matching.")
 
 ;;;###autoload
 (make-variable-buffer-local 'imenu-generic-expression)
@@ -517,29 +526,18 @@ This variable is local in all buffers, once set.")
        (setq keep-at-top (cons imenu--rescan-item nil)
              menulist (delq imenu--rescan-item menulist)))
     (setq tail menulist)
-    (while tail
-      (if (imenu--subalist-p (car tail))
-         (setq keep-at-top (cons (car tail) keep-at-top)
-               menulist (delq (car tail) menulist)))
-      (setq tail (cdr tail)))
+    (dolist (item tail)
+      (when (imenu--subalist-p item)
+       (push item keep-at-top)
+       (setq menulist (delq item menulist))))
     (if imenu-sort-function
-       (setq menulist
-             (sort
-              (let ((res nil)
-                    (oldlist menulist))
-                ;; Copy list method from the cl package `copy-list'
-                (while (consp oldlist) (push (pop oldlist) res))
-                (if res                ; in case, e.g. no functions defined
-                    (prog1 (nreverse res) (setcdr res oldlist))))
-              imenu-sort-function)))
+       (setq menulist (sort menulist imenu-sort-function)))
     (if (> (length menulist) imenu-max-items)
-       (let ((count 0))
-         (setq menulist
-               (mapcar
-                (function
-                 (lambda (menu)
-                   (cons (format "From: %s" (caar menu)) menu)))
-                (imenu--split menulist imenu-max-items)))))
+       (setq menulist
+             (mapcar
+              (lambda (menu)
+                (cons (format "From: %s" (caar menu)) menu))
+              (imenu--split menulist imenu-max-items))))
     (cons title
          (nconc (nreverse keep-at-top) menulist))))
 
@@ -566,7 +564,8 @@ This variable is local in all buffers, once set.")
               ;; truncate if necessary
               (if (and (numberp imenu-max-item-length)
                        (> (length (car item)) imenu-max-item-length))
-                  (setcar item (substring (car item) 0 imenu-max-item-length)))))))
+                  (setcar item (substring (car item) 0
+                                          imenu-max-item-length)))))))
          menulist))
 
 
@@ -618,42 +617,30 @@ as a way for the user to ask to recalculate the buffer's index alist."
     (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
 
   (and alist
-       (mapcar
-       (function
-        (lambda (item)
-          (cond
-           ((markerp (cdr item))
-            (set-marker (cdr item) nil))
-           ;; Don't process one alist twice.
-           ((memq (cdr item) imenu--cleanup-seen))
-           ((imenu--subalist-p item)
-            (imenu--cleanup (cdr item))))))
+       (mapc
+       (lambda (item)
+         (cond
+          ((markerp (cdr item))
+           (set-marker (cdr item) nil))
+          ;; Don't process one alist twice.
+          ((memq (cdr item) imenu--cleanup-seen))
+          ((imenu--subalist-p item)
+           (imenu--cleanup (cdr item)))))
        alist)
        t))
 
-(defun imenu--create-keymap-2 (alist counter &optional commands)
-  (let ((map nil))
-    (mapcar
-     (function
-      (lambda (item)
-       (cond
-        ((imenu--subalist-p item)
-         (append (list (setq counter (1+ counter))
-                       (car item) 'keymap (car item))
-                 (imenu--create-keymap-2 (cdr item) (+ counter 10) commands)))
-        (t
-         (let ((end (if commands `(lambda () (interactive)
-                                    (imenu--menubar-select ',item))
-                      (cons '(nil) item))))
-           (cons (car item)
-                 (cons (car item) end)))))))
-     alist)))
-
-;; If COMMANDS is non-nil, make a real keymap
-;; with a real command used as the definition.
-;; If it is nil, make something suitable for x-popup-menu.
-(defun imenu--create-keymap-1 (title alist &optional commands)
-  (append (list 'keymap title) (imenu--create-keymap-2 alist 0 commands)))
+(defun imenu--create-keymap (title alist &optional cmd)
+  (list* 'keymap title
+        (mapcar
+         (lambda (item)
+           (list* (car item) (car item)
+                  (cond
+                   ((imenu--subalist-p item)
+                    (imenu--create-keymap (car item) (cdr item) cmd))
+                   (t
+                    `(lambda () (interactive)
+                       ,(if cmd `(,cmd ',item) (list 'quote item)))))))
+         alist)))
 
 (defun imenu--in-alist (str alist)
   "Check whether the string STR is contained in multi-level ALIST."
@@ -680,15 +667,16 @@ as a way for the user to ask to recalculate the buffer's index alist."
     res))
 
 (defvar imenu-syntax-alist nil
-  "Alist of syntax table modifiers to use while executing `imenu--generic-function'.
+  "Alist of syntax table modifiers to use while in `imenu--generic-function'.
 
 The car of the assocs may be either a character or a string and the
-cdr is a syntax description appropriate fo `modify-syntax-entry'.  For
+cdr is a syntax description appropriate for `modify-syntax-entry'.  For
 a string, all the characters in the string get the specified syntax.
 
 This is typically used to give word syntax to characters which
 normally have symbol syntax to simplify `imenu-expression'
 and speed-up matching.")
+;;;###autoload
 (make-variable-buffer-local 'imenu-syntax-alist)
 
 (defun imenu-default-create-index-function ()
@@ -722,38 +710,26 @@ Their results are gathered into an index alist."
        (t
         (error "This buffer cannot use `imenu-default-create-index-function'"))))
 
-(defun imenu--replace-spaces (name replacement)
-  ;; Replace all spaces in NAME with REPLACEMENT.
-  ;; That second argument should be a string.
-  (mapconcat
-   (function
-    (lambda (ch)
-      (if (char-equal ch ?\ )
-         replacement
-       (char-to-string ch))))
-   name
-   ""))
-
 ;; Not used and would require cl at run time
-;;; (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
-;;;   ;; Takes a nested INDEX-ALIST and returns a flat index alist.
-;;;   ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
-;;;   ;; name and a space concatenated to the names of the children.
-;;;   ;; Third argument PREFIX is for internal use only.
-;;;   (mapcan
-;;;    (lambda (item)
-;;;      (let* ((name (car item))
-;;;        (pos (cdr item))
-;;;        (new-prefix (and concat-names
-;;;                         (if prefix
-;;;                             (concat prefix imenu-level-separator name)
-;;;                           name))))
-;;;        (cond
-;;;    ((or (markerp pos) (numberp pos))
-;;;     (list (cons new-prefix pos)))
-;;;    (t
-;;;     (imenu--flatten-index-alist pos new-prefix)))))
-;;;    index-alist))
+;; (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
+;;   ;; Takes a nested INDEX-ALIST and returns a flat index alist.
+;;   ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
+;;   ;; name and a space concatenated to the names of the children.
+;;   ;; Third argument PREFIX is for internal use only.
+;;   (mapcan
+;;    (lambda (item)
+;;      (let* ((name (car item))
+;;         (pos (cdr item))
+;;         (new-prefix (and concat-names
+;;                          (if prefix
+;;                              (concat prefix imenu-level-separator name)
+;;                            name))))
+;;        (cond
+;;     ((or (markerp pos) (numberp pos))
+;;      (list (cons new-prefix pos)))
+;;     (t
+;;      (imenu--flatten-index-alist pos new-prefix)))))
+;;    index-alist))
 
 ;;;
 ;;; Generic index gathering function.
@@ -762,10 +738,9 @@ Their results are gathered into an index alist."
 (defvar imenu-case-fold-search t
   "Defines whether `imenu--generic-function' should fold case when matching.
 
-This buffer-local variable should be set (only) by initialization code
-for modes which use `imenu--generic-function'.  If it is not set, that
-function will use the current value of `case-fold-search' to match
-patterns.")
+This variable should be set (only) by initialization code
+for modes which use `imenu--generic-function'.  If it is not set, but
+`font-lock-defaults' is set, then font-lock's setting is used.")
 ;;;###autoload
 (make-variable-buffer-local 'imenu-case-fold-search)
 
@@ -797,20 +772,21 @@ PATTERNS."
 
   (let ((index-alist (list 'dummy))
        prev-pos beg
-        (case-fold-search imenu-case-fold-search)
+        (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
+                                 (not (local-variable-p 'font-lock-defaults)))
+                             imenu-case-fold-search
+                           (nth 2 font-lock-defaults)))
         (old-table (syntax-table))
         (table (copy-syntax-table (syntax-table)))
         (slist imenu-syntax-alist))
     ;; Modify the syntax table used while matching regexps.
-    (while slist
+    (dolist (syn slist)
       ;; The character(s) to modify may be a single char or a string.
-      (if (numberp (caar slist))
-         (modify-syntax-entry (caar slist) (cdar slist) table)
-       (mapcar (function
-                (lambda (c)
-                  (modify-syntax-entry c (cdar slist) table)))
-               (caar slist)))
-      (setq slist (cdr slist)))
+      (if (numberp (car syn))
+         (modify-syntax-entry (car syn) (cdr syn) table)
+        (mapc (lambda (c)
+                (modify-syntax-entry c (cdr syn) table))
+              (car syn))))
     (goto-char (point-max))
     (imenu-progress-message prev-pos 0 t)
     (unwind-protect                    ; for syntax table
@@ -818,50 +794,44 @@ PATTERNS."
          (set-syntax-table table)
          ;; map over the elements of imenu-generic-expression
          ;; (typically functions, variables ...)
-         (mapcar
-          (function
-           (lambda (pat)
-             (let ((menu-title (car pat))
-                   (regexp (nth 1 pat))
-                   (index (nth 2 pat))
-                   (function (nth 3 pat))
-                   (rest (nthcdr 4 pat)))
-               ;; Go backwards for convenience of adding items in order.
-               (goto-char (point-max))
-               (while (re-search-backward regexp nil t)
-                 (imenu-progress-message prev-pos nil t)
-                 (setq beg (match-beginning index))
-                 ;; Add this sort of submenu only when we've found an
-                 ;; item for it, avoiding empty, duff menus.
-                 (unless (assoc menu-title index-alist)
-                   (push (list menu-title) index-alist))
-                 (if imenu-use-markers
-                     (setq beg (set-marker (make-marker) beg)))
-                 (let ((item
-                        (if function
-                            (nconc (list (match-string-no-properties index)
-                                         beg function)
-                                   rest)
-                          (cons (match-string-no-properties index)
-                                beg)))
-                       ;; This is the desired submenu,
-                       ;; starting with its title (or nil).
-                       (menu (assoc menu-title index-alist)))
-                   ;; Insert the item unless it is already present.
-                   (unless (member item (cdr menu))
-                     (setcdr menu
-                             (cons item (cdr menu)))))))))
-          patterns)
+         (dolist (pat patterns)
+           (let ((menu-title (car pat))
+                 (regexp (nth 1 pat))
+                 (index (nth 2 pat))
+                 (function (nth 3 pat))
+                 (rest (nthcdr 4 pat)))
+             ;; Go backwards for convenience of adding items in order.
+             (goto-char (point-max))
+             (while (re-search-backward regexp nil t)
+               (imenu-progress-message prev-pos nil t)
+               (setq beg (match-beginning index))
+               ;; Add this sort of submenu only when we've found an
+               ;; item for it, avoiding empty, duff menus.
+               (unless (assoc menu-title index-alist)
+                 (push (list menu-title) index-alist))
+               (if imenu-use-markers
+                   (setq beg (copy-marker beg)))
+               (let ((item
+                      (if function
+                          (nconc (list (match-string-no-properties index)
+                                       beg function)
+                                 rest)
+                        (cons (match-string-no-properties index)
+                              beg)))
+                     ;; This is the desired submenu,
+                     ;; starting with its title (or nil).
+                     (menu (assoc menu-title index-alist)))
+                 ;; Insert the item unless it is already present.
+                 (unless (member item (cdr menu))
+                   (setcdr menu
+                           (cons item (cdr menu))))))))
          (set-syntax-table old-table)))
     (imenu-progress-message prev-pos 100 t)
     ;; Sort each submenu by position.
     ;; This is in case one submenu gets items from two different regexps.
-    (let ((tail index-alist))
-      (while tail
-       (if (listp (car tail))
-           (setcdr (car tail)
-                   (sort (cdr (car tail)) 'imenu--sort-by-position)))
-       (setq tail (cdr tail))))
+    (dolist (item index-alist)
+      (when (listp item)
+       (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
     (let ((main-element (assq nil index-alist)))
       (nconc (delq main-element (delq 'dummy index-alist))
             (cdr main-element)))))
@@ -872,6 +842,19 @@ PATTERNS."
 ;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
+;; See also info-lookup-find-item
+(defun imenu-find-default (guess completions)
+  "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
+  (catch 'found
+    (let ((case-fold-search t))
+      (if (assoc guess completions) guess
+       (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
+                         (concat "\\`" (regexp-quote guess))
+                         (concat (regexp-quote guess) "\\'")
+                         (regexp-quote guess)))
+         (dolist (x completions)
+           (if (string-match re (car x)) (throw 'found (car x)))))))))
+
 (defun imenu--completion-buffer (index-alist &optional prompt)
   "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
 
@@ -880,40 +863,28 @@ Returns t for rescan and otherwise a position number."
   (let ((name (thing-at-point 'symbol))
        choice
        (prepared-index-alist
-        (mapcar
-         (function
-          (lambda (item)
-            (cons (imenu--replace-spaces (car item) imenu-space-replacement)
-                  (cdr item))))
-         index-alist)))
+        (if (not imenu-space-replacement) index-alist
+          (mapcar
+           (lambda (item)
+             (cons (subst-char-in-string ?\ (aref imenu-space-replacement 0)
+                                         (car item))
+                   (cdr item)))
+           index-alist))))
+    (when (stringp name)
+      (setq name (or (imenu-find-default name prepared-index-alist) name)))
     (cond (prompt)
          ((and name (imenu--in-alist name prepared-index-alist))
           (setq prompt (format "Index item (default %s): " name)))
          (t (setq prompt "Index item: ")))
-    (if (eq imenu-always-use-completion-buffer-p 'never)
-       (setq name (completing-read prompt
-                                   prepared-index-alist
-                                   nil t nil 'imenu--history-list name))
-      (save-window-excursion
-       ;; Display the completion buffer
-       (with-output-to-temp-buffer "*Completions*"
-         (display-completion-list
-          (all-completions "" prepared-index-alist )))
-       (let ((minibuffer-setup-hook
-              (function
-               (lambda ()
-                 (let ((buffer (current-buffer)))
-                   (save-excursion
-                     (set-buffer "*Completions*")
-                     (setq completion-reference-buffer buffer)))))))
-         ;; Make a completion question
-         (setq name (completing-read prompt
-                                     prepared-index-alist
-                                     nil t nil 'imenu--history-list name)))))
-    (cond ((not (stringp name))
-          nil)
-         ((string= name (car imenu--rescan-item))
-          t)
+    (let ((minibuffer-setup-hook minibuffer-setup-hook))
+      ;; Display the completion buffer.
+      (if (not imenu-eager-completion-buffer)
+         (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
+      (setq name (completing-read prompt
+                                 prepared-index-alist
+                                 nil t nil 'imenu--history-list name)))
+    (cond ((not (stringp name)) nil)
+         ((string= name (car imenu--rescan-item)) t)
          (t
           (setq choice (assoc name prepared-index-alist))
           (if (imenu--subalist-p choice)
@@ -927,43 +898,12 @@ INDEX-ALIST is the buffer index and EVENT is a mouse event.
 
 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
   (setq index-alist (imenu--split-submenus index-alist))
-  (let* ((menu         (imenu--split-menu index-alist
-                                  (or title (buffer-name))))
-       position)
-    (setq menu (imenu--create-keymap-1 (car menu)
-                                      (if (< 1 (length (cdr menu)))
-                                          (cdr menu)
-                                        (cdr (car (cdr menu))))))
-    (setq position (x-popup-menu event menu))
-    (cond ((eq position nil)
-          position)
-         ;; If one call to x-popup-menu handled the nested menus,
-         ;; find the result by looking down the menus here.
-         ((and (listp position)
-               (numberp (car position))
-               (stringp (nth (1- (length position)) position)))
-          (let ((final menu))
-            (while position
-              (setq final (assq (car position) final))
-              (setq position (cdr position)))
-             (or (string= (car final) (car imenu--rescan-item))
-                 (nthcdr 3 final))))
-         ;; If x-popup-menu went just one level and found a leaf item,
-         ;; return the INDEX-ALIST element for that.
-         ((and (consp position)
-               (stringp (car position))
-               (null (cdr position)))
-          (or (string= (car position) (car imenu--rescan-item))
-              (assq (car position) index-alist)))
-         ;; If x-popup-menu went just one level
-         ;; and found a non-leaf item (a submenu),
-         ;; recurse to handle the rest.
-         ((listp position)
-          (imenu--mouse-menu position event
-                             (if title
-                                 (concat title imenu-level-separator
-                                         (car (rassq position index-alist)))
-                               (car (rassq position index-alist))))))))
+  (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
+        (map (imenu--create-keymap (car menu)
+                                   (cdr (if (< 1 (length (cdr menu)))
+                                            menu
+                                          (car (cdr menu)))))))
+    (popup-menu map event)))
 
 (defun imenu-choose-buffer-index (&optional prompt alist)
   "Let the user select from a buffer index and return the chosen index.
@@ -978,14 +918,14 @@ select from ALIST.
 With no index alist ALIST, it calls `imenu--make-index-alist' to
 create the index alist.
 
-If `imenu-always-use-completion-buffer-p' is non-nil, then the
+If `imenu-use-popup-menu' is non-nil, then the
 completion buffer is always used, no matter if the mouse was used or
 not.
 
 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
   (let (index-alist
        (mouse-triggered (listp last-nonmenu-event))
-       (result t) )
+       (result t))
     ;; If selected by mouse, see to that the window where the mouse is
     ;; really is selected.
     (and mouse-triggered
@@ -996,8 +936,8 @@ The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
     (while (eq result t)
       (setq index-alist (if alist alist (imenu--make-index-alist)))
       (setq result
-           (if (and mouse-triggered
-                    (not imenu-always-use-completion-buffer-p))
+           (if (and imenu-use-popup-menu
+                    (or (eq imenu-use-popup-menu t) mouse-triggered))
                (imenu--mouse-menu index-alist last-nonmenu-event)
              (imenu--completion-buffer index-alist prompt)))
       (and (eq result t)
@@ -1016,15 +956,12 @@ See the command `imenu' for more information."
          imenu-generic-expression
          (not (eq imenu-create-index-function
                   'imenu-default-create-index-function)))
-      (let ((newmap (make-sparse-keymap))
-           (menu-bar (lookup-key (current-local-map) [menu-bar])))
+      (let ((newmap (make-sparse-keymap)))
+       (set-keymap-parent newmap (current-local-map))
        (setq imenu--last-menubar-index-alist nil)
-       (define-key newmap [menu-bar]
-         (append (make-sparse-keymap) menu-bar))
        (define-key newmap [menu-bar index]
-         (cons name (nconc (make-sparse-keymap "Imenu")
-                           (make-sparse-keymap))))
-       (use-local-map (append newmap (current-local-map)))
+         `(menu-item ,name ,(make-sparse-keymap "Imenu")))
+       (use-local-map newmap)
        (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
     (error "The mode `%s' does not support Imenu" mode-name)))
 
@@ -1038,34 +975,44 @@ A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
 
 (defvar imenu-buffer-menubar nil)
 
+(defvar imenu-menubar-modified-tick 0
+  "The value of (buffer-modified-tick) as of last call to `imenu-update-menubar'.
+This value becomes local in every buffer when it is set.")
+(make-variable-buffer-local 'imenu-menubar-modified-tick)
+
 (defun imenu-update-menubar ()
-  (and (current-local-map)
-       (keymapp (lookup-key (current-local-map) [menu-bar index]))
-       (let ((index-alist (imenu--make-index-alist t)))
-        ;; Don't bother updating if the index-alist has not changed
-        ;; since the last time we did it.
-        (or (equal index-alist imenu--last-menubar-index-alist)
-            (let (menu menu1 old)
-              (setq imenu--last-menubar-index-alist index-alist)
-              (setq index-alist (imenu--split-submenus index-alist))
-              (setq menu (imenu--split-menu index-alist
-                                             (buffer-name)))
-              (setq menu1 (imenu--create-keymap-1 (car menu) 
-                                                   (if (< 1 (length (cdr menu)))
-                                                       (cdr menu)
-                                                    (cdr (car (cdr menu))))
-                                                   t))
-              (setq old (lookup-key (current-local-map) [menu-bar index]))
-              (setcdr old (cdr menu1)))))))
+  (when (and (current-local-map)
+            (keymapp (lookup-key (current-local-map) [menu-bar index]))
+            (not (eq (buffer-modified-tick)
+                     imenu-menubar-modified-tick)))
+    (setq imenu-menubar-modified-tick (buffer-modified-tick))
+    (let ((index-alist (imenu--make-index-alist t)))
+      ;; Don't bother updating if the index-alist has not changed
+      ;; since the last time we did it.
+      (unless (equal index-alist imenu--last-menubar-index-alist)
+       (let (menu menu1 old)
+         (setq imenu--last-menubar-index-alist index-alist)
+         (setq index-alist (imenu--split-submenus index-alist))
+         (setq menu (imenu--split-menu index-alist
+                                       (buffer-name)))
+         (setq menu1 (imenu--create-keymap (car menu)
+                                           (cdr (if (< 1 (length (cdr menu)))
+                                                    menu
+                                                  (car (cdr menu))))
+                                           'imenu--menubar-select))
+         (setq old (lookup-key (current-local-map) [menu-bar index]))
+         (setcdr old (cdr menu1)))))))
 
 (defun imenu--menubar-select (item)
-  "Use Imenu to select the function or variable named in this menu item."
+  "Use Imenu to select the function or variable named in this menu ITEM."
   (if (equal item imenu--rescan-item)
       (progn
        (imenu--cleanup)
        (setq imenu--index-alist nil)
-       (imenu-update-menubar))
-    (imenu item)))
+       (imenu-update-menubar)
+       t)
+    (imenu item)
+    nil))
 
 (defun imenu-default-goto-function (name position &optional rest)
   "Move the point to the given position.
@@ -1088,18 +1035,17 @@ for more information."
   ;; Convert a string to an alist element.
   (if (stringp index-item)
       (setq index-item (assoc index-item (imenu--make-index-alist))))
-  (and index-item
-       (progn
-        (push-mark)
-        (let* ((is-special-item (listp (cdr index-item)))
-               (function
-                (if is-special-item
-                    (nth 2 index-item) imenu-default-goto-function))
-              (position (if is-special-item
-                            (cadr index-item) (cdr index-item)))
-              (rest (if is-special-item (cddr index-item))))
-          (apply function (car index-item) position rest))))
-  (run-hooks 'imenu-after-jump-hook))
+  (when index-item
+    (push-mark)
+    (let* ((is-special-item (listp (cdr index-item)))
+          (function
+           (if is-special-item
+               (nth 2 index-item) imenu-default-goto-function))
+          (position (if is-special-item
+                        (cadr index-item) (cdr index-item)))
+          (rest (if is-special-item (cddr index-item))))
+      (apply function (car index-item) position rest))
+    (run-hooks 'imenu-after-jump-hook)))
 
 (dolist (mess
         '("^No items suitable for an index found in this buffer$"