(Vsearch_spaces_regexp):
[emacs.git] / lisp / imenu.el
blob16116025fb827774d047467d569b62319507ffb2
1 ;;; imenu.el --- framework for mode-specific buffer indexes
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2003, 2004
4 ;; Free Software Foundation, Inc.
6 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
7 ;; Lars Lindberg <lli@sypro.cap.se>
8 ;; Maintainer: FSF
9 ;; Created: 8 Feb 1994
10 ;; Keywords: tools convenience
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
29 ;;; Commentary:
31 ;; Purpose of this package:
32 ;; To present a framework for mode-specific buffer indexes.
33 ;; A buffer index is an alist of names and buffer positions.
34 ;; For instance all functions in a C-file and their positions.
36 ;; It is documented in the Emacs Lisp manual.
38 ;; How it works:
40 ;; A mode-specific function is called to generate the index. It is
41 ;; then presented to the user, who can choose from this index.
43 ;; The package comes with a set of example functions for how to
44 ;; utilize this package.
46 ;; There are *examples* for index gathering functions/regular
47 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
48 ;; customize for other modes. A function for jumping to the chosen
49 ;; index position is also supplied.
51 ;;; History:
52 ;; Thanks go to
53 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
54 ;; [dean] - Dean Andrews ada@unison.com
55 ;; [alon] - Alon Albert al@mercury.co.il
56 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
57 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
58 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
59 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
60 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
61 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
63 ;;; Code:
65 (require 'newcomment)
67 (eval-when-compile (require 'cl))
69 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 ;;;
71 ;;; Customizable variables
72 ;;;
73 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
75 (defgroup imenu nil
76 "Mode-specific buffer indexes."
77 :group 'matching
78 :group 'frames
79 :group 'convenience
80 :link '(custom-manual "(elisp)Imenu"))
82 (defcustom imenu-use-markers t
83 "*Non-nil means use markers instead of integers for Imenu buffer positions.
85 Setting this to nil makes Imenu work a little faster but editing the
86 buffer will make the generated index positions wrong.
88 This might not yet be honored by all index-building functions."
89 :type 'boolean
90 :group 'imenu)
93 (defcustom imenu-max-item-length 60
94 "*If a number, truncate Imenu entries to that length."
95 :type '(choice integer
96 (const :tag "Unlimited"))
97 :group 'imenu)
99 (defcustom imenu-auto-rescan nil
100 "*Non-nil means Imenu should always rescan the buffers."
101 :type 'boolean
102 :group 'imenu)
104 (defcustom imenu-auto-rescan-maxout 60000
105 "*Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
106 This variable is buffer-local."
107 :type 'integer
108 :group 'imenu)
110 (defvar imenu-always-use-completion-buffer-p nil)
111 (make-obsolete-variable 'imenu-always-use-completion-buffer-p
112 'imenu-use-popup-menu "21.4")
114 (defcustom imenu-use-popup-menu
115 (if imenu-always-use-completion-buffer-p
116 (not (eq imenu-always-use-completion-buffer-p 'never))
117 'on-mouse)
118 "Use a popup menu rather than a minibuffer prompt.
119 If nil, always use a minibuffer prompt.
120 If t, always use a popup menu,
121 If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
122 :type '(choice (const :tag "On Mouse" on-mouse)
123 (const :tag "Never" nil)
124 (other :tag "Always" t)))
126 (defcustom imenu-eager-completion-buffer
127 (not (eq imenu-always-use-completion-buffer-p 'never))
128 "If non-nil, eagerly popup the completion buffer."
129 :type 'boolean
130 :group 'imenu
131 :version "21.4")
133 (defcustom imenu-after-jump-hook nil
134 "*Hooks called after jumping to a place in the buffer.
136 Useful things to use here include `reposition-window', `recenter', and
137 \(lambda () (recenter 0)) to show at top of screen."
138 :type 'hook
139 :group 'imenu)
141 ;;;###autoload
142 (defcustom imenu-sort-function nil
143 "*The function to use for sorting the index mouse-menu.
145 Affects only the mouse index menu.
147 Set this to nil if you don't want any sorting (faster).
148 The items in the menu are then presented in the order they were found
149 in the buffer.
151 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
153 The function should take two arguments and return t if the first
154 element should come before the second. The arguments are cons cells;
155 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
156 :type '(choice (const :tag "No sorting" nil)
157 (const :tag "Sort by name" imenu--sort-by-name)
158 (function :tag "Another function"))
159 :group 'imenu)
161 (defcustom imenu-max-items 25
162 "*Maximum number of elements in a mouse menu for Imenu."
163 :type 'integer
164 :group 'imenu)
166 ;; No longer used. KFS 2004-10-27
167 ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
168 ;; "*Progress message during the index scanning of the buffer.
169 ;; If non-nil, user gets a message during the scanning of the buffer.
171 ;; Relevant only if the mode-specific function that creates the buffer
172 ;; index use `imenu-progress-message', and not useful if that is fast, in
173 ;; which case you might as well set this to nil."
174 ;; :type '(choice string
175 ;; (const :tag "None" nil))
176 ;; :group 'imenu)
178 (defcustom imenu-space-replacement "."
179 "*The replacement string for spaces in index names.
180 Used when presenting the index in a completion buffer to make the
181 names work as tokens."
182 :type '(choice string (const nil))
183 :group 'imenu)
185 (defcustom imenu-level-separator ":"
186 "*The separator between index names of different levels.
187 Used for making mouse-menu titles and for flattening nested indexes
188 with name concatenation."
189 :type 'string
190 :group 'imenu)
192 ;;;###autoload
193 (defvar imenu-generic-expression nil
194 "The regex pattern to use for creating a buffer index.
196 If non-nil this pattern is passed to `imenu--generic-function'
197 to create a buffer index.
199 The value should be an alist with elements that look like this:
200 (MENU-TITLE REGEXP INDEX)
201 or like this:
202 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
203 with zero or more ARGUMENTS. The former format creates a simple element in
204 the index alist when it matches; the latter creates a special element
205 of the form (NAME POSITION-MARKER FUNCTION ARGUMENTS...)
206 with FUNCTION and ARGUMENTS copied from `imenu-generic-expression'.
208 MENU-TITLE is a string used as the title for the submenu or nil if the
209 entries are not nested.
211 REGEXP is a regexp that should match a construct in the buffer that is
212 to be displayed in the menu; i.e., function or variable definitions,
213 etc. It contains a substring which is the name to appear in the
214 menu. See the info section on Regexps for more information.
216 INDEX points to the substring in REGEXP that contains the name (of the
217 function, variable or type) that is to appear in the menu.
219 The variable `imenu-case-fold-search' determines whether or not the
220 regexp matches are case sensitive, and `imenu-syntax-alist' can be
221 used to alter the syntax table for the search.
223 For example, see the value of `fortran-imenu-generic-expression' used by
224 `fortran-mode' with `imenu-syntax-alist' set locally to give the
225 characters which normally have \"symbol\" syntax \"word\" syntax
226 during matching.")
228 ;;;###autoload
229 (make-variable-buffer-local 'imenu-generic-expression)
231 ;;;; Hooks
233 ;;;###autoload
234 (defvar imenu-create-index-function 'imenu-default-create-index-function
235 "The function to use for creating a buffer index.
237 It should be a function that takes no arguments and returns an index
238 of the current buffer as an alist.
240 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
241 Special elements look like (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...).
242 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
243 The function `imenu--subalist-p' tests an element and returns t
244 if it is a sub-alist.
246 This function is called within a `save-excursion'.")
247 ;;;###autoload
248 (make-variable-buffer-local 'imenu-create-index-function)
250 ;;;###autoload
251 (defvar imenu-prev-index-position-function 'beginning-of-defun
252 "Function for finding the next index position.
254 If `imenu-create-index-function' is set to
255 `imenu-default-create-index-function', then you must set this variable
256 to a function that will find the next index, looking backwards in the
257 file.
259 The function should leave point at the place to be connected to the
260 index and it should return nil when it doesn't find another index.")
261 ;;;###autoload
262 (make-variable-buffer-local 'imenu-prev-index-position-function)
264 ;;;###autoload
265 (defvar imenu-extract-index-name-function nil
266 "Function for extracting the index item name, given a position.
268 This function is called after `imenu-prev-index-position-function'
269 finds a position for an index item, with point at that position.
270 It should return the name for that index item.")
271 ;;;###autoload
272 (make-variable-buffer-local 'imenu-extract-index-name-function)
274 ;;;###autoload
275 (defvar imenu-name-lookup-function nil
276 "Function to compare string with index item.
278 This function will be called with two strings, and should return
279 non-nil if they match.
281 If nil, comparison is done with `string='.
282 Set this to some other function for more advanced comparisons,
283 such as \"begins with\" or \"name matches and number of
284 arguments match\".")
285 ;;;###autoload
286 (make-variable-buffer-local 'imenu-name-lookup-function)
288 ;;;###autoload
289 (defvar imenu-default-goto-function 'imenu-default-goto-function
290 "The default function called when selecting an Imenu item.
291 The function in this variable is called when selecting a normal index-item.")
292 ;;;###autoload
293 (make-variable-buffer-local 'imenu-default-goto-function)
296 (defun imenu--subalist-p (item)
297 (and (consp (cdr item)) (listp (cadr item))
298 (not (eq (car (cadr item)) 'lambda))))
300 ;; Macro to display a progress message.
301 ;; RELPOS is the relative position to display.
302 ;; If RELPOS is nil, then the relative position in the buffer
303 ;; is calculated.
304 ;; PREVPOS is the variable in which we store the last position displayed.
305 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
307 ;; Made obsolete/empty, as computers are now faster than the eye, and
308 ;; it had problems updating the messages correctly, and could shadow
309 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
311 ;; `(and
312 ;; imenu-scanning-message
313 ;; (let ((pos ,(if relpos
314 ;; relpos
315 ;; `(imenu--relative-position ,reverse))))
316 ;; (if ,(if relpos t
317 ;; `(> pos (+ 5 ,prevpos)))
318 ;; (progn
319 ;; (message imenu-scanning-message pos)
320 ;; (setq ,prevpos pos)))))
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
325 ;;;;
326 ;;;; Some examples of functions utilizing the framework of this
327 ;;;; package.
328 ;;;;
329 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
331 ;; FIXME: This is the only imenu-example-* definition that's actually used,
332 ;; and it seems to only be used by cperl-mode.el. We should just move it to
333 ;; cperl-mode.el and remove the rest.
334 (defun imenu-example--name-and-position ()
335 "Return the current/previous sexp and its (beginning) location.
336 Don't move point."
337 (save-excursion
338 (forward-sexp -1)
339 ;; [ydi] modified for imenu-use-markers
340 (let ((beg (if imenu-use-markers (point-marker) (point)))
341 (end (progn (forward-sexp) (point))))
342 (cons (buffer-substring beg end)
343 beg))))
346 ;;; Lisp
349 (defun imenu-example--lisp-extract-index-name ()
350 ;; Example of a candidate for `imenu-extract-index-name-function'.
351 ;; This will generate a flat index of definitions in a lisp file.
352 (save-match-data
353 (and (looking-at "(def")
354 (condition-case nil
355 (progn
356 (down-list 1)
357 (forward-sexp 2)
358 (let ((beg (point))
359 (end (progn (forward-sexp -1) (point))))
360 (buffer-substring beg end)))
361 (error nil)))))
363 (defun imenu-example--create-lisp-index ()
364 ;; Example of a candidate for `imenu-create-index-function'.
365 ;; It will generate a nested index of definitions.
366 (let ((index-alist '())
367 (index-var-alist '())
368 (index-type-alist '())
369 (index-unknown-alist '())
370 prev-pos)
371 (goto-char (point-max))
372 (imenu-progress-message prev-pos 0)
373 ;; Search for the function
374 (while (beginning-of-defun)
375 (imenu-progress-message prev-pos nil t)
376 (save-match-data
377 (and (looking-at "(def")
378 (save-excursion
379 (down-list 1)
380 (cond
381 ((looking-at "def\\(var\\|const\\)")
382 (forward-sexp 2)
383 (push (imenu-example--name-and-position)
384 index-var-alist))
385 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
386 (forward-sexp 2)
387 (push (imenu-example--name-and-position)
388 index-alist))
389 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
390 (forward-sexp 2)
391 (if (= (char-after (1- (point))) ?\))
392 (progn
393 (forward-sexp -1)
394 (down-list 1)
395 (forward-sexp 1)))
396 (push (imenu-example--name-and-position)
397 index-type-alist))
399 (forward-sexp 2)
400 (push (imenu-example--name-and-position)
401 index-unknown-alist)))))))
402 (imenu-progress-message prev-pos 100)
403 (and index-var-alist
404 (push (cons "Variables" index-var-alist)
405 index-alist))
406 (and index-type-alist
407 (push (cons "Types" index-type-alist)
408 index-alist))
409 (and index-unknown-alist
410 (push (cons "Syntax-unknown" index-unknown-alist)
411 index-alist))
412 index-alist))
414 ;; Regular expression to find C functions
415 (defvar imenu-example--function-name-regexp-c
416 (concat
417 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
418 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
419 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
420 "\\([*&]+[ \t]*\\)?" ; pointer
421 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
424 (defun imenu-example--create-c-index (&optional regexp)
425 (let ((index-alist '())
426 prev-pos char)
427 (goto-char (point-min))
428 (imenu-progress-message prev-pos 0)
429 ;; Search for the function
430 (save-match-data
431 (while (re-search-forward
432 (or regexp imenu-example--function-name-regexp-c)
433 nil t)
434 (imenu-progress-message prev-pos)
435 (backward-up-list 1)
436 (save-excursion
437 (goto-char (scan-sexps (point) 1))
438 (setq char (following-char)))
439 ;; Skip this function name if it is a prototype declaration.
440 (if (not (eq char ?\;))
441 (push (imenu-example--name-and-position) index-alist))))
442 (imenu-progress-message prev-pos 100)
443 (nreverse index-alist)))
446 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
448 ;;; Internal variables
450 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
452 ;; The item to use in the index for rescanning the buffer.
453 (defconst imenu--rescan-item '("*Rescan*" . -99))
455 ;; The latest buffer index.
456 ;; Buffer local.
457 (defvar imenu--index-alist nil
458 "The buffer index computed for this buffer in Imenu.
459 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
460 Special elements look like (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...).
461 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).")
463 (make-variable-buffer-local 'imenu--index-alist)
465 (defvar imenu--last-menubar-index-alist nil
466 "The latest buffer index used to update the menu bar menu.")
468 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
470 ;; History list for 'jump-to-function-in-buffer'.
471 ;; Making this buffer local caused it not to work!
472 (defvar imenu--history-list nil)
474 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
476 ;;; Internal support functions
478 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
481 ;;; Sort function
482 ;;; Sorts the items depending on their index name.
483 ;;; An item looks like (NAME . POSITION).
485 (defun imenu--sort-by-name (item1 item2)
486 (string-lessp (car item1) (car item2)))
488 (defun imenu--sort-by-position (item1 item2)
489 (< (cdr item1) (cdr item2)))
491 (defun imenu--relative-position (&optional reverse)
492 ;; Support function to calculate relative position in buffer
493 ;; Beginning of buffer is 0 and end of buffer is 100
494 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
495 (let ((pos (point))
496 (total (buffer-size)))
497 (and reverse (setq pos (- total pos)))
498 (if (> total 50000)
499 ;; Avoid overflow from multiplying by 100!
500 (/ (1- pos) (max (/ total 100) 1))
501 (/ (* 100 (1- pos)) (max total 1)))))
503 ;; Split LIST into sublists of max length N.
504 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
505 (defun imenu--split (list n)
506 (let ((remain list)
507 (result '())
508 (sublist '())
509 (i 0))
510 (while remain
511 (push (pop remain) sublist)
512 (incf i)
513 (and (= i n)
514 ;; We have finished a sublist
515 (progn (push (nreverse sublist) result)
516 (setq i 0)
517 (setq sublist '()))))
518 ;; There might be a sublist (if the length of LIST mod n is != 0)
519 ;; that has to be added to the result list.
520 (and sublist
521 (push (nreverse sublist) result))
522 (nreverse result)))
524 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
525 ;;; In any case, add TITLE to the front of the alist.
526 (defun imenu--split-menu (menulist title)
527 (let (keep-at-top tail)
528 (if (memq imenu--rescan-item menulist)
529 (setq keep-at-top (cons imenu--rescan-item nil)
530 menulist (delq imenu--rescan-item menulist)))
531 (setq tail menulist)
532 (dolist (item tail)
533 (when (imenu--subalist-p item)
534 (push item keep-at-top)
535 (setq menulist (delq item menulist))))
536 (if imenu-sort-function
537 (setq menulist (sort menulist imenu-sort-function)))
538 (if (> (length menulist) imenu-max-items)
539 (setq menulist
540 (mapcar
541 (lambda (menu)
542 (cons (format "From: %s" (caar menu)) menu))
543 (imenu--split menulist imenu-max-items))))
544 (cons title
545 (nconc (nreverse keep-at-top) menulist))))
547 ;;; Split up each long alist that are nested within ALIST
548 ;;; into nested alists.
549 (defun imenu--split-submenus (alist)
550 (mapcar (function
551 (lambda (elt)
552 (if (and (consp elt)
553 (stringp (car elt))
554 (listp (cdr elt)))
555 (imenu--split-menu (cdr elt) (car elt))
556 elt)))
557 alist))
559 ;;; Truncate all strings in MENULIST to imenu-max-item-length
560 (defun imenu--truncate-items (menulist)
561 (mapcar (function
562 (lambda (item)
563 (cond
564 ((consp (cdr item))
565 (imenu--truncate-items (cdr item)))
566 ;; truncate if necessary
567 ((and (numberp imenu-max-item-length)
568 (> (length (car item)) imenu-max-item-length))
569 (setcar item (substring (car item) 0 imenu-max-item-length))))))
570 menulist))
573 (defun imenu--make-index-alist (&optional noerror)
574 "Create an index-alist for the definitions in the current buffer.
576 Report an error if the list is empty unless NOERROR is supplied and
577 non-nil.
579 Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
580 Special elements look like (INDEX-NAME FUNCTION ARGUMENTS...).
581 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
582 The function `imenu--subalist-p' tests an element and returns t
583 if it is a sub-alist.
585 There is one simple element with negative POSITION; that's intended
586 as a way for the user to ask to recalculate the buffer's index alist."
587 (or (and imenu--index-alist
588 (or (not imenu-auto-rescan)
589 (and imenu-auto-rescan
590 (> (buffer-size) imenu-auto-rescan-maxout))))
591 ;; Get the index; truncate if necessary
592 (progn
593 (setq imenu--index-alist
594 (save-excursion
595 (save-restriction
596 (widen)
597 (funcall imenu-create-index-function))))
598 (imenu--truncate-items imenu--index-alist)))
599 (or imenu--index-alist noerror
600 (error "No items suitable for an index found in this buffer"))
601 (or imenu--index-alist
602 (setq imenu--index-alist (list nil)))
603 ;; Add a rescan option to the index.
604 (cons imenu--rescan-item imenu--index-alist))
606 ;;; Find all markers in alist and makes
607 ;;; them point nowhere.
608 ;;; The top-level call uses nil as the argument;
609 ;;; non-nil arguments are in recursivecalls.
610 (defvar imenu--cleanup-seen)
612 (defun imenu--cleanup (&optional alist)
613 ;; If alist is provided use that list.
614 ;; If not, empty the table of lists already seen
615 ;; and use imenu--index-alist.
616 (if alist
617 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
618 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
620 (and alist
621 (mapc
622 (lambda (item)
623 (cond
624 ((markerp (cdr item))
625 (set-marker (cdr item) nil))
626 ;; Don't process one alist twice.
627 ((memq (cdr item) imenu--cleanup-seen))
628 ((imenu--subalist-p item)
629 (imenu--cleanup (cdr item)))))
630 alist)
633 (defun imenu--create-keymap (title alist &optional cmd)
634 (list* 'keymap title
635 (mapcar
636 (lambda (item)
637 (list* (car item) (car item)
638 (cond
639 ((imenu--subalist-p item)
640 (imenu--create-keymap (car item) (cdr item) cmd))
642 `(lambda () (interactive)
643 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
644 alist)))
646 (defun imenu--in-alist (str alist)
647 "Check whether the string STR is contained in multi-level ALIST."
648 (let (elt head tail res)
649 (setq res nil)
650 (while alist
651 (setq elt (car alist)
652 tail (cdr elt)
653 alist (cdr alist)
654 head (car elt))
655 ;; A nested ALIST element looks like
656 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
657 ;; while a bottom-level element looks like
658 ;; (INDEX-NAME . INDEX-POSITION)
659 ;; We are only interested in the bottom-level elements, so we need to
660 ;; recurse if TAIL is a list.
661 (cond ((listp tail)
662 (if (setq res (imenu--in-alist str tail))
663 (setq alist nil)))
664 ((if imenu-name-lookup-function
665 (funcall imenu-name-lookup-function str head)
666 (string= str head))
667 (setq alist nil res elt))))
668 res))
670 (defvar imenu-syntax-alist nil
671 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
673 The car of the assocs may be either a character or a string and the
674 cdr is a syntax description appropriate for `modify-syntax-entry'. For
675 a string, all the characters in the string get the specified syntax.
677 This is typically used to give word syntax to characters which
678 normally have symbol syntax to simplify `imenu-expression'
679 and speed-up matching.")
680 ;;;###autoload
681 (make-variable-buffer-local 'imenu-syntax-alist)
683 (defun imenu-default-create-index-function ()
684 "*Wrapper for index searching functions.
686 Moves point to end of buffer and then repeatedly calls
687 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
688 Their results are gathered into an index alist."
689 ;; These should really be done by setting imenu-create-index-function
690 ;; in these major modes. But save that change for later.
691 (cond ((and imenu-prev-index-position-function
692 imenu-extract-index-name-function)
693 (let ((index-alist '())
694 prev-pos name)
695 (goto-char (point-max))
696 (imenu-progress-message prev-pos 0 t)
697 ;; Search for the function
698 (while (funcall imenu-prev-index-position-function)
699 (imenu-progress-message prev-pos nil t)
700 (save-excursion
701 (setq name (funcall imenu-extract-index-name-function)))
702 (and (stringp name)
703 ;; [ydi] updated for imenu-use-markers
704 (push (cons name (if imenu-use-markers (point-marker) (point)))
705 index-alist)))
706 (imenu-progress-message prev-pos 100 t)
707 index-alist))
708 ;; Use generic expression if possible.
709 ((and imenu-generic-expression)
710 (imenu--generic-function imenu-generic-expression))
712 (error "This buffer cannot use `imenu-default-create-index-function'"))))
714 ;; Not used and would require cl at run time
715 ;; (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
716 ;; ;; Takes a nested INDEX-ALIST and returns a flat index alist.
717 ;; ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
718 ;; ;; name and a space concatenated to the names of the children.
719 ;; ;; Third argument PREFIX is for internal use only.
720 ;; (mapcan
721 ;; (lambda (item)
722 ;; (let* ((name (car item))
723 ;; (pos (cdr item))
724 ;; (new-prefix (and concat-names
725 ;; (if prefix
726 ;; (concat prefix imenu-level-separator name)
727 ;; name))))
728 ;; (cond
729 ;; ((or (markerp pos) (numberp pos))
730 ;; (list (cons new-prefix pos)))
731 ;; (t
732 ;; (imenu--flatten-index-alist pos new-prefix)))))
733 ;; index-alist))
736 ;;; Generic index gathering function.
739 (defvar imenu-case-fold-search t
740 "Defines whether `imenu--generic-function' should fold case when matching.
742 This variable should be set (only) by initialization code
743 for modes which use `imenu--generic-function'. If it is not set, but
744 `font-lock-defaults' is set, then font-lock's setting is used.")
745 ;;;###autoload
746 (make-variable-buffer-local 'imenu-case-fold-search)
748 ;; Originally "Built on some ideas that Erik Naggum <erik@naggum.no>
749 ;; once posted to comp.emacs" but since substantially re-written.
750 (defun imenu--generic-function (patterns)
751 "Return an index of the current buffer as an alist.
753 PATTERNS is an alist with elements that look like this:
754 (MENU-TITLE REGEXP INDEX).
755 or like this:
756 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
757 with zero or more ARGUMENTS.
759 MENU-TITLE is a string used as the title for the submenu or nil if the
760 entries are not nested.
762 REGEXP is a regexp that should match a construct in the buffer that is
763 to be displayed in the menu; i.e., function or variable definitions,
764 etc. It contains a substring which is the name to appear in the
765 menu. See the info section on Regexps for more information.
767 INDEX points to the substring in REGEXP that contains the name (of the
768 function, variable or type) that is to appear in the menu.
770 See `lisp-imenu-generic-expression' for an example of PATTERNS.
772 Returns an index of the current buffer as an alist. The elements in
773 the alist look like:
774 (INDEX-NAME . INDEX-POSITION)
775 or like:
776 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
777 They may also be nested index alists like:
778 (INDEX-NAME . INDEX-ALIST)
779 depending on PATTERNS."
781 (let ((index-alist (list 'dummy))
782 prev-pos beg
783 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
784 (not (local-variable-p 'font-lock-defaults)))
785 imenu-case-fold-search
786 (nth 2 font-lock-defaults)))
787 (old-table (syntax-table))
788 (table (copy-syntax-table (syntax-table)))
789 (slist imenu-syntax-alist))
790 ;; Modify the syntax table used while matching regexps.
791 (dolist (syn slist)
792 ;; The character(s) to modify may be a single char or a string.
793 (if (numberp (car syn))
794 (modify-syntax-entry (car syn) (cdr syn) table)
795 (mapc (lambda (c)
796 (modify-syntax-entry c (cdr syn) table))
797 (car syn))))
798 (goto-char (point-max))
799 (imenu-progress-message prev-pos 0 t)
800 (unwind-protect ; for syntax table
801 (save-match-data
802 (set-syntax-table table)
803 ;; map over the elements of imenu-generic-expression
804 ;; (typically functions, variables ...)
805 (dolist (pat patterns)
806 (let ((menu-title (car pat))
807 (regexp (nth 1 pat))
808 (index (nth 2 pat))
809 (function (nth 3 pat))
810 (rest (nthcdr 4 pat))
812 ;; Go backwards for convenience of adding items in order.
813 (goto-char (point-max))
814 (while (re-search-backward regexp nil t)
815 (goto-char (match-end index))
816 (setq beg (match-beginning index))
817 (if (setq cs (save-match-data (comment-beginning)))
818 (goto-char cs) ; skip this one, it's in a comment
819 (goto-char beg)
820 (imenu-progress-message prev-pos nil t)
821 ;; Add this sort of submenu only when we've found an
822 ;; item for it, avoiding empty, duff menus.
823 (unless (assoc menu-title index-alist)
824 (push (list menu-title) index-alist))
825 (if imenu-use-markers
826 (setq beg (copy-marker beg)))
827 (let ((item
828 (if function
829 (nconc (list (match-string-no-properties index)
830 beg function)
831 rest)
832 (cons (match-string-no-properties index)
833 beg)))
834 ;; This is the desired submenu,
835 ;; starting with its title (or nil).
836 (menu (assoc menu-title index-alist)))
837 ;; Insert the item unless it is already present.
838 (unless (member item (cdr menu))
839 (setcdr menu
840 (cons item (cdr menu)))))))))
841 (set-syntax-table old-table)))
842 (imenu-progress-message prev-pos 100 t)
843 ;; Sort each submenu by position.
844 ;; This is in case one submenu gets items from two different regexps.
845 (dolist (item index-alist)
846 (when (listp item)
847 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
848 (let ((main-element (assq nil index-alist)))
849 (nconc (delq main-element (delq 'dummy index-alist))
850 (cdr main-element)))))
852 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
854 ;;; The main functions for this package!
856 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
858 ;; See also info-lookup-find-item
859 (defun imenu-find-default (guess completions)
860 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
861 (catch 'found
862 (let ((case-fold-search t))
863 (if (assoc guess completions) guess
864 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
865 (concat "\\`" (regexp-quote guess))
866 (concat (regexp-quote guess) "\\'")
867 (regexp-quote guess)))
868 (dolist (x completions)
869 (if (string-match re (car x)) (throw 'found (car x)))))))))
871 (defun imenu--completion-buffer (index-alist &optional prompt)
872 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
874 Return one of the entries in index-alist or nil."
875 ;; Create a list for this buffer only when needed.
876 (let ((name (thing-at-point 'symbol))
877 choice
878 (prepared-index-alist
879 (if (not imenu-space-replacement) index-alist
880 (mapcar
881 (lambda (item)
882 (cons (subst-char-in-string ?\ (aref imenu-space-replacement 0)
883 (car item))
884 (cdr item)))
885 index-alist))))
886 (when (stringp name)
887 (setq name (or (imenu-find-default name prepared-index-alist) name)))
888 (cond (prompt)
889 ((and name (imenu--in-alist name prepared-index-alist))
890 (setq prompt (format "Index item (default %s): " name)))
891 (t (setq prompt "Index item: ")))
892 (let ((minibuffer-setup-hook minibuffer-setup-hook))
893 ;; Display the completion buffer.
894 (if (not imenu-eager-completion-buffer)
895 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
896 (setq name (completing-read prompt
897 prepared-index-alist
898 nil t nil 'imenu--history-list name)))
900 (when (stringp name)
901 (setq choice (assoc name prepared-index-alist))
902 (if (imenu--subalist-p choice)
903 (imenu--completion-buffer (cdr choice) prompt)
904 choice))))
906 (defun imenu--mouse-menu (index-alist event &optional title)
907 "Let the user select from a buffer index from a mouse menu.
909 INDEX-ALIST is the buffer index and EVENT is a mouse event.
911 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
912 (setq index-alist (imenu--split-submenus index-alist))
913 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
914 (map (imenu--create-keymap (car menu)
915 (cdr (if (< 1 (length (cdr menu)))
916 menu
917 (car (cdr menu)))))))
918 (popup-menu map event)))
920 (defun imenu-choose-buffer-index (&optional prompt alist)
921 "Let the user select from a buffer index and return the chosen index.
923 If the user originally activated this function with the mouse, a mouse
924 menu is used. Otherwise a completion buffer is used and the user is
925 prompted with PROMPT.
927 If you call this function with index alist ALIST, then it lets the user
928 select from ALIST.
930 With no index alist ALIST, it calls `imenu--make-index-alist' to
931 create the index alist.
933 If `imenu-use-popup-menu' is non-nil, then the
934 completion buffer is always used, no matter if the mouse was used or
935 not.
937 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
938 (let (index-alist
939 (mouse-triggered (listp last-nonmenu-event))
940 (result t))
941 ;; If selected by mouse, see to that the window where the mouse is
942 ;; really is selected.
943 (and mouse-triggered
944 (not (equal last-nonmenu-event '(menu-bar)))
945 (let ((window (posn-window (event-start last-nonmenu-event))))
946 (or (framep window) (null window) (select-window window))))
947 ;; Create a list for this buffer only when needed.
948 (while (eq result t)
949 (setq index-alist (if alist alist (imenu--make-index-alist)))
950 (setq result
951 (if (and imenu-use-popup-menu
952 (or (eq imenu-use-popup-menu t) mouse-triggered))
953 (imenu--mouse-menu index-alist last-nonmenu-event)
954 (imenu--completion-buffer index-alist prompt)))
955 (and (equal result imenu--rescan-item)
956 (imenu--cleanup)
957 (setq result t imenu--index-alist nil)))
958 result))
960 ;;;###autoload
961 (defun imenu-add-to-menubar (name)
962 "Add an `imenu' entry to the menu bar for the current buffer.
963 NAME is a string used to name the menu bar item.
964 See the command `imenu' for more information."
965 (interactive "sImenu menu item name: ")
966 (if (or (and imenu-prev-index-position-function
967 imenu-extract-index-name-function)
968 imenu-generic-expression
969 (not (eq imenu-create-index-function
970 'imenu-default-create-index-function)))
971 (let ((newmap (make-sparse-keymap)))
972 (set-keymap-parent newmap (current-local-map))
973 (setq imenu--last-menubar-index-alist nil)
974 (define-key newmap [menu-bar index]
975 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
976 (use-local-map newmap)
977 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
978 (error "The mode `%s' does not support Imenu" mode-name)))
980 ;;;###autoload
981 (defun imenu-add-menubar-index ()
982 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
984 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
985 (interactive)
986 (imenu-add-to-menubar "Index"))
988 (defvar imenu-buffer-menubar nil)
990 (defvar imenu-menubar-modified-tick 0
991 "The value of (buffer-modified-tick) as of last call to `imenu-update-menubar'.")
992 (make-variable-buffer-local 'imenu-menubar-modified-tick)
994 (defun imenu-update-menubar ()
995 (when (and (current-local-map)
996 (keymapp (lookup-key (current-local-map) [menu-bar index]))
997 (not (eq (buffer-modified-tick)
998 imenu-menubar-modified-tick)))
999 (setq imenu-menubar-modified-tick (buffer-modified-tick))
1000 (let ((index-alist (imenu--make-index-alist t)))
1001 ;; Don't bother updating if the index-alist has not changed
1002 ;; since the last time we did it.
1003 (unless (equal index-alist imenu--last-menubar-index-alist)
1004 (let (menu menu1 old)
1005 (setq imenu--last-menubar-index-alist index-alist)
1006 (setq index-alist (imenu--split-submenus index-alist))
1007 (setq menu (imenu--split-menu index-alist
1008 (buffer-name)))
1009 (setq menu1 (imenu--create-keymap (car menu)
1010 (cdr (if (< 1 (length (cdr menu)))
1011 menu
1012 (car (cdr menu))))
1013 'imenu--menubar-select))
1014 (setq old (lookup-key (current-local-map) [menu-bar index]))
1015 (setcdr old (cdr menu1)))))))
1017 (defun imenu--menubar-select (item)
1018 "Use Imenu to select the function or variable named in this menu ITEM."
1019 (if (equal item imenu--rescan-item)
1020 (progn
1021 (imenu--cleanup)
1022 ;; Make sure imenu-update-menubar redoes everything.
1023 (setq imenu-menubar-modified-tick -1)
1024 (setq imenu--index-alist nil)
1025 (setq imenu--last-menubar-index-alist nil)
1026 (imenu-update-menubar)
1028 (imenu item)
1029 nil))
1031 (defun imenu-default-goto-function (name position &optional rest)
1032 "Move to the given position.
1034 NAME is ignored. POSITION is where to move. REST is also ignored.
1035 The ignored args just make this function have the same interface as a
1036 function placed in a special index-item."
1037 (if (or (< position (point-min))
1038 (> position (point-max)))
1039 ;; widen if outside narrowing
1040 (widen))
1041 (goto-char position))
1043 ;;;###autoload
1044 (defun imenu (index-item)
1045 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1046 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1047 for more information."
1048 (interactive (list (imenu-choose-buffer-index)))
1049 ;; Convert a string to an alist element.
1050 (if (stringp index-item)
1051 (setq index-item (assoc index-item (imenu--make-index-alist))))
1052 (when index-item
1053 (push-mark)
1054 (let* ((is-special-item (listp (cdr index-item)))
1055 (function
1056 (if is-special-item
1057 (nth 2 index-item) imenu-default-goto-function))
1058 (position (if is-special-item
1059 (cadr index-item) (cdr index-item)))
1060 (rest (if is-special-item (cddr index-item))))
1061 (apply function (car index-item) position rest))
1062 (run-hooks 'imenu-after-jump-hook)))
1064 (dolist (mess
1065 '("^No items suitable for an index found in this buffer$"
1066 "^This buffer cannot use `imenu-default-create-index-function'$"
1067 "^The mode `.*' does not support Imenu$"))
1068 (add-to-list 'debug-ignored-errors mess))
1070 (provide 'imenu)
1072 ;; arch-tag: 98a2f5f5-4b91-4704-b18c-3aacf77d77a7
1073 ;;; imenu.el ends here