1 ;;; imenu.el --- Framework for mode-specific buffer indexes.
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
5 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
6 ;; Lars Lindberg <lli@sypro.cap.se>
9 ;; Keywords: tools convenience
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Purpose of this package:
31 ;; To present a framework for mode-specific buffer indexes.
32 ;; A buffer index is an alist of names and buffer positions.
33 ;; For instance all functions in a C-file and their positions.
35 ;; It is documented in the Emacs Lisp manual.
39 ;; A mode-specific function is called to generate the index. It is
40 ;; then presented to the user, who can choose from this index.
42 ;; The package comes with a set of example functions for how to
43 ;; utilize this package.
45 ;; There are *examples* for index gathering functions/regular
46 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
47 ;; customize for other modes. A function for jumping to the chosen
48 ;; index position is also supplied.
52 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
53 ;; [dean] - Dean Andrews ada@unison.com
54 ;; [alon] - Alon Albert al@mercury.co.il
55 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
56 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
57 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
58 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
59 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
60 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
64 (eval-when-compile (require 'cl))
66 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
68 ;;; Customizable variables
70 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
73 "Mode-specific buffer indexes."
77 :link '(custom-manual "(elisp)Imenu"))
79 (defcustom imenu-use-markers t
80 "*Non-nil means use markers instead of integers for Imenu buffer positions.
82 Setting this to nil makes Imenu work a little faster but editing the
83 buffer will make the generated index positions wrong.
85 This might not yet be honored by all index-building functions."
90 (defcustom imenu-max-item-length 60
91 "*If a number, truncate Imenu entries to that length."
92 :type '(choice integer
93 (const :tag "Unlimited"))
96 (defcustom imenu-auto-rescan nil
97 "*Non-nil means Imenu should always rescan the buffers."
101 (defcustom imenu-auto-rescan-maxout 60000
102 "*Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
103 This variable is buffer-local."
107 (defcustom imenu-always-use-completion-buffer-p nil
108 "*Set this to non-nil for displaying the index in a completion buffer.
110 `never' means never automatically display a listing of any kind.
111 A value of nil (the default) means display the index as a mouse menu
112 if the mouse was used to invoke `imenu'.
113 Another non-nil value means always display the index in a completion buffer."
114 :type '(choice (const :tag "On Mouse" nil)
115 (const :tag "Never" never)
116 (other :tag "Always" t))
120 (defcustom imenu-sort-function nil
121 "*The function to use for sorting the index mouse-menu.
123 Affects only the mouse index menu.
125 Set this to nil if you don't want any sorting (faster).
126 The items in the menu are then presented in the order they were found
129 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
131 The function should take two arguments and return t if the first
132 element should come before the second. The arguments are cons cells;
133 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
134 :type '(choice (const :tag "No sorting" nil)
135 (const :tag "Sort by name" imenu--sort-by-name)
136 (function :tag "Another function"))
139 (defcustom imenu-max-items 25
140 "*Maximum number of elements in a mouse menu for Imenu."
144 (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
145 "*Progress message during the index scanning of the buffer.
146 If non-nil, user gets a message during the scanning of the buffer.
148 Relevant only if the mode-specific function that creates the buffer
149 index use `imenu-progress-message', and not useful if that is fast, in
150 which case you might as well set this to nil."
151 :type '(choice string
152 (const :tag "None" nil))
155 (defcustom imenu-space-replacement "."
156 "*The replacement string for spaces in index names.
157 Used when presenting the index in a completion buffer to make the
158 names work as tokens."
162 (defcustom imenu-level-separator ":"
163 "*The separator between index names of different levels.
164 Used for making mouse-menu titles and for flattening nested indexes
165 with name concatenation."
170 (defvar imenu-generic-expression nil
171 "The regex pattern to use for creating a buffer index.
173 If non-nil this pattern is passed to `imenu--generic-function'
174 to create a buffer index.
176 The value should be an alist with elements that look like this:
177 (MENU-TITLE REGEXP INDEX)
179 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
180 with zero or more ARGUMENTS. The former format creates a simple element in
181 the index alist when it matches; the latter creates a special element
182 of the form (NAME FUNCTION POSITION-MARKER ARGUMENTS...)
183 with FUNCTION and ARGUMENTS beiong copied from `imenu-generic-expression'.
185 MENU-TITLE is a string used as the title for the submenu or nil if the
186 entries are not nested.
188 REGEXP is a regexp that should match a construct in the buffer that is
189 to be displayed in the menu; i.e., function or variable definitions,
190 etc. It contains a substring which is the name to appear in the
191 menu. See the info section on Regexps for more information.
193 INDEX points to the substring in REGEXP that contains the name (of the
194 function, variable or type) that is to appear in the menu.
196 The variable is buffer-local.
198 The variable `imenu-case-fold-search' determines whether or not the
199 regexp matches are case sensitive. and `imenu-syntax-alist' can be
200 used to alter the syntax table for the search.
202 For example, see the value of `lisp-imenu-generic-expression' used by
203 `lisp-mode' and `emacs-lisp-mode' with `imenu-syntax-alist' set
204 locally to give the characters which normally have \"punctuation\"
205 syntax \"word\" syntax during matching.")
208 (make-variable-buffer-local 'imenu-generic-expression)
213 (defvar imenu-create-index-function 'imenu-default-create-index-function
214 "The function to use for creating a buffer index.
216 It should be a function that takes no arguments and returns an index
217 of the current buffer as an alist.
219 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
220 Special elements look like (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...).
221 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
222 The function `imenu--subalist-p' tests an element and returns t
223 if it is a sub-alist.
225 This function is called within a `save-excursion'.
227 The variable is buffer-local.")
229 (make-variable-buffer-local 'imenu-create-index-function)
232 (defvar imenu-prev-index-position-function 'beginning-of-defun
233 "Function for finding the next index position.
235 If `imenu-create-index-function' is set to
236 `imenu-default-create-index-function', then you must set this variable
237 to a function that will find the next index, looking backwards in the
240 The function should leave point at the place to be connected to the
241 index and it should return nil when it doesn't find another index.
243 This variable is local in all buffers.")
245 (make-variable-buffer-local 'imenu-prev-index-position-function)
248 (defvar imenu-extract-index-name-function nil
249 "Function for extracting the index item name, given a position.
251 This function is called after `imenu-prev-index-position-function'
252 finds a position for an index item, with point at that position.
253 It should return the name for that index item.
255 This variable is local in all buffers.")
257 (make-variable-buffer-local 'imenu-extract-index-name-function)
260 (defvar imenu-default-goto-function 'imenu-default-goto-function
261 "The default function called when selecting an Imenu item.
262 The function in this variable is called when selecting a normal index-item.")
264 (make-variable-buffer-local 'imenu-default-goto-function)
267 (defun imenu--subalist-p (item)
268 (and (consp (cdr item)) (listp (cadr item))
269 (not (eq (car (cadr item)) 'lambda))))
271 ;; Macro to display a progress message.
272 ;; RELPOS is the relative position to display.
273 ;; If RELPOS is nil, then the relative position in the buffer
275 ;; PREVPOS is the variable in which we store the last position displayed.
276 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
278 imenu-scanning-message
279 (let ((pos ,(if relpos
281 `(imenu--relative-position ,reverse))))
283 `(> pos (+ 5 ,prevpos)))
285 (message imenu-scanning-message pos)
286 (setq ,prevpos pos))))))
289 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
291 ;;;; Some examples of functions utilizing the framework of this
294 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
296 ;; Return the current/previous sexp and the location of the sexp (its
297 ;; beginning) without moving the point.
298 (defun imenu-example--name-and-position ()
301 ;; [ydi] modified for imenu-use-markers
302 (let ((beg (if imenu-use-markers (point-marker) (point)))
303 (end (progn (forward-sexp) (point))))
304 (cons (buffer-substring beg end)
311 (defun imenu-example--lisp-extract-index-name ()
312 ;; Example of a candidate for `imenu-extract-index-name-function'.
313 ;; This will generate a flat index of definitions in a lisp file.
315 (and (looking-at "(def")
321 (end (progn (forward-sexp -1) (point))))
322 (buffer-substring beg end)))
325 (defun imenu-example--create-lisp-index ()
326 ;; Example of a candidate for `imenu-create-index-function'.
327 ;; It will generate a nested index of definitions.
328 (let ((index-alist '())
329 (index-var-alist '())
330 (index-type-alist '())
331 (index-unknown-alist '())
333 (goto-char (point-max))
334 (imenu-progress-message prev-pos 0)
335 ;; Search for the function
336 (while (beginning-of-defun)
337 (imenu-progress-message prev-pos nil t)
339 (and (looking-at "(def")
343 ((looking-at "def\\(var\\|const\\)")
345 (push (imenu-example--name-and-position)
347 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
349 (push (imenu-example--name-and-position)
351 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
353 (if (= (char-after (1- (point))) ?\))
358 (push (imenu-example--name-and-position)
362 (push (imenu-example--name-and-position)
363 index-unknown-alist)))))))
364 (imenu-progress-message prev-pos 100)
366 (push (cons "Variables" index-var-alist)
368 (and index-type-alist
369 (push (cons "Types" index-type-alist)
371 (and index-unknown-alist
372 (push (cons "Syntax-unknown" index-unknown-alist)
376 ;; Regular expression to find C functions
377 (defvar imenu-example--function-name-regexp-c
379 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
380 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
381 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
382 "\\([*&]+[ \t]*\\)?" ; pointer
383 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
386 (defun imenu-example--create-c-index (&optional regexp)
387 (let ((index-alist '())
389 (goto-char (point-min))
390 (imenu-progress-message prev-pos 0)
391 ;; Search for the function
393 (while (re-search-forward
394 (or regexp imenu-example--function-name-regexp-c)
396 (imenu-progress-message prev-pos)
399 (goto-char (scan-sexps (point) 1))
400 (setq char (following-char)))
401 ;; Skip this function name if it is a prototype declaration.
402 (if (not (eq char ?\;))
403 (push (imenu-example--name-and-position) index-alist))))
404 (imenu-progress-message prev-pos 100)
405 (nreverse index-alist)))
408 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
410 ;;; Internal variables
412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
414 ;; The item to use in the index for rescanning the buffer.
415 (defconst imenu--rescan-item '("*Rescan*" . -99))
417 ;; The latest buffer index.
419 (defvar imenu--index-alist nil
420 "The buffer index computed for this buffer in Imenu.
421 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
422 Special elements look like (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...).
423 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
425 This variable is local in all buffers, once set.")
427 (make-variable-buffer-local 'imenu--index-alist)
429 (defvar imenu--last-menubar-index-alist nil
430 "The latest buffer index used to update the menu bar menu.")
432 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
434 ;; History list for 'jump-to-function-in-buffer'.
435 ;; Making this buffer local caused it not to work!
436 (defvar imenu--history-list nil)
438 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
440 ;;; Internal support functions
442 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
446 ;;; Sorts the items depending on their index name.
447 ;;; An item looks like (NAME . POSITION).
449 (defun imenu--sort-by-name (item1 item2)
450 (string-lessp (car item1) (car item2)))
452 (defun imenu--sort-by-position (item1 item2)
453 (< (cdr item1) (cdr item2)))
455 (defun imenu--relative-position (&optional reverse)
456 ;; Support function to calculate relative position in buffer
457 ;; Beginning of buffer is 0 and end of buffer is 100
458 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
460 (total (buffer-size)))
461 (and reverse (setq pos (- total pos)))
463 ;; Avoid overflow from multiplying by 100!
464 (/ (1- pos) (max (/ total 100) 1))
465 (/ (* 100 (1- pos)) (max total 1)))))
467 ;; Split LIST into sublists of max length N.
468 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
469 (defun imenu--split (list n)
475 (push (pop remain) sublist)
478 ;; We have finished a sublist
479 (progn (push (nreverse sublist) result)
481 (setq sublist '()))))
482 ;; There might be a sublist (if the length of LIST mod n is != 0)
483 ;; that has to be added to the result list.
485 (push (nreverse sublist) result))
488 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
489 ;;; In any case, add TITLE to the front of the alist.
490 (defun imenu--split-menu (menulist title)
491 (let (keep-at-top tail)
492 (if (memq imenu--rescan-item menulist)
493 (setq keep-at-top (cons imenu--rescan-item nil)
494 menulist (delq imenu--rescan-item menulist)))
497 (if (imenu--subalist-p (car tail))
498 (setq keep-at-top (cons (car tail) keep-at-top)
499 menulist (delq (car tail) menulist)))
500 (setq tail (cdr tail)))
501 (if imenu-sort-function
506 ;; Copy list method from the cl package `copy-list'
507 (while (consp oldlist) (push (pop oldlist) res))
508 (if res ; in case, e.g. no functions defined
509 (prog1 (nreverse res) (setcdr res oldlist))))
510 imenu-sort-function)))
511 (if (> (length menulist) imenu-max-items)
517 (cons (format "From: %s" (caar menu)) menu)))
518 (imenu--split menulist imenu-max-items)))))
520 (nconc (nreverse keep-at-top) menulist))))
522 ;;; Split up each long alist that are nested within ALIST
523 ;;; into nested alists.
524 (defun imenu--split-submenus (alist)
530 (imenu--split-menu (cdr elt) (car elt))
534 ;;; Truncate all strings in MENULIST to imenu-max-item-length
535 (defun imenu--truncate-items (menulist)
540 (imenu--truncate-items (cdr item)))
542 ;; truncate if necessary
543 (if (and (numberp imenu-max-item-length)
544 (> (length (car item)) imenu-max-item-length))
545 (setcar item (substring (car item) 0 imenu-max-item-length)))))))
549 (defun imenu--make-index-alist (&optional noerror)
550 "Create an index-alist for the definitions in the current buffer.
552 Report an error if the list is empty unless NOERROR is supplied and
555 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
556 Special elements look like (INDEX-NAME FUNCTION ARGUMENTS...).
557 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
558 The function `imenu--subalist-p' tests an element and returns t
559 if it is a sub-alist.
561 There is one simple element with negative POSITION; that's intended
562 as a way for the user to ask to recalculate the buffer's index alist."
563 (or (and imenu--index-alist
564 (or (not imenu-auto-rescan)
565 (and imenu-auto-rescan
566 (> (buffer-size) imenu-auto-rescan-maxout))))
567 ;; Get the index; truncate if necessary
569 (setq imenu--index-alist
573 (funcall imenu-create-index-function))))
574 (imenu--truncate-items imenu--index-alist)))
575 (or imenu--index-alist noerror
576 (error "No items suitable for an index found in this buffer"))
577 (or imenu--index-alist
578 (setq imenu--index-alist (list nil)))
579 ;; Add a rescan option to the index.
580 (cons imenu--rescan-item imenu--index-alist))
582 ;;; Find all markers in alist and makes
583 ;;; them point nowhere.
584 ;;; The top-level call uses nil as the argument;
585 ;;; non-nil arguments are in recursivecalls.
586 (defvar imenu--cleanup-seen)
588 (defun imenu--cleanup (&optional alist)
589 ;; If alist is provided use that list.
590 ;; If not, empty the table of lists already seen
591 ;; and use imenu--index-alist.
593 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
594 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
601 ((markerp (cdr item))
602 (set-marker (cdr item) nil))
603 ;; Don't process one alist twice.
604 ((memq (cdr item) imenu--cleanup-seen))
605 ((imenu--subalist-p item)
606 (imenu--cleanup (cdr item))))))
610 (defun imenu--create-keymap-2 (alist counter &optional commands)
616 ((imenu--subalist-p item)
617 (append (list (setq counter (1+ counter))
618 (car item) 'keymap (car item))
619 (imenu--create-keymap-2 (cdr item) (+ counter 10) commands)))
621 (let ((end (if commands `(lambda () (interactive)
622 (imenu--menubar-select ',item))
623 (cons '(nil) item))))
625 (cons (car item) end)))))))
628 ;; If COMMANDS is non-nil, make a real keymap
629 ;; with a real command used as the definition.
630 ;; If it is nil, make something suitable for x-popup-menu.
631 (defun imenu--create-keymap-1 (title alist &optional commands)
632 (append (list 'keymap title) (imenu--create-keymap-2 alist 0 commands)))
634 (defun imenu--in-alist (str alist)
635 "Check whether the string STR is contained in multi-level ALIST."
636 (let (elt head tail res)
639 (setq elt (car alist)
643 ;; A nested ALIST element looks like
644 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
645 ;; while a bottom-level element looks like
646 ;; (INDEX-NAME . INDEX-POSITION)
647 ;; We are only interested in the bottom-level elements, so we need to
648 ;; recurse if TAIL is a list.
650 (if (setq res (imenu--in-alist str tail))
653 (setq alist nil res elt))))
656 (defvar imenu-syntax-alist nil
657 "Alist of syntax table modifiers to use while executing `imenu--generic-function'.
659 The car of the assocs may be either a character or a string and the
660 cdr is a syntax description appropriate fo `modify-syntax-entry'. For
661 a string, all the characters in the string get the specified syntax.
663 This is typically used to give word syntax to characters which
664 normally have symbol syntax to simplify `imenu-expression'
665 and speed-up matching.")
666 (make-variable-buffer-local 'imenu-syntax-alist)
668 (defun imenu-default-create-index-function ()
669 "*Wrapper for index searching functions.
671 Moves point to end of buffer and then repeatedly calls
672 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
673 Their results are gathered into an index alist."
674 ;; These should really be done by setting imenu-create-index-function
675 ;; in these major modes. But save that change for later.
676 (cond ((and imenu-prev-index-position-function
677 imenu-extract-index-name-function)
678 (let ((index-alist '())
680 (goto-char (point-max))
681 (imenu-progress-message prev-pos 0 t)
682 ;; Search for the function
683 (while (funcall imenu-prev-index-position-function)
684 (imenu-progress-message prev-pos nil t)
686 (setq name (funcall imenu-extract-index-name-function)))
688 ;; [ydi] updated for imenu-use-markers
689 (push (cons name (if imenu-use-markers (point-marker) (point)))
691 (imenu-progress-message prev-pos 100 t)
693 ;; Use generic expression if possible.
694 ((and imenu-generic-expression)
695 (imenu--generic-function imenu-generic-expression))
697 (error "This buffer cannot use `imenu-default-create-index-function'"))))
699 (defun imenu--replace-spaces (name replacement)
700 ;; Replace all spaces in NAME with REPLACEMENT.
701 ;; That second argument should be a string.
705 (if (char-equal ch ?\ )
707 (char-to-string ch))))
711 ;; Not used and would require cl at run time
712 ;;; (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
713 ;;; ;; Takes a nested INDEX-ALIST and returns a flat index alist.
714 ;;; ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
715 ;;; ;; name and a space concatenated to the names of the children.
716 ;;; ;; Third argument PREFIX is for internal use only.
719 ;;; (let* ((name (car item))
721 ;;; (new-prefix (and concat-names
723 ;;; (concat prefix imenu-level-separator name)
726 ;;; ((or (markerp pos) (numberp pos))
727 ;;; (list (cons new-prefix pos)))
729 ;;; (imenu--flatten-index-alist pos new-prefix)))))
733 ;;; Generic index gathering function.
736 (defvar imenu-case-fold-search t
737 "Defines whether `imenu--generic-function' should fold case when matching.
739 This buffer-local variable should be set (only) by initialization code
740 for modes which use `imenu--generic-function'. If it is not set, that
741 function will use the current value of `case-fold-search' to match
744 (make-variable-buffer-local 'imenu-case-fold-search)
746 ;; Originally "Built on some ideas that Erik Naggum <erik@naggum.no>
747 ;; once posted to comp.emacs" but since substantially re-written.
748 (defun imenu--generic-function (patterns)
749 "Return an index of the current buffer as an alist.
751 PATTERNS is an alist with elements that look like this:
752 (MENU-TITLE REGEXP INDEX).
754 MENU-TITLE is a string used as the title for the submenu or nil if the
755 entries are not nested.
757 REGEXP is a regexp that should match a construct in the buffer that is
758 to be displayed in the menu; i.e., function or variable definitions,
759 etc. It contains a substring which is the name to appear in the
760 menu. See the info section on Regexps for more information.
762 INDEX points to the substring in REGEXP that contains the name (of the
763 function, variable or type) that is to appear in the menu.
765 See `lisp-imenu-generic-expression' for an example of PATTERNS.
767 Returns an index of the current buffer as an alist. The elements in
768 the alist look like: (INDEX-NAME . INDEX-POSITION). They may also be
769 nested index lists like (INDEX-NAME . INDEX-ALIST) depending on
772 (let ((index-alist (list 'dummy))
774 (case-fold-search imenu-case-fold-search)
775 (old-table (syntax-table))
776 (table (copy-syntax-table (syntax-table)))
777 (slist imenu-syntax-alist))
778 ;; Modify the syntax table used while matching regexps.
780 ;; The character(s) to modify may be a single char or a string.
781 (if (numberp (caar slist))
782 (modify-syntax-entry (caar slist) (cdar slist) table)
785 (modify-syntax-entry c (cdar slist) table)))
787 (setq slist (cdr slist)))
788 (goto-char (point-max))
789 (imenu-progress-message prev-pos 0 t)
790 (unwind-protect ; for syntax table
792 (set-syntax-table table)
793 ;; map over the elements of imenu-generic-expression
794 ;; (typically functions, variables ...)
798 (let ((menu-title (car pat))
801 (function (nth 3 pat))
802 (rest (nthcdr 4 pat)))
803 ;; Go backwards for convenience of adding items in order.
804 (goto-char (point-max))
805 (while (re-search-backward regexp nil t)
806 (imenu-progress-message prev-pos nil t)
807 (setq beg (match-beginning index))
808 ;; Add this sort of submenu only when we've found an
809 ;; item for it, avoiding empty, duff menus.
810 (unless (assoc menu-title index-alist)
811 (push (list menu-title) index-alist))
812 (if imenu-use-markers
813 (setq beg (set-marker (make-marker) beg)))
816 (nconc (list (match-string-no-properties index)
819 (cons (match-string-no-properties index)
821 ;; This is the desired submenu,
822 ;; starting with its title (or nil).
823 (menu (assoc menu-title index-alist)))
824 ;; Insert the item unless it is already present.
825 (unless (member item (cdr menu))
827 (cons item (cdr menu)))))))))
829 (set-syntax-table old-table)))
830 (imenu-progress-message prev-pos 100 t)
831 ;; Sort each submenu by position.
832 ;; This is in case one submenu gets items from two different regexps.
833 (let ((tail index-alist))
835 (if (listp (car tail))
837 (sort (cdr (car tail)) 'imenu--sort-by-position)))
838 (setq tail (cdr tail))))
839 (let ((main-element (assq nil index-alist)))
840 (nconc (delq main-element (delq 'dummy index-alist))
841 (cdr main-element)))))
843 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
845 ;;; The main functions for this package!
847 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
849 (defun imenu--completion-buffer (index-alist &optional prompt)
850 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
852 Returns t for rescan and otherwise a position number."
853 ;; Create a list for this buffer only when needed.
854 (let ((name (thing-at-point 'symbol))
856 (prepared-index-alist
860 (cons (imenu--replace-spaces (car item) imenu-space-replacement)
864 ((and name (imenu--in-alist name prepared-index-alist))
865 (setq prompt (format "Index item (default %s): " name)))
866 (t (setq prompt "Index item: ")))
867 (if (eq imenu-always-use-completion-buffer-p 'never)
868 (setq name (completing-read prompt
870 nil t nil 'imenu--history-list name))
871 (save-window-excursion
872 ;; Display the completion buffer
873 (with-output-to-temp-buffer "*Completions*"
874 (display-completion-list
875 (all-completions "" prepared-index-alist )))
876 (let ((minibuffer-setup-hook
879 (let ((buffer (current-buffer)))
881 (set-buffer "*Completions*")
882 (setq completion-reference-buffer buffer)))))))
883 ;; Make a completion question
884 (setq name (completing-read prompt
886 nil t nil 'imenu--history-list name)))))
887 (cond ((not (stringp name))
889 ((string= name (car imenu--rescan-item))
892 (setq choice (assoc name prepared-index-alist))
893 (if (imenu--subalist-p choice)
894 (imenu--completion-buffer (cdr choice) prompt)
897 (defun imenu--mouse-menu (index-alist event &optional title)
898 "Let the user select from a buffer index from a mouse menu.
900 INDEX-ALIST is the buffer index and EVENT is a mouse event.
902 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
903 (setq index-alist (imenu--split-submenus index-alist))
904 (let* ((menu (imenu--split-menu index-alist
905 (or title (buffer-name))))
907 (setq menu (imenu--create-keymap-1 (car menu)
908 (if (< 1 (length (cdr menu)))
910 (cdr (car (cdr menu))))))
911 (setq position (x-popup-menu event menu))
912 (cond ((eq position nil)
914 ;; If one call to x-popup-menu handled the nested menus,
915 ;; find the result by looking down the menus here.
916 ((and (listp position)
917 (numberp (car position))
918 (stringp (nth (1- (length position)) position)))
921 (setq final (assoc (car position) final))
922 (setq position (cdr position)))
923 (or (string= (car final) (car imenu--rescan-item))
925 ;; If x-popup-menu went just one level and found a leaf item,
926 ;; return the INDEX-ALIST element for that.
927 ((and (consp position)
928 (stringp (car position))
929 (null (cdr position)))
930 (or (string= (car position) (car imenu--rescan-item))
931 (assq (car position) index-alist)))
932 ;; If x-popup-menu went just one level
933 ;; and found a non-leaf item (a submenu),
934 ;; recurse to handle the rest.
936 (imenu--mouse-menu position event
938 (concat title imenu-level-separator
939 (car (rassq position index-alist)))
940 (car (rassq position index-alist))))))))
942 (defun imenu-choose-buffer-index (&optional prompt alist)
943 "Let the user select from a buffer index and return the chosen index.
945 If the user originally activated this function with the mouse, a mouse
946 menu is used. Otherwise a completion buffer is used and the user is
947 prompted with PROMPT.
949 If you call this function with index alist ALIST, then it lets the user
952 With no index alist ALIST, it calls `imenu--make-index-alist' to
953 create the index alist.
955 If `imenu-always-use-completion-buffer-p' is non-nil, then the
956 completion buffer is always used, no matter if the mouse was used or
959 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
961 (mouse-triggered (listp last-nonmenu-event))
963 ;; If selected by mouse, see to that the window where the mouse is
964 ;; really is selected.
966 (not (equal last-nonmenu-event '(menu-bar)))
967 (let ((window (posn-window (event-start last-nonmenu-event))))
968 (or (framep window) (null window) (select-window window))))
969 ;; Create a list for this buffer only when needed.
971 (setq index-alist (if alist alist (imenu--make-index-alist)))
973 (if (and mouse-triggered
974 (not imenu-always-use-completion-buffer-p))
975 (imenu--mouse-menu index-alist last-nonmenu-event)
976 (imenu--completion-buffer index-alist prompt)))
979 (setq imenu--index-alist nil)))
983 (defun imenu-add-to-menubar (name)
984 "Add an `imenu' entry to the menu bar for the current buffer.
985 NAME is a string used to name the menu bar item.
986 See the command `imenu' for more information."
987 (interactive "sImenu menu item name: ")
988 (if (or (and imenu-prev-index-position-function
989 imenu-extract-index-name-function)
990 imenu-generic-expression
991 (not (eq imenu-create-index-function
992 'imenu-default-create-index-function)))
993 (let ((newmap (make-sparse-keymap))
994 (menu-bar (lookup-key (current-local-map) [menu-bar])))
995 (setq imenu--last-menubar-index-alist nil)
996 (define-key newmap [menu-bar]
997 (append (make-sparse-keymap) menu-bar))
998 (define-key newmap [menu-bar index]
999 (cons name (nconc (make-sparse-keymap "Imenu")
1000 (make-sparse-keymap))))
1001 (use-local-map (append newmap (current-local-map)))
1002 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
1003 (error "The mode `%s' does not support Imenu" mode-name)))
1006 (defun imenu-add-menubar-index ()
1007 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
1009 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
1011 (imenu-add-to-menubar "Index"))
1013 (defvar imenu-buffer-menubar nil)
1015 (defun imenu-update-menubar ()
1016 (and (current-local-map)
1017 (keymapp (lookup-key (current-local-map) [menu-bar index]))
1018 (let ((index-alist (imenu--make-index-alist t)))
1019 ;; Don't bother updating if the index-alist has not changed
1020 ;; since the last time we did it.
1021 (or (equal index-alist imenu--last-menubar-index-alist)
1022 (let (menu menu1 old)
1023 (setq imenu--last-menubar-index-alist index-alist)
1024 (setq index-alist (imenu--split-submenus index-alist))
1025 (setq menu (imenu--split-menu index-alist
1027 (setq menu1 (imenu--create-keymap-1 (car menu)
1028 (if (< 1 (length (cdr menu)))
1030 (cdr (car (cdr menu))))
1032 (setq old (lookup-key (current-local-map) [menu-bar index]))
1033 (setcdr old (cdr menu1)))))))
1035 (defun imenu--menubar-select (item)
1036 "Use Imenu to select the function or variable named in this menu item."
1037 (if (equal item imenu--rescan-item)
1040 (setq imenu--index-alist nil)
1041 (imenu-update-menubar))
1044 (defun imenu-default-goto-function (name position &optional rest)
1045 "Move the point to the given position.
1047 NAME is ignored. POSITION is where to move. REST is also ignored.
1048 The ignored args just make this function have the same interface as a
1049 function placed in a special index-item."
1050 (if (or (< position (point-min))
1051 (> position (point-max)))
1052 ;; widen if outside narrowing
1054 (goto-char position))
1057 (defun imenu (index-item)
1058 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1059 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1060 for more information."
1061 (interactive (list (imenu-choose-buffer-index)))
1062 ;; Convert a string to an alist element.
1063 (if (stringp index-item)
1064 (setq index-item (assoc index-item (imenu--make-index-alist))))
1068 (let* ((is-special-item (listp (cdr index-item)))
1071 (nth 2 index-item) imenu-default-goto-function))
1072 (position (if is-special-item
1073 (cadr index-item) (cdr index-item)))
1074 (rest (if is-special-item (cddr index-item))))
1075 (apply function (car index-item) position rest)))))
1079 ;;; imenu.el ends here