lisp/*: Add declarations, remove unused bindings, mark unused args.
[emacs.git] / lisp / imenu.el
blobceea9420c4c0bee1e6037614c7df22fc4a6cfbcf
1 ;;; imenu.el --- framework for mode-specific buffer indexes
3 ;; Copyright (C) 1994-1998, 2001-2012 Free Software Foundation, Inc.
5 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
6 ;; Lars Lindberg <lli@sypro.cap.se>
7 ;; Maintainer: FSF
8 ;; Created: 8 Feb 1994
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 3 of the License, or
16 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Purpose of this package:
29 ;; To present a framework for mode-specific buffer indexes.
30 ;; A buffer index is an alist of names and buffer positions.
31 ;; For instance all functions in a C-file and their positions.
33 ;; It is documented in the Emacs Lisp manual.
35 ;; How it works:
37 ;; A mode-specific function is called to generate the index. It is
38 ;; then presented to the user, who can choose from this index.
40 ;; The package comes with a set of example functions for how to
41 ;; utilize this package.
43 ;; There are *examples* for index gathering functions/regular
44 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
45 ;; customize for other modes. A function for jumping to the chosen
46 ;; index position is also supplied.
48 ;;; History:
49 ;; Thanks go to
50 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
51 ;; [dean] - Dean Andrews ada@unison.com
52 ;; [alon] - Alon Albert al@mercury.co.il
53 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
54 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
55 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
56 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
57 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
58 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
60 ;;; Code:
62 (eval-when-compile (require 'cl))
64 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
65 ;;;
66 ;;; Customizable variables
67 ;;;
68 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 (defgroup imenu nil
71 "Mode-specific buffer indexes."
72 :group 'matching
73 :group 'frames
74 :group 'convenience
75 :link '(custom-manual "(elisp)Imenu"))
77 (defcustom imenu-use-markers t
78 "Non-nil means use markers instead of integers for Imenu buffer positions.
80 Setting this to nil makes Imenu work a little faster but editing the
81 buffer will make the generated index positions wrong.
83 This might not yet be honored by all index-building functions."
84 :type 'boolean
85 :group 'imenu)
88 (defcustom imenu-max-item-length 60
89 "If a number, truncate Imenu entries to that length."
90 :type '(choice integer
91 (const :tag "Unlimited"))
92 :group 'imenu)
94 (defcustom imenu-auto-rescan nil
95 "Non-nil means Imenu should always rescan the buffers."
96 :type 'boolean
97 :group 'imenu)
99 (defcustom imenu-auto-rescan-maxout 60000
100 "Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
101 This variable is buffer-local."
102 :type 'integer
103 :group 'imenu)
105 (defvar imenu-always-use-completion-buffer-p nil)
106 (make-obsolete-variable 'imenu-always-use-completion-buffer-p
107 'imenu-use-popup-menu "22.1")
109 (defcustom imenu-use-popup-menu
110 (if imenu-always-use-completion-buffer-p
111 (not (eq imenu-always-use-completion-buffer-p 'never))
112 'on-mouse)
113 "Use a popup menu rather than a minibuffer prompt.
114 If nil, always use a minibuffer prompt.
115 If t, always use a popup menu,
116 If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
117 :type '(choice (const :tag "On Mouse" on-mouse)
118 (const :tag "Never" nil)
119 (other :tag "Always" t))
120 :group 'imenu)
122 (defcustom imenu-eager-completion-buffer
123 (not (eq imenu-always-use-completion-buffer-p 'never))
124 "If non-nil, eagerly popup the completion buffer."
125 :type 'boolean
126 :group 'imenu
127 :version "22.1")
129 (defcustom imenu-after-jump-hook nil
130 "Hooks called after jumping to a place in the buffer.
132 Useful things to use here include `reposition-window', `recenter', and
133 \(lambda () (recenter 0)) to show at top of screen."
134 :type 'hook
135 :group 'imenu)
137 ;;;###autoload
138 (defcustom imenu-sort-function nil
139 "The function to use for sorting the index mouse-menu.
141 Affects only the mouse index menu.
143 Set this to nil if you don't want any sorting (faster).
144 The items in the menu are then presented in the order they were found
145 in the buffer.
147 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
149 The function should take two arguments and return t if the first
150 element should come before the second. The arguments are cons cells;
151 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
152 :type '(choice (const :tag "No sorting" nil)
153 (const :tag "Sort by name" imenu--sort-by-name)
154 (function :tag "Another function"))
155 :group 'imenu)
157 (defcustom imenu-max-items 25
158 "Maximum number of elements in a mouse menu for Imenu."
159 :type 'integer
160 :group 'imenu)
162 ;; No longer used. KFS 2004-10-27
163 ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
164 ;; "Progress message during the index scanning of the buffer.
165 ;; If non-nil, user gets a message during the scanning of the buffer.
167 ;; Relevant only if the mode-specific function that creates the buffer
168 ;; index use `imenu-progress-message', and not useful if that is fast, in
169 ;; which case you might as well set this to nil."
170 ;; :type '(choice string
171 ;; (const :tag "None" nil))
172 ;; :group 'imenu)
174 (defcustom imenu-space-replacement "."
175 "The replacement string for spaces in index names.
176 Used when presenting the index in a completion buffer to make the
177 names work as tokens."
178 :type '(choice string (const nil))
179 :group 'imenu)
181 (defcustom imenu-level-separator ":"
182 "The separator between index names of different levels.
183 Used for making mouse-menu titles and for flattening nested indexes
184 with name concatenation."
185 :type 'string
186 :group 'imenu)
188 ;;;###autoload
189 (defvar imenu-generic-expression nil
190 "The regex pattern to use for creating a buffer index.
192 If non-nil this pattern is passed to `imenu--generic-function' to
193 create a buffer index. Look there for the documentation of this
194 pattern's structure.
196 For example, see the value of `fortran-imenu-generic-expression' used by
197 `fortran-mode' with `imenu-syntax-alist' set locally to give the
198 characters which normally have \"symbol\" syntax \"word\" syntax
199 during matching.")
200 ;;;###autoload(put 'imenu-generic-expression 'risky-local-variable t)
202 ;;;###autoload
203 (make-variable-buffer-local 'imenu-generic-expression)
205 ;;;; Hooks
207 ;;;###autoload
208 (defvar imenu-create-index-function 'imenu-default-create-index-function
209 "The function to use for creating an index alist of the current buffer.
211 It should be a function that takes no arguments and returns
212 an index alist of the current buffer. The function is
213 called within a `save-excursion'.
215 See `imenu--index-alist' for the format of the buffer index alist.")
216 ;;;###autoload
217 (make-variable-buffer-local 'imenu-create-index-function)
219 ;;;###autoload
220 (defvar imenu-prev-index-position-function 'beginning-of-defun
221 "Function for finding the next index position.
223 If `imenu-create-index-function' is set to
224 `imenu-default-create-index-function', then you must set this variable
225 to a function that will find the next index, looking backwards in the
226 file.
228 The function should leave point at the place to be connected to the
229 index and it should return nil when it doesn't find another index.")
230 ;;;###autoload
231 (make-variable-buffer-local 'imenu-prev-index-position-function)
233 ;;;###autoload
234 (defvar imenu-extract-index-name-function nil
235 "Function for extracting the index item name, given a position.
237 This function is called after `imenu-prev-index-position-function'
238 finds a position for an index item, with point at that position.
239 It should return the name for that index item.")
240 ;;;###autoload
241 (make-variable-buffer-local 'imenu-extract-index-name-function)
243 ;;;###autoload
244 (defvar imenu-name-lookup-function nil
245 "Function to compare string with index item.
247 This function will be called with two strings, and should return
248 non-nil if they match.
250 If nil, comparison is done with `string='.
251 Set this to some other function for more advanced comparisons,
252 such as \"begins with\" or \"name matches and number of
253 arguments match\".")
254 ;;;###autoload
255 (make-variable-buffer-local 'imenu-name-lookup-function)
257 ;;;###autoload
258 (defvar imenu-default-goto-function 'imenu-default-goto-function
259 "The default function called when selecting an Imenu item.
260 The function in this variable is called when selecting a normal index-item.")
261 ;;;###autoload
262 (make-variable-buffer-local 'imenu-default-goto-function)
265 (defun imenu--subalist-p (item)
266 (and (consp (cdr item)) (listp (cadr item))
267 (not (eq (car (cadr item)) 'lambda))))
270 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
271 ;;;;
272 ;;;; Some examples of functions utilizing the framework of this
273 ;;;; package.
274 ;;;;
275 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
277 ;; FIXME: This was the only imenu-example-* definition actually used,
278 ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
279 ;; all be removed.
280 (defun imenu-example--name-and-position ()
281 "Return the current/previous sexp and its (beginning) location.
282 Don't move point."
283 (save-excursion
284 (forward-sexp -1)
285 ;; [ydi] modified for imenu-use-markers
286 (let ((beg (if imenu-use-markers (point-marker) (point)))
287 (end (progn (forward-sexp) (point))))
288 (cons (buffer-substring beg end)
289 beg))))
290 (make-obsolete 'imenu-example--name-and-position
291 "use your own function instead." "23.2")
294 ;;; Lisp
297 (defun imenu-example--lisp-extract-index-name ()
298 ;; Example of a candidate for `imenu-extract-index-name-function'.
299 ;; This will generate a flat index of definitions in a lisp file.
300 (save-match-data
301 (and (looking-at "(def")
302 (condition-case nil
303 (progn
304 (down-list 1)
305 (forward-sexp 2)
306 (let ((beg (point))
307 (end (progn (forward-sexp -1) (point))))
308 (buffer-substring beg end)))
309 (error nil)))))
310 (make-obsolete 'imenu-example--lisp-extract-index-name "your own" "23.2")
312 (defun imenu-example--create-lisp-index ()
313 ;; Example of a candidate for `imenu-create-index-function'.
314 ;; It will generate a nested index of definitions.
315 (let ((index-alist '())
316 (index-var-alist '())
317 (index-type-alist '())
318 (index-unknown-alist '()))
319 (goto-char (point-max))
320 ;; Search for the function
321 (while (beginning-of-defun)
322 (save-match-data
323 (and (looking-at "(def")
324 (save-excursion
325 (down-list 1)
326 (cond
327 ((looking-at "def\\(var\\|const\\)")
328 (forward-sexp 2)
329 (push (imenu-example--name-and-position)
330 index-var-alist))
331 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
332 (forward-sexp 2)
333 (push (imenu-example--name-and-position)
334 index-alist))
335 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
336 (forward-sexp 2)
337 (if (= (char-after (1- (point))) ?\))
338 (progn
339 (forward-sexp -1)
340 (down-list 1)
341 (forward-sexp 1)))
342 (push (imenu-example--name-and-position)
343 index-type-alist))
345 (forward-sexp 2)
346 (push (imenu-example--name-and-position)
347 index-unknown-alist)))))))
348 (and index-var-alist
349 (push (cons "Variables" index-var-alist)
350 index-alist))
351 (and index-type-alist
352 (push (cons "Types" index-type-alist)
353 index-alist))
354 (and index-unknown-alist
355 (push (cons "Syntax-unknown" index-unknown-alist)
356 index-alist))
357 index-alist))
358 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
360 ;; Regular expression to find C functions
361 (defvar imenu-example--function-name-regexp-c
362 (concat
363 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
364 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
365 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
366 "\\([*&]+[ \t]*\\)?" ; pointer
367 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
370 (defun imenu-example--create-c-index (&optional regexp)
371 (let ((index-alist '())
372 char)
373 (goto-char (point-min))
374 ;; Search for the function
375 (save-match-data
376 (while (re-search-forward
377 (or regexp imenu-example--function-name-regexp-c)
378 nil t)
379 (backward-up-list 1)
380 (save-excursion
381 (goto-char (scan-sexps (point) 1))
382 (setq char (following-char)))
383 ;; Skip this function name if it is a prototype declaration.
384 (if (not (eq char ?\;))
385 (push (imenu-example--name-and-position) index-alist))))
386 (nreverse index-alist)))
387 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
389 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
391 ;;; Internal variables
393 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
395 ;; The item to use in the index for rescanning the buffer.
396 (defconst imenu--rescan-item '("*Rescan*" . -99))
398 ;; The latest buffer index.
399 ;; Buffer local.
400 (defvar imenu--index-alist nil
401 "The buffer index alist computed for this buffer in Imenu.
403 Simple elements in the alist look like (INDEX-NAME . POSITION).
404 POSITION is the buffer position of the item; to go to the item
405 is simply to move point to that position.
407 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
408 To \"go to\" a special element means applying FUNCTION
409 to INDEX-NAME, POSITION, and the ARGUMENTS.
411 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
412 The function `imenu--subalist-p' tests an element and returns t
413 if it is a sub-alist.
415 There is one simple element with negative POSITION; selecting that
416 element recalculates the buffer's index alist.")
417 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
419 (make-variable-buffer-local 'imenu--index-alist)
421 (defvar imenu--last-menubar-index-alist nil
422 "The latest buffer index alist used to update the menu bar menu.")
424 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
426 ;; History list for 'jump-to-function-in-buffer'.
427 ;; Making this buffer local caused it not to work!
428 (defvar imenu--history-list nil)
430 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
432 ;;; Internal support functions
434 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
437 ;;; Sort function
438 ;;; Sorts the items depending on their index name.
439 ;;; An item looks like (NAME . POSITION).
441 (defun imenu--sort-by-name (item1 item2)
442 (string-lessp (car item1) (car item2)))
444 (defun imenu--sort-by-position (item1 item2)
445 (< (cdr item1) (cdr item2)))
447 (defun imenu--relative-position (&optional reverse)
448 ;; Support function to calculate relative position in buffer
449 ;; Beginning of buffer is 0 and end of buffer is 100
450 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
451 (let ((pos (point))
452 (total (buffer-size)))
453 (and reverse (setq pos (- total pos)))
454 (if (> total 50000)
455 ;; Avoid overflow from multiplying by 100!
456 (/ (1- pos) (max (/ total 100) 1))
457 (/ (* 100 (1- pos)) (max total 1)))))
459 ;; Split LIST into sublists of max length N.
460 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
462 ;; The returned list DOES NOT share structure with LIST.
463 (defun imenu--split (list n)
464 (let ((remain list)
465 (result '())
466 (sublist '())
467 (i 0))
468 (while remain
469 (push (pop remain) sublist)
470 (incf i)
471 (and (= i n)
472 ;; We have finished a sublist
473 (progn (push (nreverse sublist) result)
474 (setq i 0)
475 (setq sublist '()))))
476 ;; There might be a sublist (if the length of LIST mod n is != 0)
477 ;; that has to be added to the result list.
478 (and sublist
479 (push (nreverse sublist) result))
480 (nreverse result)))
482 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
483 ;;; In any case, add TITLE to the front of the alist.
484 ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
485 ;;; beginning of the returned alist.
487 ;;; The returned alist DOES NOT share structure with MENULIST.
488 (defun imenu--split-menu (menulist title)
489 (let ((menulist (copy-sequence menulist))
490 keep-at-top tail)
491 (if (memq imenu--rescan-item menulist)
492 (setq keep-at-top (list imenu--rescan-item)
493 menulist (delq imenu--rescan-item menulist)))
494 (setq tail menulist)
495 (dolist (item tail)
496 (when (imenu--subalist-p item)
497 (push item keep-at-top)
498 (setq menulist (delq item menulist))))
499 (if imenu-sort-function
500 (setq menulist (sort menulist imenu-sort-function)))
501 (if (> (length menulist) imenu-max-items)
502 (setq menulist
503 (mapcar
504 (lambda (menu)
505 (cons (format "From: %s" (caar menu)) menu))
506 (imenu--split menulist imenu-max-items))))
507 (cons title
508 (nconc (nreverse keep-at-top) menulist))))
510 ;;; Split up each long alist that are nested within ALIST
511 ;;; into nested alists.
513 ;;; Return a split and sorted copy of ALIST. The returned alist DOES
514 ;;; NOT share structure with ALIST.
515 (defun imenu--split-submenus (alist)
516 (mapcar (function
517 (lambda (elt)
518 (if (and (consp elt)
519 (stringp (car elt))
520 (listp (cdr elt)))
521 (imenu--split-menu (cdr elt) (car elt))
522 elt)))
523 alist))
525 ;;; Truncate all strings in MENULIST to imenu-max-item-length
526 (defun imenu--truncate-items (menulist)
527 (mapcar (function
528 (lambda (item)
529 (cond
530 ((consp (cdr item))
531 (imenu--truncate-items (cdr item)))
532 ;; truncate if necessary
533 ((and (numberp imenu-max-item-length)
534 (> (length (car item)) imenu-max-item-length))
535 (setcar item (substring (car item) 0 imenu-max-item-length))))))
536 menulist))
539 (defun imenu--make-index-alist (&optional noerror)
540 "Create an index alist for the definitions in the current buffer.
541 This works by using the hook function `imenu-create-index-function'.
542 Report an error if the list is empty unless NOERROR is supplied and
543 non-nil.
545 See `imenu--index-alist' for the format of the index alist."
546 (or (and imenu--index-alist
547 (or (not imenu-auto-rescan)
548 (and imenu-auto-rescan
549 (> (buffer-size) imenu-auto-rescan-maxout))))
550 ;; Get the index; truncate if necessary
551 (progn
552 (setq imenu--index-alist
553 (save-excursion
554 (save-restriction
555 (widen)
556 (funcall imenu-create-index-function))))
557 (imenu--truncate-items imenu--index-alist)))
558 (or imenu--index-alist noerror
559 (error "No items suitable for an index found in this buffer"))
560 (or imenu--index-alist
561 (setq imenu--index-alist (list nil)))
562 ;; Add a rescan option to the index.
563 (cons imenu--rescan-item imenu--index-alist))
565 ;;; Find all markers in alist and makes
566 ;;; them point nowhere.
567 ;;; The top-level call uses nil as the argument;
568 ;;; non-nil arguments are in recursive calls.
569 (defvar imenu--cleanup-seen)
571 (defun imenu--cleanup (&optional alist)
572 ;; If alist is provided use that list.
573 ;; If not, empty the table of lists already seen
574 ;; and use imenu--index-alist.
575 (if alist
576 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
577 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
579 (and alist
580 (mapc
581 (lambda (item)
582 (cond
583 ((markerp (cdr item))
584 (set-marker (cdr item) nil))
585 ;; Don't process one alist twice.
586 ((memq (cdr item) imenu--cleanup-seen))
587 ((imenu--subalist-p item)
588 (imenu--cleanup (cdr item)))))
589 alist)
592 (defun imenu--create-keymap (title alist &optional cmd)
593 (list* 'keymap title
594 (mapcar
595 (lambda (item)
596 (list* (car item) (car item)
597 (cond
598 ((imenu--subalist-p item)
599 (imenu--create-keymap (car item) (cdr item) cmd))
601 `(lambda () (interactive)
602 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
603 alist)))
605 (defun imenu--in-alist (str alist)
606 "Check whether the string STR is contained in multi-level ALIST."
607 (let (elt head tail res)
608 (setq res nil)
609 (while alist
610 (setq elt (car alist)
611 tail (cdr elt)
612 alist (cdr alist)
613 head (car elt))
614 ;; A nested ALIST element looks like
615 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
616 ;; while a bottom-level element looks like
617 ;; (INDEX-NAME . INDEX-POSITION)
618 ;; We are only interested in the bottom-level elements, so we need to
619 ;; recurse if TAIL is a list.
620 (cond ((listp tail)
621 (if (setq res (imenu--in-alist str tail))
622 (setq alist nil)))
623 ((if imenu-name-lookup-function
624 (funcall imenu-name-lookup-function str head)
625 (string= str head))
626 (setq alist nil res elt))))
627 res))
629 (defvar imenu-syntax-alist nil
630 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
632 The car of the assocs may be either a character or a string and the
633 cdr is a syntax description appropriate for `modify-syntax-entry'. For
634 a string, all the characters in the string get the specified syntax.
636 This is typically used to give word syntax to characters which
637 normally have symbol syntax to simplify `imenu-expression'
638 and speed-up matching.")
639 ;;;###autoload
640 (make-variable-buffer-local 'imenu-syntax-alist)
642 (defun imenu-default-create-index-function ()
643 "Default function to create an index alist of the current buffer.
645 The most general method is to move point to end of buffer, then repeatedly call
646 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
647 All the results returned by the latter are gathered into an index alist.
648 This method is used if those two variables are non-nil.
650 The alternate method, which is the one most often used, is to call
651 `imenu--generic-function' with `imenu-generic-expression' as argument."
652 ;; These should really be done by setting imenu-create-index-function
653 ;; in these major modes. But save that change for later.
654 (cond ((and imenu-prev-index-position-function
655 imenu-extract-index-name-function)
656 (let ((index-alist '()) (pos (point))
657 name)
658 (goto-char (point-max))
659 ;; Search for the function
660 (while (funcall imenu-prev-index-position-function)
661 (when (= pos (point))
662 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
663 (setq pos (point))
664 (save-excursion
665 (setq name (funcall imenu-extract-index-name-function)))
666 (and (stringp name)
667 ;; [ydi] updated for imenu-use-markers
668 (push (cons name (if imenu-use-markers (point-marker) (point)))
669 index-alist)))
670 index-alist))
671 ;; Use generic expression if possible.
672 ((and imenu-generic-expression)
673 (imenu--generic-function imenu-generic-expression))
675 (error "This buffer cannot use `imenu-default-create-index-function'"))))
678 ;;; Generic index gathering function.
681 (defvar imenu-case-fold-search t
682 "Defines whether `imenu--generic-function' should fold case when matching.
684 This variable should be set (only) by initialization code
685 for modes which use `imenu--generic-function'. If it is not set, but
686 `font-lock-defaults' is set, then font-lock's setting is used.")
687 ;;;###autoload
688 (make-variable-buffer-local 'imenu-case-fold-search)
690 ;; This function can be called with quitting disabled,
691 ;; so it needs to be careful never to loop!
692 (defun imenu--generic-function (patterns)
693 "Return an index alist of the current buffer based on PATTERNS.
695 PATTERNS is an alist with elements that look like this:
696 (MENU-TITLE REGEXP INDEX)
697 or like this:
698 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
699 with zero or more ARGUMENTS. The former format creates a simple
700 element in the index alist when it matches; the latter creates a
701 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
702 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
704 MENU-TITLE is a string used as the title for the submenu or nil
705 if the entries are not nested.
707 REGEXP is a regexp that should match a construct in the buffer
708 that is to be displayed in the menu; i.e., function or variable
709 definitions, etc. It contains a substring which is the name to
710 appear in the menu. See the info section on Regexps for more
711 information. REGEXP may also be a function, called without
712 arguments. It is expected to search backwards. It shall return
713 true and set `match-data' if it finds another element.
715 INDEX points to the substring in REGEXP that contains the
716 name (of the function, variable or type) that is to appear in the
717 menu.
719 The variable `imenu-case-fold-search' determines whether or not the
720 regexp matches are case sensitive, and `imenu-syntax-alist' can be
721 used to alter the syntax table for the search.
723 See `lisp-imenu-generic-expression' for an example of PATTERNS.
725 Returns an index of the current buffer as an alist. The elements in
726 the alist look like:
727 (INDEX-NAME . INDEX-POSITION)
728 or like:
729 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
730 They may also be nested index alists like:
731 (INDEX-NAME . INDEX-ALIST)
732 depending on PATTERNS."
734 (let ((index-alist (list 'dummy))
735 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
736 (not (local-variable-p 'font-lock-defaults)))
737 imenu-case-fold-search
738 (nth 2 font-lock-defaults)))
739 (old-table (syntax-table))
740 (table (copy-syntax-table (syntax-table)))
741 (slist imenu-syntax-alist))
742 ;; Modify the syntax table used while matching regexps.
743 (dolist (syn slist)
744 ;; The character(s) to modify may be a single char or a string.
745 (if (numberp (car syn))
746 (modify-syntax-entry (car syn) (cdr syn) table)
747 (mapc (lambda (c)
748 (modify-syntax-entry c (cdr syn) table))
749 (car syn))))
750 (goto-char (point-max))
751 (unwind-protect ; for syntax table
752 (save-match-data
753 (set-syntax-table table)
755 ;; map over the elements of imenu-generic-expression
756 ;; (typically functions, variables ...)
757 (dolist (pat patterns)
758 (let ((menu-title (car pat))
759 (regexp (nth 1 pat))
760 (index (nth 2 pat))
761 (function (nth 3 pat))
762 (rest (nthcdr 4 pat))
763 start beg)
764 ;; Go backwards for convenience of adding items in order.
765 (goto-char (point-max))
766 (while (and (if (functionp regexp)
767 (funcall regexp)
768 (and
769 (re-search-backward regexp nil t)
770 ;; Do not count invisible definitions.
771 (let ((invis (invisible-p (point))))
772 (or (not invis)
773 (progn
774 (while (and invis
775 (not (bobp)))
776 (setq invis (not (re-search-backward
777 regexp nil 'move))))
778 (not invis))))))
779 ;; Exit the loop if we get an empty match,
780 ;; because it means a bad regexp was specified.
781 (not (= (match-beginning 0) (match-end 0))))
782 (setq start (point))
783 ;; Record the start of the line in which the match starts.
784 ;; That's the official position of this definition.
785 (goto-char (match-beginning index))
786 (beginning-of-line)
787 (setq beg (point))
788 ;; Add this sort of submenu only when we've found an
789 ;; item for it, avoiding empty, duff menus.
790 (unless (assoc menu-title index-alist)
791 (push (list menu-title) index-alist))
792 (if imenu-use-markers
793 (setq beg (copy-marker beg)))
794 (let ((item
795 (if function
796 (nconc (list (match-string-no-properties index)
797 beg function)
798 rest)
799 (cons (match-string-no-properties index)
800 beg)))
801 ;; This is the desired submenu,
802 ;; starting with its title (or nil).
803 (menu (assoc menu-title index-alist)))
804 ;; Insert the item unless it is already present.
805 (unless (member item (cdr menu))
806 (setcdr menu
807 (cons item (cdr menu)))))
808 ;; Go to the start of the match, to make sure we
809 ;; keep making progress backwards.
810 (goto-char start))))
811 (set-syntax-table old-table)))
812 ;; Sort each submenu by position.
813 ;; This is in case one submenu gets items from two different regexps.
814 (dolist (item index-alist)
815 (when (listp item)
816 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
817 (let ((main-element (assq nil index-alist)))
818 (nconc (delq main-element (delq 'dummy index-alist))
819 (cdr main-element)))))
821 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
823 ;;; The main functions for this package!
825 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
827 ;; See also info-lookup-find-item
828 (defun imenu-find-default (guess completions)
829 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
830 (catch 'found
831 (let ((case-fold-search t))
832 (if (assoc guess completions) guess
833 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
834 (concat "\\`" (regexp-quote guess))
835 (concat (regexp-quote guess) "\\'")
836 (regexp-quote guess)))
837 (dolist (x completions)
838 (if (string-match re (car x)) (throw 'found (car x)))))))))
840 (defun imenu--completion-buffer (index-alist &optional prompt)
841 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
843 Return one of the entries in index-alist or nil."
844 ;; Create a list for this buffer only when needed.
845 (let ((name (thing-at-point 'symbol))
846 choice
847 (prepared-index-alist
848 (if (not imenu-space-replacement) index-alist
849 (mapcar
850 (lambda (item)
851 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
852 (car item))
853 (cdr item)))
854 index-alist))))
855 (when (stringp name)
856 (setq name (or (imenu-find-default name prepared-index-alist) name)))
857 (cond (prompt)
858 ((and name (imenu--in-alist name prepared-index-alist))
859 (setq prompt (format "Index item (default %s): " name)))
860 (t (setq prompt "Index item: ")))
861 (let ((minibuffer-setup-hook minibuffer-setup-hook))
862 ;; Display the completion buffer.
863 (if (not imenu-eager-completion-buffer)
864 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
865 (setq name (completing-read prompt
866 prepared-index-alist
867 nil t nil 'imenu--history-list name)))
869 (when (stringp name)
870 (setq choice (assoc name prepared-index-alist))
871 (if (imenu--subalist-p choice)
872 (imenu--completion-buffer (cdr choice) prompt)
873 choice))))
875 (defun imenu--mouse-menu (index-alist event &optional title)
876 "Let the user select from a buffer index from a mouse menu.
878 INDEX-ALIST is the buffer index and EVENT is a mouse event.
880 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
881 (setq index-alist (imenu--split-submenus index-alist))
882 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
883 (map (imenu--create-keymap (car menu)
884 (cdr (if (< 1 (length (cdr menu)))
885 menu
886 (car (cdr menu)))))))
887 (popup-menu map event)))
889 (defun imenu-choose-buffer-index (&optional prompt alist)
890 "Let the user select from a buffer index and return the chosen index.
892 If the user originally activated this function with the mouse, a mouse
893 menu is used. Otherwise a completion buffer is used and the user is
894 prompted with PROMPT.
896 If you call this function with index alist ALIST, then it lets the user
897 select from ALIST.
899 With no index alist ALIST, it calls `imenu--make-index-alist' to
900 create the index alist.
902 If `imenu-use-popup-menu' is nil, then the completion buffer
903 is always used, no matter if the mouse was used or not.
905 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
906 (let (index-alist
907 (mouse-triggered (listp last-nonmenu-event))
908 (result t))
909 ;; If selected by mouse, see to that the window where the mouse is
910 ;; really is selected.
911 (and mouse-triggered
912 (not (equal last-nonmenu-event '(menu-bar)))
913 (let ((window (posn-window (event-start last-nonmenu-event))))
914 (or (framep window) (null window) (select-window window))))
915 ;; Create a list for this buffer only when needed.
916 (while (eq result t)
917 (setq index-alist (if alist alist (imenu--make-index-alist)))
918 (setq result
919 (if (and imenu-use-popup-menu
920 (or (eq imenu-use-popup-menu t) mouse-triggered))
921 (imenu--mouse-menu index-alist last-nonmenu-event)
922 (imenu--completion-buffer index-alist prompt)))
923 (and (equal result imenu--rescan-item)
924 (imenu--cleanup)
925 (setq result t imenu--index-alist nil)))
926 result))
928 ;;;###autoload
929 (defun imenu-add-to-menubar (name)
930 "Add an `imenu' entry to the menu bar for the current buffer.
931 NAME is a string used to name the menu bar item.
932 See the command `imenu' for more information."
933 (interactive "sImenu menu item name: ")
934 (if (or (and imenu-prev-index-position-function
935 imenu-extract-index-name-function)
936 imenu-generic-expression
937 (not (eq imenu-create-index-function
938 'imenu-default-create-index-function)))
939 (unless (and (current-local-map)
940 (keymapp (lookup-key (current-local-map) [menu-bar index])))
941 (let ((newmap (make-sparse-keymap)))
942 (set-keymap-parent newmap (current-local-map))
943 (setq imenu--last-menubar-index-alist nil)
944 (define-key newmap [menu-bar index]
945 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
946 (use-local-map newmap)
947 (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
948 (error "The mode `%s' does not support Imenu"
949 (format-mode-line mode-name))))
951 ;;;###autoload
952 (defun imenu-add-menubar-index ()
953 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
955 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
956 (interactive)
957 (imenu-add-to-menubar "Index"))
959 (defvar imenu-buffer-menubar nil)
961 (defvar imenu-menubar-modified-tick 0
962 "The value of (buffer-chars-modified-tick) as of the last call
963 to `imenu-update-menubar'.")
964 (make-variable-buffer-local 'imenu-menubar-modified-tick)
966 (defun imenu-update-menubar ()
967 (when (and (current-local-map)
968 (keymapp (lookup-key (current-local-map) [menu-bar index]))
969 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
970 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
971 (let ((index-alist (imenu--make-index-alist t)))
972 ;; Don't bother updating if the index-alist has not changed
973 ;; since the last time we did it.
974 (unless (equal index-alist imenu--last-menubar-index-alist)
975 (let (menu menu1 old)
976 (setq imenu--last-menubar-index-alist index-alist)
977 (setq index-alist (imenu--split-submenus index-alist))
978 (setq menu (imenu--split-menu index-alist
979 (buffer-name)))
980 (setq menu1 (imenu--create-keymap (car menu)
981 (cdr (if (< 1 (length (cdr menu)))
982 menu
983 (car (cdr menu))))
984 'imenu--menubar-select))
985 (setq old (lookup-key (current-local-map) [menu-bar index]))
986 ;; This should never happen, but in some odd cases, potentially,
987 ;; lookup-key may return a dynamically composed keymap.
988 (if (keymapp (cadr old)) (setq old (cadr old)))
989 (setcdr old (cdr menu1)))))))
991 (defun imenu--menubar-select (item)
992 "Use Imenu to select the function or variable named in this menu ITEM."
993 (if (equal item imenu--rescan-item)
994 (progn
995 (imenu--cleanup)
996 ;; Make sure imenu-update-menubar redoes everything.
997 (setq imenu-menubar-modified-tick -1)
998 (setq imenu--index-alist nil)
999 (setq imenu--last-menubar-index-alist nil)
1000 (imenu-update-menubar)
1002 (imenu item)
1003 nil))
1005 (defun imenu-default-goto-function (_name position &optional _rest)
1006 "Move to the given position.
1008 NAME is ignored. POSITION is where to move. REST is also ignored.
1009 The ignored args just make this function have the same interface as a
1010 function placed in a special index-item."
1011 (if (or (< position (point-min))
1012 (> position (point-max)))
1013 ;; widen if outside narrowing
1014 (widen))
1015 (goto-char position))
1017 ;;;###autoload
1018 (defun imenu (index-item)
1019 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1020 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1021 for more information."
1022 (interactive (list (imenu-choose-buffer-index)))
1023 ;; Convert a string to an alist element.
1024 (if (stringp index-item)
1025 (setq index-item (assoc index-item (imenu--make-index-alist))))
1026 (when index-item
1027 (push-mark)
1028 (let* ((is-special-item (listp (cdr index-item)))
1029 (function
1030 (if is-special-item
1031 (nth 2 index-item) imenu-default-goto-function))
1032 (position (if is-special-item
1033 (cadr index-item) (cdr index-item)))
1034 (rest (if is-special-item (cddr index-item))))
1035 (apply function (car index-item) position rest))
1036 (run-hooks 'imenu-after-jump-hook)))
1038 (dolist (mess
1039 '("^No items suitable for an index found in this buffer$"
1040 "^This buffer cannot use `imenu-default-create-index-function'$"
1041 "^The mode `.*' does not support Imenu$"))
1042 (add-to-list 'debug-ignored-errors mess))
1044 (provide 'imenu)
1046 ;;; imenu.el ends here