Replace MenuHandle and GetMenuHandle with MenuRef and
[emacs.git] / lisp / imenu.el
blobee7f3432c4d3c3487e3bbee92d38a1d99f5909bf
1 ;;; imenu.el --- framework for mode-specific buffer indexes
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 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 3, 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., 51 Franklin Street, Fifth Floor,
27 ;; Boston, MA 02110-1301, 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 (eval-when-compile (require 'cl))
67 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
68 ;;;
69 ;;; Customizable variables
70 ;;;
71 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
73 (defgroup imenu nil
74 "Mode-specific buffer indexes."
75 :group 'matching
76 :group 'frames
77 :group 'convenience
78 :link '(custom-manual "(elisp)Imenu"))
80 (defcustom imenu-use-markers t
81 "*Non-nil means use markers instead of integers for Imenu buffer positions.
83 Setting this to nil makes Imenu work a little faster but editing the
84 buffer will make the generated index positions wrong.
86 This might not yet be honored by all index-building functions."
87 :type 'boolean
88 :group 'imenu)
91 (defcustom imenu-max-item-length 60
92 "*If a number, truncate Imenu entries to that length."
93 :type '(choice integer
94 (const :tag "Unlimited"))
95 :group 'imenu)
97 (defcustom imenu-auto-rescan nil
98 "*Non-nil means Imenu should always rescan the buffers."
99 :type 'boolean
100 :group 'imenu)
102 (defcustom imenu-auto-rescan-maxout 60000
103 "*Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
104 This variable is buffer-local."
105 :type 'integer
106 :group 'imenu)
108 (defvar imenu-always-use-completion-buffer-p nil)
109 (make-obsolete-variable 'imenu-always-use-completion-buffer-p
110 'imenu-use-popup-menu "22.1")
112 (defcustom imenu-use-popup-menu
113 (if imenu-always-use-completion-buffer-p
114 (not (eq imenu-always-use-completion-buffer-p 'never))
115 'on-mouse)
116 "Use a popup menu rather than a minibuffer prompt.
117 If nil, always use a minibuffer prompt.
118 If t, always use a popup menu,
119 If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
120 :type '(choice (const :tag "On Mouse" on-mouse)
121 (const :tag "Never" nil)
122 (other :tag "Always" t))
123 :group 'imenu)
125 (defcustom imenu-eager-completion-buffer
126 (not (eq imenu-always-use-completion-buffer-p 'never))
127 "If non-nil, eagerly popup the completion buffer."
128 :type 'boolean
129 :group 'imenu
130 :version "22.1")
132 (defcustom imenu-after-jump-hook nil
133 "*Hooks called after jumping to a place in the buffer.
135 Useful things to use here include `reposition-window', `recenter', and
136 \(lambda () (recenter 0)) to show at top of screen."
137 :type 'hook
138 :group 'imenu)
140 ;;;###autoload
141 (defcustom imenu-sort-function nil
142 "*The function to use for sorting the index mouse-menu.
144 Affects only the mouse index menu.
146 Set this to nil if you don't want any sorting (faster).
147 The items in the menu are then presented in the order they were found
148 in the buffer.
150 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
152 The function should take two arguments and return t if the first
153 element should come before the second. The arguments are cons cells;
154 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
155 :type '(choice (const :tag "No sorting" nil)
156 (const :tag "Sort by name" imenu--sort-by-name)
157 (function :tag "Another function"))
158 :group 'imenu)
160 (defcustom imenu-max-items 25
161 "*Maximum number of elements in a mouse menu for Imenu."
162 :type 'integer
163 :group 'imenu)
165 ;; No longer used. KFS 2004-10-27
166 ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
167 ;; "*Progress message during the index scanning of the buffer.
168 ;; If non-nil, user gets a message during the scanning of the buffer.
170 ;; Relevant only if the mode-specific function that creates the buffer
171 ;; index use `imenu-progress-message', and not useful if that is fast, in
172 ;; which case you might as well set this to nil."
173 ;; :type '(choice string
174 ;; (const :tag "None" nil))
175 ;; :group 'imenu)
177 (defcustom imenu-space-replacement "."
178 "*The replacement string for spaces in index names.
179 Used when presenting the index in a completion buffer to make the
180 names work as tokens."
181 :type '(choice string (const nil))
182 :group 'imenu)
184 (defcustom imenu-level-separator ":"
185 "*The separator between index names of different levels.
186 Used for making mouse-menu titles and for flattening nested indexes
187 with name concatenation."
188 :type 'string
189 :group 'imenu)
191 ;;;###autoload
192 (defvar imenu-generic-expression nil
193 "The regex pattern to use for creating a buffer index.
195 If non-nil this pattern is passed to `imenu--generic-function' to
196 create a buffer index. Look there for the documentation of this
197 pattern's structure.
199 For example, see the value of `fortran-imenu-generic-expression' used by
200 `fortran-mode' with `imenu-syntax-alist' set locally to give the
201 characters which normally have \"symbol\" syntax \"word\" syntax
202 during matching.")
204 ;;;###autoload
205 (make-variable-buffer-local 'imenu-generic-expression)
207 ;;;; Hooks
209 ;;;###autoload
210 (defvar imenu-create-index-function 'imenu-default-create-index-function
211 "The function to use for creating an index alist of the current buffer.
213 It should be a function that takes no arguments and returns
214 an index alist of the current buffer. The function is
215 called within a `save-excursion'.
217 See `imenu--index-alist' for the format of the buffer index alist.")
218 ;;;###autoload
219 (make-variable-buffer-local 'imenu-create-index-function)
221 ;;;###autoload
222 (defvar imenu-prev-index-position-function 'beginning-of-defun
223 "Function for finding the next index position.
225 If `imenu-create-index-function' is set to
226 `imenu-default-create-index-function', then you must set this variable
227 to a function that will find the next index, looking backwards in the
228 file.
230 The function should leave point at the place to be connected to the
231 index and it should return nil when it doesn't find another index.")
232 ;;;###autoload
233 (make-variable-buffer-local 'imenu-prev-index-position-function)
235 ;;;###autoload
236 (defvar imenu-extract-index-name-function nil
237 "Function for extracting the index item name, given a position.
239 This function is called after `imenu-prev-index-position-function'
240 finds a position for an index item, with point at that position.
241 It should return the name for that index item.")
242 ;;;###autoload
243 (make-variable-buffer-local 'imenu-extract-index-name-function)
245 ;;;###autoload
246 (defvar imenu-name-lookup-function nil
247 "Function to compare string with index item.
249 This function will be called with two strings, and should return
250 non-nil if they match.
252 If nil, comparison is done with `string='.
253 Set this to some other function for more advanced comparisons,
254 such as \"begins with\" or \"name matches and number of
255 arguments match\".")
256 ;;;###autoload
257 (make-variable-buffer-local 'imenu-name-lookup-function)
259 ;;;###autoload
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.")
263 ;;;###autoload
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
274 ;; is calculated.
275 ;; PREVPOS is the variable in which we store the last position displayed.
276 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
278 ;; Made obsolete/empty, as computers are now faster than the eye, and
279 ;; it had problems updating the messages correctly, and could shadow
280 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
282 ;; `(and
283 ;; imenu-scanning-message
284 ;; (let ((pos ,(if relpos
285 ;; relpos
286 ;; `(imenu--relative-position ,reverse))))
287 ;; (if ,(if relpos t
288 ;; `(> pos (+ 5 ,prevpos)))
289 ;; (progn
290 ;; (message imenu-scanning-message pos)
291 ;; (setq ,prevpos pos)))))
295 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
296 ;;;;
297 ;;;; Some examples of functions utilizing the framework of this
298 ;;;; package.
299 ;;;;
300 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
302 ;; FIXME: This is the only imenu-example-* definition that's actually used,
303 ;; and it seems to only be used by cperl-mode.el. We should just move it to
304 ;; cperl-mode.el and remove the rest.
305 (defun imenu-example--name-and-position ()
306 "Return the current/previous sexp and its (beginning) location.
307 Don't move point."
308 (save-excursion
309 (forward-sexp -1)
310 ;; [ydi] modified for imenu-use-markers
311 (let ((beg (if imenu-use-markers (point-marker) (point)))
312 (end (progn (forward-sexp) (point))))
313 (cons (buffer-substring beg end)
314 beg))))
317 ;;; Lisp
320 (defun imenu-example--lisp-extract-index-name ()
321 ;; Example of a candidate for `imenu-extract-index-name-function'.
322 ;; This will generate a flat index of definitions in a lisp file.
323 (save-match-data
324 (and (looking-at "(def")
325 (condition-case nil
326 (progn
327 (down-list 1)
328 (forward-sexp 2)
329 (let ((beg (point))
330 (end (progn (forward-sexp -1) (point))))
331 (buffer-substring beg end)))
332 (error nil)))))
334 (defun imenu-example--create-lisp-index ()
335 ;; Example of a candidate for `imenu-create-index-function'.
336 ;; It will generate a nested index of definitions.
337 (let ((index-alist '())
338 (index-var-alist '())
339 (index-type-alist '())
340 (index-unknown-alist '())
341 prev-pos)
342 (goto-char (point-max))
343 (imenu-progress-message prev-pos 0)
344 ;; Search for the function
345 (while (beginning-of-defun)
346 (imenu-progress-message prev-pos nil t)
347 (save-match-data
348 (and (looking-at "(def")
349 (save-excursion
350 (down-list 1)
351 (cond
352 ((looking-at "def\\(var\\|const\\)")
353 (forward-sexp 2)
354 (push (imenu-example--name-and-position)
355 index-var-alist))
356 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
357 (forward-sexp 2)
358 (push (imenu-example--name-and-position)
359 index-alist))
360 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
361 (forward-sexp 2)
362 (if (= (char-after (1- (point))) ?\))
363 (progn
364 (forward-sexp -1)
365 (down-list 1)
366 (forward-sexp 1)))
367 (push (imenu-example--name-and-position)
368 index-type-alist))
370 (forward-sexp 2)
371 (push (imenu-example--name-and-position)
372 index-unknown-alist)))))))
373 (imenu-progress-message prev-pos 100)
374 (and index-var-alist
375 (push (cons "Variables" index-var-alist)
376 index-alist))
377 (and index-type-alist
378 (push (cons "Types" index-type-alist)
379 index-alist))
380 (and index-unknown-alist
381 (push (cons "Syntax-unknown" index-unknown-alist)
382 index-alist))
383 index-alist))
385 ;; Regular expression to find C functions
386 (defvar imenu-example--function-name-regexp-c
387 (concat
388 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
389 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
390 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
391 "\\([*&]+[ \t]*\\)?" ; pointer
392 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
395 (defun imenu-example--create-c-index (&optional regexp)
396 (let ((index-alist '())
397 prev-pos char)
398 (goto-char (point-min))
399 (imenu-progress-message prev-pos 0)
400 ;; Search for the function
401 (save-match-data
402 (while (re-search-forward
403 (or regexp imenu-example--function-name-regexp-c)
404 nil t)
405 (imenu-progress-message prev-pos)
406 (backward-up-list 1)
407 (save-excursion
408 (goto-char (scan-sexps (point) 1))
409 (setq char (following-char)))
410 ;; Skip this function name if it is a prototype declaration.
411 (if (not (eq char ?\;))
412 (push (imenu-example--name-and-position) index-alist))))
413 (imenu-progress-message prev-pos 100)
414 (nreverse index-alist)))
417 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
419 ;;; Internal variables
421 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
423 ;; The item to use in the index for rescanning the buffer.
424 (defconst imenu--rescan-item '("*Rescan*" . -99))
426 ;; The latest buffer index.
427 ;; Buffer local.
428 (defvar imenu--index-alist nil
429 "The buffer index alist computed for this buffer in Imenu.
431 Simple elements in the alist look like (INDEX-NAME . POSITION).
432 POSITION is the buffer position of the item; to go to the item
433 is simply to move point to that position.
435 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
436 To \"go to\" a special element means applying FUNCTION
437 to INDEX-NAME, POSITION, and the ARGUMENTS.
439 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
440 The function `imenu--subalist-p' tests an element and returns t
441 if it is a sub-alist.
443 There is one simple element with negative POSITION; selecting that
444 element recalculates the buffer's index alist.")
446 (make-variable-buffer-local 'imenu--index-alist)
448 (defvar imenu--last-menubar-index-alist nil
449 "The latest buffer index alist used to update the menu bar menu.")
451 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
453 ;; History list for 'jump-to-function-in-buffer'.
454 ;; Making this buffer local caused it not to work!
455 (defvar imenu--history-list nil)
457 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
459 ;;; Internal support functions
461 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
464 ;;; Sort function
465 ;;; Sorts the items depending on their index name.
466 ;;; An item looks like (NAME . POSITION).
468 (defun imenu--sort-by-name (item1 item2)
469 (string-lessp (car item1) (car item2)))
471 (defun imenu--sort-by-position (item1 item2)
472 (< (cdr item1) (cdr item2)))
474 (defun imenu--relative-position (&optional reverse)
475 ;; Support function to calculate relative position in buffer
476 ;; Beginning of buffer is 0 and end of buffer is 100
477 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
478 (let ((pos (point))
479 (total (buffer-size)))
480 (and reverse (setq pos (- total pos)))
481 (if (> total 50000)
482 ;; Avoid overflow from multiplying by 100!
483 (/ (1- pos) (max (/ total 100) 1))
484 (/ (* 100 (1- pos)) (max total 1)))))
486 ;; Split LIST into sublists of max length N.
487 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
488 (defun imenu--split (list n)
489 (let ((remain list)
490 (result '())
491 (sublist '())
492 (i 0))
493 (while remain
494 (push (pop remain) sublist)
495 (incf i)
496 (and (= i n)
497 ;; We have finished a sublist
498 (progn (push (nreverse sublist) result)
499 (setq i 0)
500 (setq sublist '()))))
501 ;; There might be a sublist (if the length of LIST mod n is != 0)
502 ;; that has to be added to the result list.
503 (and sublist
504 (push (nreverse sublist) result))
505 (nreverse result)))
507 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
508 ;;; In any case, add TITLE to the front of the alist.
509 (defun imenu--split-menu (menulist title)
510 (let (keep-at-top tail)
511 (if (memq imenu--rescan-item menulist)
512 (setq keep-at-top (cons imenu--rescan-item nil)
513 menulist (delq imenu--rescan-item menulist)))
514 (setq tail menulist)
515 (dolist (item tail)
516 (when (imenu--subalist-p item)
517 (push item keep-at-top)
518 (setq menulist (delq item menulist))))
519 (if imenu-sort-function
520 (setq menulist (sort (copy-sequence menulist) imenu-sort-function)))
521 (if (> (length menulist) imenu-max-items)
522 (setq menulist
523 (mapcar
524 (lambda (menu)
525 (cons (format "From: %s" (caar menu)) menu))
526 (imenu--split menulist imenu-max-items))))
527 (cons title
528 (nconc (nreverse keep-at-top) menulist))))
530 ;;; Split up each long alist that are nested within ALIST
531 ;;; into nested alists.
532 (defun imenu--split-submenus (alist)
533 (mapcar (function
534 (lambda (elt)
535 (if (and (consp elt)
536 (stringp (car elt))
537 (listp (cdr elt)))
538 (imenu--split-menu (cdr elt) (car elt))
539 elt)))
540 alist))
542 ;;; Truncate all strings in MENULIST to imenu-max-item-length
543 (defun imenu--truncate-items (menulist)
544 (mapcar (function
545 (lambda (item)
546 (cond
547 ((consp (cdr item))
548 (imenu--truncate-items (cdr item)))
549 ;; truncate if necessary
550 ((and (numberp imenu-max-item-length)
551 (> (length (car item)) imenu-max-item-length))
552 (setcar item (substring (car item) 0 imenu-max-item-length))))))
553 menulist))
556 (defun imenu--make-index-alist (&optional noerror)
557 "Create an index alist for the definitions in the current buffer.
558 This works by using the hook function `imenu-create-index-function'.
559 Report an error if the list is empty unless NOERROR is supplied and
560 non-nil.
562 See `imenu--index-alist' for the format of the 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
568 (progn
569 (setq imenu--index-alist
570 (save-excursion
571 (save-restriction
572 (widen)
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.
592 (if alist
593 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
594 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
596 (and alist
597 (mapc
598 (lambda (item)
599 (cond
600 ((markerp (cdr item))
601 (set-marker (cdr item) nil))
602 ;; Don't process one alist twice.
603 ((memq (cdr item) imenu--cleanup-seen))
604 ((imenu--subalist-p item)
605 (imenu--cleanup (cdr item)))))
606 alist)
609 (defun imenu--create-keymap (title alist &optional cmd)
610 (list* 'keymap title
611 (mapcar
612 (lambda (item)
613 (list* (car item) (car item)
614 (cond
615 ((imenu--subalist-p item)
616 (imenu--create-keymap (car item) (cdr item) cmd))
618 `(lambda () (interactive)
619 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
620 alist)))
622 (defun imenu--in-alist (str alist)
623 "Check whether the string STR is contained in multi-level ALIST."
624 (let (elt head tail res)
625 (setq res nil)
626 (while alist
627 (setq elt (car alist)
628 tail (cdr elt)
629 alist (cdr alist)
630 head (car elt))
631 ;; A nested ALIST element looks like
632 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
633 ;; while a bottom-level element looks like
634 ;; (INDEX-NAME . INDEX-POSITION)
635 ;; We are only interested in the bottom-level elements, so we need to
636 ;; recurse if TAIL is a list.
637 (cond ((listp tail)
638 (if (setq res (imenu--in-alist str tail))
639 (setq alist nil)))
640 ((if imenu-name-lookup-function
641 (funcall imenu-name-lookup-function str head)
642 (string= str head))
643 (setq alist nil res elt))))
644 res))
646 (defvar imenu-syntax-alist nil
647 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
649 The car of the assocs may be either a character or a string and the
650 cdr is a syntax description appropriate for `modify-syntax-entry'. For
651 a string, all the characters in the string get the specified syntax.
653 This is typically used to give word syntax to characters which
654 normally have symbol syntax to simplify `imenu-expression'
655 and speed-up matching.")
656 ;;;###autoload
657 (make-variable-buffer-local 'imenu-syntax-alist)
659 (defun imenu-default-create-index-function ()
660 "*Default function to create an index alist of the current buffer.
662 The most general method is to move point to end of buffer, then repeatedly call
663 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
664 All the results returned by the latter are gathered into an index alist.
665 This method is used if those two variables are non-nil.
667 The alternate method, which is the one most often used, is to call
668 `imenu--generic-function' with `imenu-generic-expression' as argument."
669 ;; These should really be done by setting imenu-create-index-function
670 ;; in these major modes. But save that change for later.
671 (cond ((and imenu-prev-index-position-function
672 imenu-extract-index-name-function)
673 (let ((index-alist '())
674 prev-pos name)
675 (goto-char (point-max))
676 (imenu-progress-message prev-pos 0 t)
677 ;; Search for the function
678 (while (funcall imenu-prev-index-position-function)
679 (imenu-progress-message prev-pos nil t)
680 (save-excursion
681 (setq name (funcall imenu-extract-index-name-function)))
682 (and (stringp name)
683 ;; [ydi] updated for imenu-use-markers
684 (push (cons name (if imenu-use-markers (point-marker) (point)))
685 index-alist)))
686 (imenu-progress-message prev-pos 100 t)
687 index-alist))
688 ;; Use generic expression if possible.
689 ((and imenu-generic-expression)
690 (imenu--generic-function imenu-generic-expression))
692 (error "This buffer cannot use `imenu-default-create-index-function'"))))
695 ;;; Generic index gathering function.
698 (defvar imenu-case-fold-search t
699 "Defines whether `imenu--generic-function' should fold case when matching.
701 This variable should be set (only) by initialization code
702 for modes which use `imenu--generic-function'. If it is not set, but
703 `font-lock-defaults' is set, then font-lock's setting is used.")
704 ;;;###autoload
705 (make-variable-buffer-local 'imenu-case-fold-search)
707 ;; This function can be called with quitting disabled,
708 ;; so it needs to be careful never to loop!
709 (defun imenu--generic-function (patterns)
710 "Return an index alist of the current buffer based on PATTERNS.
712 PATTERNS is an alist with elements that look like this:
713 (MENU-TITLE REGEXP INDEX)
714 or like this:
715 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
716 with zero or more ARGUMENTS. The former format creates a simple
717 element in the index alist when it matches; the latter creates a
718 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
719 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
721 MENU-TITLE is a string used as the title for the submenu or nil
722 if the entries are not nested.
724 REGEXP is a regexp that should match a construct in the buffer
725 that is to be displayed in the menu; i.e., function or variable
726 definitions, etc. It contains a substring which is the name to
727 appear in the menu. See the info section on Regexps for more
728 information. REGEXP may also be a function, called without
729 arguments. It is expected to search backwards. It shall return
730 true and set `match-data' if it finds another element.
732 INDEX points to the substring in REGEXP that contains the
733 name (of the function, variable or type) that is to appear in the
734 menu.
736 The variable `imenu-case-fold-search' determines whether or not the
737 regexp matches are case sensitive, and `imenu-syntax-alist' can be
738 used to alter the syntax table for the search.
740 See `lisp-imenu-generic-expression' for an example of PATTERNS.
742 Returns an index of the current buffer as an alist. The elements in
743 the alist look like:
744 (INDEX-NAME . INDEX-POSITION)
745 or like:
746 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
747 They may also be nested index alists like:
748 (INDEX-NAME . INDEX-ALIST)
749 depending on PATTERNS."
751 (let ((index-alist (list 'dummy))
752 prev-pos
753 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
754 (not (local-variable-p 'font-lock-defaults)))
755 imenu-case-fold-search
756 (nth 2 font-lock-defaults)))
757 (old-table (syntax-table))
758 (table (copy-syntax-table (syntax-table)))
759 (slist imenu-syntax-alist))
760 ;; Modify the syntax table used while matching regexps.
761 (dolist (syn slist)
762 ;; The character(s) to modify may be a single char or a string.
763 (if (numberp (car syn))
764 (modify-syntax-entry (car syn) (cdr syn) table)
765 (mapc (lambda (c)
766 (modify-syntax-entry c (cdr syn) table))
767 (car syn))))
768 (goto-char (point-max))
769 (imenu-progress-message prev-pos 0 t)
770 (unwind-protect ; for syntax table
771 (save-match-data
772 (set-syntax-table table)
774 ;; map over the elements of imenu-generic-expression
775 ;; (typically functions, variables ...)
776 (dolist (pat patterns)
777 (let ((menu-title (car pat))
778 (regexp (nth 1 pat))
779 (index (nth 2 pat))
780 (function (nth 3 pat))
781 (rest (nthcdr 4 pat))
782 start beg)
783 ;; Go backwards for convenience of adding items in order.
784 (goto-char (point-max))
785 (while (and (if (functionp regexp)
786 (funcall regexp)
787 (re-search-backward regexp nil t))
788 ;; Exit the loop if we get an empty match,
789 ;; because it means a bad regexp was specified.
790 (not (= (match-beginning 0) (match-end 0))))
791 (setq start (point))
792 ;; Record the start of the line in which the match starts.
793 ;; That's the official position of this definition.
794 (goto-char (match-beginning index))
795 (beginning-of-line)
796 (setq beg (point))
797 (imenu-progress-message prev-pos nil t)
798 ;; Add this sort of submenu only when we've found an
799 ;; item for it, avoiding empty, duff menus.
800 (unless (assoc menu-title index-alist)
801 (push (list menu-title) index-alist))
802 (if imenu-use-markers
803 (setq beg (copy-marker beg)))
804 (let ((item
805 (if function
806 (nconc (list (match-string-no-properties index)
807 beg function)
808 rest)
809 (cons (match-string-no-properties index)
810 beg)))
811 ;; This is the desired submenu,
812 ;; starting with its title (or nil).
813 (menu (assoc menu-title index-alist)))
814 ;; Insert the item unless it is already present.
815 (unless (member item (cdr menu))
816 (setcdr menu
817 (cons item (cdr menu)))))
818 ;; Go to the start of the match, to make sure we
819 ;; keep making progress backwards.
820 (goto-char start))))
821 (set-syntax-table old-table)))
822 (imenu-progress-message prev-pos 100 t)
823 ;; Sort each submenu by position.
824 ;; This is in case one submenu gets items from two different regexps.
825 (dolist (item index-alist)
826 (when (listp item)
827 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
828 (let ((main-element (assq nil index-alist)))
829 (nconc (delq main-element (delq 'dummy index-alist))
830 (cdr main-element)))))
832 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
834 ;;; The main functions for this package!
836 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
838 ;; See also info-lookup-find-item
839 (defun imenu-find-default (guess completions)
840 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
841 (catch 'found
842 (let ((case-fold-search t))
843 (if (assoc guess completions) guess
844 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
845 (concat "\\`" (regexp-quote guess))
846 (concat (regexp-quote guess) "\\'")
847 (regexp-quote guess)))
848 (dolist (x completions)
849 (if (string-match re (car x)) (throw 'found (car x)))))))))
851 (defun imenu--completion-buffer (index-alist &optional prompt)
852 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
854 Return one of the entries in index-alist or nil."
855 ;; Create a list for this buffer only when needed.
856 (let ((name (thing-at-point 'symbol))
857 choice
858 (prepared-index-alist
859 (if (not imenu-space-replacement) index-alist
860 (mapcar
861 (lambda (item)
862 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
863 (car item))
864 (cdr item)))
865 index-alist))))
866 (when (stringp name)
867 (setq name (or (imenu-find-default name prepared-index-alist) name)))
868 (cond (prompt)
869 ((and name (imenu--in-alist name prepared-index-alist))
870 (setq prompt (format "Index item (default %s): " name)))
871 (t (setq prompt "Index item: ")))
872 (let ((minibuffer-setup-hook minibuffer-setup-hook))
873 ;; Display the completion buffer.
874 (if (not imenu-eager-completion-buffer)
875 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
876 (setq name (completing-read prompt
877 prepared-index-alist
878 nil t nil 'imenu--history-list name)))
880 (when (stringp name)
881 (setq choice (assoc name prepared-index-alist))
882 (if (imenu--subalist-p choice)
883 (imenu--completion-buffer (cdr choice) prompt)
884 choice))))
886 (defun imenu--mouse-menu (index-alist event &optional title)
887 "Let the user select from a buffer index from a mouse menu.
889 INDEX-ALIST is the buffer index and EVENT is a mouse event.
891 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
892 (setq index-alist (imenu--split-submenus index-alist))
893 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
894 (map (imenu--create-keymap (car menu)
895 (cdr (if (< 1 (length (cdr menu)))
896 menu
897 (car (cdr menu)))))))
898 (popup-menu map event)))
900 (defun imenu-choose-buffer-index (&optional prompt alist)
901 "Let the user select from a buffer index and return the chosen index.
903 If the user originally activated this function with the mouse, a mouse
904 menu is used. Otherwise a completion buffer is used and the user is
905 prompted with PROMPT.
907 If you call this function with index alist ALIST, then it lets the user
908 select from ALIST.
910 With no index alist ALIST, it calls `imenu--make-index-alist' to
911 create the index alist.
913 If `imenu-use-popup-menu' is nil, then the completion buffer
914 is always used, no matter if the mouse was used or not.
916 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
917 (let (index-alist
918 (mouse-triggered (listp last-nonmenu-event))
919 (result t))
920 ;; If selected by mouse, see to that the window where the mouse is
921 ;; really is selected.
922 (and mouse-triggered
923 (not (equal last-nonmenu-event '(menu-bar)))
924 (let ((window (posn-window (event-start last-nonmenu-event))))
925 (or (framep window) (null window) (select-window window))))
926 ;; Create a list for this buffer only when needed.
927 (while (eq result t)
928 (setq index-alist (if alist alist (imenu--make-index-alist)))
929 (setq result
930 (if (and imenu-use-popup-menu
931 (or (eq imenu-use-popup-menu t) mouse-triggered))
932 (imenu--mouse-menu index-alist last-nonmenu-event)
933 (imenu--completion-buffer index-alist prompt)))
934 (and (equal result imenu--rescan-item)
935 (imenu--cleanup)
936 (setq result t imenu--index-alist nil)))
937 result))
939 ;;;###autoload
940 (defun imenu-add-to-menubar (name)
941 "Add an `imenu' entry to the menu bar for the current buffer.
942 NAME is a string used to name the menu bar item.
943 See the command `imenu' for more information."
944 (interactive "sImenu menu item name: ")
945 (if (or (and imenu-prev-index-position-function
946 imenu-extract-index-name-function)
947 imenu-generic-expression
948 (not (eq imenu-create-index-function
949 'imenu-default-create-index-function)))
950 (let ((newmap (make-sparse-keymap)))
951 (set-keymap-parent newmap (current-local-map))
952 (setq imenu--last-menubar-index-alist nil)
953 (define-key newmap [menu-bar index]
954 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
955 (use-local-map newmap)
956 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
957 (error "The mode `%s' does not support Imenu" mode-name)))
959 ;;;###autoload
960 (defun imenu-add-menubar-index ()
961 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
963 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
964 (interactive)
965 (imenu-add-to-menubar "Index"))
967 (defvar imenu-buffer-menubar nil)
969 (defvar imenu-menubar-modified-tick 0
970 "The value of (buffer-chars-modified-tick) as of the last call
971 to `imenu-update-menubar'.")
972 (make-variable-buffer-local 'imenu-menubar-modified-tick)
974 (defun imenu-update-menubar ()
975 (when (and (current-local-map)
976 (keymapp (lookup-key (current-local-map) [menu-bar index]))
977 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
978 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
979 (let ((index-alist (imenu--make-index-alist t)))
980 ;; Don't bother updating if the index-alist has not changed
981 ;; since the last time we did it.
982 (unless (equal index-alist imenu--last-menubar-index-alist)
983 (let (menu menu1 old)
984 (setq imenu--last-menubar-index-alist index-alist)
985 (setq index-alist (imenu--split-submenus index-alist))
986 (setq menu (imenu--split-menu index-alist
987 (buffer-name)))
988 (setq menu1 (imenu--create-keymap (car menu)
989 (cdr (if (< 1 (length (cdr menu)))
990 menu
991 (car (cdr menu))))
992 'imenu--menubar-select))
993 (setq old (lookup-key (current-local-map) [menu-bar index]))
994 (setcdr old (cdr menu1)))))))
996 (defun imenu--menubar-select (item)
997 "Use Imenu to select the function or variable named in this menu ITEM."
998 (if (equal item imenu--rescan-item)
999 (progn
1000 (imenu--cleanup)
1001 ;; Make sure imenu-update-menubar redoes everything.
1002 (setq imenu-menubar-modified-tick -1)
1003 (setq imenu--index-alist nil)
1004 (setq imenu--last-menubar-index-alist nil)
1005 (imenu-update-menubar)
1007 (imenu item)
1008 nil))
1010 (defun imenu-default-goto-function (name position &optional rest)
1011 "Move to the given position.
1013 NAME is ignored. POSITION is where to move. REST is also ignored.
1014 The ignored args just make this function have the same interface as a
1015 function placed in a special index-item."
1016 (if (or (< position (point-min))
1017 (> position (point-max)))
1018 ;; widen if outside narrowing
1019 (widen))
1020 (goto-char position))
1022 ;;;###autoload
1023 (defun imenu (index-item)
1024 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1025 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1026 for more information."
1027 (interactive (list (imenu-choose-buffer-index)))
1028 ;; Convert a string to an alist element.
1029 (if (stringp index-item)
1030 (setq index-item (assoc index-item (imenu--make-index-alist))))
1031 (when index-item
1032 (push-mark)
1033 (let* ((is-special-item (listp (cdr index-item)))
1034 (function
1035 (if is-special-item
1036 (nth 2 index-item) imenu-default-goto-function))
1037 (position (if is-special-item
1038 (cadr index-item) (cdr index-item)))
1039 (rest (if is-special-item (cddr index-item))))
1040 (apply function (car index-item) position rest))
1041 (run-hooks 'imenu-after-jump-hook)))
1043 (dolist (mess
1044 '("^No items suitable for an index found in this buffer$"
1045 "^This buffer cannot use `imenu-default-create-index-function'$"
1046 "^The mode `.*' does not support Imenu$"))
1047 (add-to-list 'debug-ignored-errors mess))
1049 (provide 'imenu)
1051 ;; arch-tag: 98a2f5f5-4b91-4704-b18c-3aacf77d77a7
1052 ;;; imenu.el ends here