auth.texi (Secret Service API): Adjust @samp to @code for collection names
[emacs.git] / lisp / imenu.el
blob8363956355b863396470b39803309730f5e61946
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))))
269 ;; Macro to display a progress message.
270 ;; RELPOS is the relative position to display.
271 ;; If RELPOS is nil, then the relative position in the buffer
272 ;; is calculated.
273 ;; PREVPOS is the variable in which we store the last position displayed.
274 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
276 ;; Made obsolete/empty, as computers are now faster than the eye, and
277 ;; it had problems updating the messages correctly, and could shadow
278 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
280 ;; `(and
281 ;; imenu-scanning-message
282 ;; (let ((pos ,(if relpos
283 ;; relpos
284 ;; `(imenu--relative-position ,reverse))))
285 ;; (if ,(if relpos t
286 ;; `(> pos (+ 5 ,prevpos)))
287 ;; (progn
288 ;; (message imenu-scanning-message pos)
289 ;; (setq ,prevpos pos)))))
293 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
294 ;;;;
295 ;;;; Some examples of functions utilizing the framework of this
296 ;;;; package.
297 ;;;;
298 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
300 ;; FIXME: This was the only imenu-example-* definition actually used,
301 ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
302 ;; all be removed.
303 (defun imenu-example--name-and-position ()
304 "Return the current/previous sexp and its (beginning) location.
305 Don't move point."
306 (save-excursion
307 (forward-sexp -1)
308 ;; [ydi] modified for imenu-use-markers
309 (let ((beg (if imenu-use-markers (point-marker) (point)))
310 (end (progn (forward-sexp) (point))))
311 (cons (buffer-substring beg end)
312 beg))))
313 (make-obsolete 'imenu-example--name-and-position
314 "use your own function instead." "23.2")
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)))))
333 (make-obsolete 'imenu-example--lisp-extract-index-name "your own" "23.2")
335 (defun imenu-example--create-lisp-index ()
336 ;; Example of a candidate for `imenu-create-index-function'.
337 ;; It will generate a nested index of definitions.
338 (let ((index-alist '())
339 (index-var-alist '())
340 (index-type-alist '())
341 (index-unknown-alist '())
342 prev-pos)
343 (goto-char (point-max))
344 (imenu-progress-message prev-pos 0)
345 ;; Search for the function
346 (while (beginning-of-defun)
347 (imenu-progress-message prev-pos nil t)
348 (save-match-data
349 (and (looking-at "(def")
350 (save-excursion
351 (down-list 1)
352 (cond
353 ((looking-at "def\\(var\\|const\\)")
354 (forward-sexp 2)
355 (push (imenu-example--name-and-position)
356 index-var-alist))
357 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
358 (forward-sexp 2)
359 (push (imenu-example--name-and-position)
360 index-alist))
361 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
362 (forward-sexp 2)
363 (if (= (char-after (1- (point))) ?\))
364 (progn
365 (forward-sexp -1)
366 (down-list 1)
367 (forward-sexp 1)))
368 (push (imenu-example--name-and-position)
369 index-type-alist))
371 (forward-sexp 2)
372 (push (imenu-example--name-and-position)
373 index-unknown-alist)))))))
374 (imenu-progress-message prev-pos 100)
375 (and index-var-alist
376 (push (cons "Variables" index-var-alist)
377 index-alist))
378 (and index-type-alist
379 (push (cons "Types" index-type-alist)
380 index-alist))
381 (and index-unknown-alist
382 (push (cons "Syntax-unknown" index-unknown-alist)
383 index-alist))
384 index-alist))
385 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
387 ;; Regular expression to find C functions
388 (defvar imenu-example--function-name-regexp-c
389 (concat
390 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
391 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
392 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
393 "\\([*&]+[ \t]*\\)?" ; pointer
394 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
397 (defun imenu-example--create-c-index (&optional regexp)
398 (let ((index-alist '())
399 prev-pos char)
400 (goto-char (point-min))
401 (imenu-progress-message prev-pos 0)
402 ;; Search for the function
403 (save-match-data
404 (while (re-search-forward
405 (or regexp imenu-example--function-name-regexp-c)
406 nil t)
407 (imenu-progress-message prev-pos)
408 (backward-up-list 1)
409 (save-excursion
410 (goto-char (scan-sexps (point) 1))
411 (setq char (following-char)))
412 ;; Skip this function name if it is a prototype declaration.
413 (if (not (eq char ?\;))
414 (push (imenu-example--name-and-position) index-alist))))
415 (imenu-progress-message prev-pos 100)
416 (nreverse index-alist)))
417 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
419 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
421 ;;; Internal variables
423 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
425 ;; The item to use in the index for rescanning the buffer.
426 (defconst imenu--rescan-item '("*Rescan*" . -99))
428 ;; The latest buffer index.
429 ;; Buffer local.
430 (defvar imenu--index-alist nil
431 "The buffer index alist computed for this buffer in Imenu.
433 Simple elements in the alist look like (INDEX-NAME . POSITION).
434 POSITION is the buffer position of the item; to go to the item
435 is simply to move point to that position.
437 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
438 To \"go to\" a special element means applying FUNCTION
439 to INDEX-NAME, POSITION, and the ARGUMENTS.
441 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
442 The function `imenu--subalist-p' tests an element and returns t
443 if it is a sub-alist.
445 There is one simple element with negative POSITION; selecting that
446 element recalculates the buffer's index alist.")
447 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
449 (make-variable-buffer-local 'imenu--index-alist)
451 (defvar imenu--last-menubar-index-alist nil
452 "The latest buffer index alist used to update the menu bar menu.")
454 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
456 ;; History list for 'jump-to-function-in-buffer'.
457 ;; Making this buffer local caused it not to work!
458 (defvar imenu--history-list nil)
460 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
462 ;;; Internal support functions
464 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
467 ;;; Sort function
468 ;;; Sorts the items depending on their index name.
469 ;;; An item looks like (NAME . POSITION).
471 (defun imenu--sort-by-name (item1 item2)
472 (string-lessp (car item1) (car item2)))
474 (defun imenu--sort-by-position (item1 item2)
475 (< (cdr item1) (cdr item2)))
477 (defun imenu--relative-position (&optional reverse)
478 ;; Support function to calculate relative position in buffer
479 ;; Beginning of buffer is 0 and end of buffer is 100
480 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
481 (let ((pos (point))
482 (total (buffer-size)))
483 (and reverse (setq pos (- total pos)))
484 (if (> total 50000)
485 ;; Avoid overflow from multiplying by 100!
486 (/ (1- pos) (max (/ total 100) 1))
487 (/ (* 100 (1- pos)) (max total 1)))))
489 ;; Split LIST into sublists of max length N.
490 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
492 ;; The returned list DOES NOT share structure with LIST.
493 (defun imenu--split (list n)
494 (let ((remain list)
495 (result '())
496 (sublist '())
497 (i 0))
498 (while remain
499 (push (pop remain) sublist)
500 (incf i)
501 (and (= i n)
502 ;; We have finished a sublist
503 (progn (push (nreverse sublist) result)
504 (setq i 0)
505 (setq sublist '()))))
506 ;; There might be a sublist (if the length of LIST mod n is != 0)
507 ;; that has to be added to the result list.
508 (and sublist
509 (push (nreverse sublist) result))
510 (nreverse result)))
512 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
513 ;;; In any case, add TITLE to the front of the alist.
514 ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
515 ;;; beginning of the returned alist.
517 ;;; The returned alist DOES NOT share structure with MENULIST.
518 (defun imenu--split-menu (menulist title)
519 (let ((menulist (copy-sequence menulist))
520 keep-at-top tail)
521 (if (memq imenu--rescan-item menulist)
522 (setq keep-at-top (list imenu--rescan-item)
523 menulist (delq imenu--rescan-item menulist)))
524 (setq tail menulist)
525 (dolist (item tail)
526 (when (imenu--subalist-p item)
527 (push item keep-at-top)
528 (setq menulist (delq item menulist))))
529 (if imenu-sort-function
530 (setq menulist (sort menulist imenu-sort-function)))
531 (if (> (length menulist) imenu-max-items)
532 (setq menulist
533 (mapcar
534 (lambda (menu)
535 (cons (format "From: %s" (caar menu)) menu))
536 (imenu--split menulist imenu-max-items))))
537 (cons title
538 (nconc (nreverse keep-at-top) menulist))))
540 ;;; Split up each long alist that are nested within ALIST
541 ;;; into nested alists.
543 ;;; Return a split and sorted copy of ALIST. The returned alist DOES
544 ;;; NOT share structure with ALIST.
545 (defun imenu--split-submenus (alist)
546 (mapcar (function
547 (lambda (elt)
548 (if (and (consp elt)
549 (stringp (car elt))
550 (listp (cdr elt)))
551 (imenu--split-menu (cdr elt) (car elt))
552 elt)))
553 alist))
555 ;;; Truncate all strings in MENULIST to imenu-max-item-length
556 (defun imenu--truncate-items (menulist)
557 (mapcar (function
558 (lambda (item)
559 (cond
560 ((consp (cdr item))
561 (imenu--truncate-items (cdr item)))
562 ;; truncate if necessary
563 ((and (numberp imenu-max-item-length)
564 (> (length (car item)) imenu-max-item-length))
565 (setcar item (substring (car item) 0 imenu-max-item-length))))))
566 menulist))
569 (defun imenu--make-index-alist (&optional noerror)
570 "Create an index alist for the definitions in the current buffer.
571 This works by using the hook function `imenu-create-index-function'.
572 Report an error if the list is empty unless NOERROR is supplied and
573 non-nil.
575 See `imenu--index-alist' for the format of the index alist."
576 (or (and imenu--index-alist
577 (or (not imenu-auto-rescan)
578 (and imenu-auto-rescan
579 (> (buffer-size) imenu-auto-rescan-maxout))))
580 ;; Get the index; truncate if necessary
581 (progn
582 (setq imenu--index-alist
583 (save-excursion
584 (save-restriction
585 (widen)
586 (funcall imenu-create-index-function))))
587 (imenu--truncate-items imenu--index-alist)))
588 (or imenu--index-alist noerror
589 (error "No items suitable for an index found in this buffer"))
590 (or imenu--index-alist
591 (setq imenu--index-alist (list nil)))
592 ;; Add a rescan option to the index.
593 (cons imenu--rescan-item imenu--index-alist))
595 ;;; Find all markers in alist and makes
596 ;;; them point nowhere.
597 ;;; The top-level call uses nil as the argument;
598 ;;; non-nil arguments are in recursive calls.
599 (defvar imenu--cleanup-seen)
601 (defun imenu--cleanup (&optional alist)
602 ;; If alist is provided use that list.
603 ;; If not, empty the table of lists already seen
604 ;; and use imenu--index-alist.
605 (if alist
606 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
607 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
609 (and alist
610 (mapc
611 (lambda (item)
612 (cond
613 ((markerp (cdr item))
614 (set-marker (cdr item) nil))
615 ;; Don't process one alist twice.
616 ((memq (cdr item) imenu--cleanup-seen))
617 ((imenu--subalist-p item)
618 (imenu--cleanup (cdr item)))))
619 alist)
622 (defun imenu--create-keymap (title alist &optional cmd)
623 (list* 'keymap title
624 (mapcar
625 (lambda (item)
626 (list* (car item) (car item)
627 (cond
628 ((imenu--subalist-p item)
629 (imenu--create-keymap (car item) (cdr item) cmd))
631 `(lambda () (interactive)
632 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
633 alist)))
635 (defun imenu--in-alist (str alist)
636 "Check whether the string STR is contained in multi-level ALIST."
637 (let (elt head tail res)
638 (setq res nil)
639 (while alist
640 (setq elt (car alist)
641 tail (cdr elt)
642 alist (cdr alist)
643 head (car elt))
644 ;; A nested ALIST element looks like
645 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
646 ;; while a bottom-level element looks like
647 ;; (INDEX-NAME . INDEX-POSITION)
648 ;; We are only interested in the bottom-level elements, so we need to
649 ;; recurse if TAIL is a list.
650 (cond ((listp tail)
651 (if (setq res (imenu--in-alist str tail))
652 (setq alist nil)))
653 ((if imenu-name-lookup-function
654 (funcall imenu-name-lookup-function str head)
655 (string= str head))
656 (setq alist nil res elt))))
657 res))
659 (defvar imenu-syntax-alist nil
660 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
662 The car of the assocs may be either a character or a string and the
663 cdr is a syntax description appropriate for `modify-syntax-entry'. For
664 a string, all the characters in the string get the specified syntax.
666 This is typically used to give word syntax to characters which
667 normally have symbol syntax to simplify `imenu-expression'
668 and speed-up matching.")
669 ;;;###autoload
670 (make-variable-buffer-local 'imenu-syntax-alist)
672 (defun imenu-default-create-index-function ()
673 "Default function to create an index alist of the current buffer.
675 The most general method is to move point to end of buffer, then repeatedly call
676 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
677 All the results returned by the latter are gathered into an index alist.
678 This method is used if those two variables are non-nil.
680 The alternate method, which is the one most often used, is to call
681 `imenu--generic-function' with `imenu-generic-expression' as argument."
682 ;; These should really be done by setting imenu-create-index-function
683 ;; in these major modes. But save that change for later.
684 (cond ((and imenu-prev-index-position-function
685 imenu-extract-index-name-function)
686 (let ((index-alist '()) (pos (point))
687 prev-pos name)
688 (goto-char (point-max))
689 (imenu-progress-message prev-pos 0 t)
690 ;; Search for the function
691 (while (funcall imenu-prev-index-position-function)
692 (when (= pos (point))
693 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
694 (setq pos (point))
695 (imenu-progress-message prev-pos nil t)
696 (save-excursion
697 (setq name (funcall imenu-extract-index-name-function)))
698 (and (stringp name)
699 ;; [ydi] updated for imenu-use-markers
700 (push (cons name (if imenu-use-markers (point-marker) (point)))
701 index-alist)))
702 (imenu-progress-message prev-pos 100 t)
703 index-alist))
704 ;; Use generic expression if possible.
705 ((and imenu-generic-expression)
706 (imenu--generic-function imenu-generic-expression))
708 (error "This buffer cannot use `imenu-default-create-index-function'"))))
711 ;;; Generic index gathering function.
714 (defvar imenu-case-fold-search t
715 "Defines whether `imenu--generic-function' should fold case when matching.
717 This variable should be set (only) by initialization code
718 for modes which use `imenu--generic-function'. If it is not set, but
719 `font-lock-defaults' is set, then font-lock's setting is used.")
720 ;;;###autoload
721 (make-variable-buffer-local 'imenu-case-fold-search)
723 ;; This function can be called with quitting disabled,
724 ;; so it needs to be careful never to loop!
725 (defun imenu--generic-function (patterns)
726 "Return an index alist of the current buffer based on PATTERNS.
728 PATTERNS is an alist with elements that look like this:
729 (MENU-TITLE REGEXP INDEX)
730 or like this:
731 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
732 with zero or more ARGUMENTS. The former format creates a simple
733 element in the index alist when it matches; the latter creates a
734 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
735 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
737 MENU-TITLE is a string used as the title for the submenu or nil
738 if the entries are not nested.
740 REGEXP is a regexp that should match a construct in the buffer
741 that is to be displayed in the menu; i.e., function or variable
742 definitions, etc. It contains a substring which is the name to
743 appear in the menu. See the info section on Regexps for more
744 information. REGEXP may also be a function, called without
745 arguments. It is expected to search backwards. It shall return
746 true and set `match-data' if it finds another element.
748 INDEX points to the substring in REGEXP that contains the
749 name (of the function, variable or type) that is to appear in the
750 menu.
752 The variable `imenu-case-fold-search' determines whether or not the
753 regexp matches are case sensitive, and `imenu-syntax-alist' can be
754 used to alter the syntax table for the search.
756 See `lisp-imenu-generic-expression' for an example of PATTERNS.
758 Returns an index of the current buffer as an alist. The elements in
759 the alist look like:
760 (INDEX-NAME . INDEX-POSITION)
761 or like:
762 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
763 They may also be nested index alists like:
764 (INDEX-NAME . INDEX-ALIST)
765 depending on PATTERNS."
767 (let ((index-alist (list 'dummy))
768 prev-pos
769 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
770 (not (local-variable-p 'font-lock-defaults)))
771 imenu-case-fold-search
772 (nth 2 font-lock-defaults)))
773 (old-table (syntax-table))
774 (table (copy-syntax-table (syntax-table)))
775 (slist imenu-syntax-alist))
776 ;; Modify the syntax table used while matching regexps.
777 (dolist (syn slist)
778 ;; The character(s) to modify may be a single char or a string.
779 (if (numberp (car syn))
780 (modify-syntax-entry (car syn) (cdr syn) table)
781 (mapc (lambda (c)
782 (modify-syntax-entry c (cdr syn) table))
783 (car syn))))
784 (goto-char (point-max))
785 (imenu-progress-message prev-pos 0 t)
786 (unwind-protect ; for syntax table
787 (save-match-data
788 (set-syntax-table table)
790 ;; map over the elements of imenu-generic-expression
791 ;; (typically functions, variables ...)
792 (dolist (pat patterns)
793 (let ((menu-title (car pat))
794 (regexp (nth 1 pat))
795 (index (nth 2 pat))
796 (function (nth 3 pat))
797 (rest (nthcdr 4 pat))
798 start beg)
799 ;; Go backwards for convenience of adding items in order.
800 (goto-char (point-max))
801 (while (and (if (functionp regexp)
802 (funcall regexp)
803 (re-search-backward regexp nil t))
804 ;; Exit the loop if we get an empty match,
805 ;; because it means a bad regexp was specified.
806 (not (= (match-beginning 0) (match-end 0))))
807 (setq start (point))
808 ;; Record the start of the line in which the match starts.
809 ;; That's the official position of this definition.
810 (goto-char (match-beginning index))
811 (beginning-of-line)
812 (setq beg (point))
813 (imenu-progress-message prev-pos nil t)
814 ;; Add this sort of submenu only when we've found an
815 ;; item for it, avoiding empty, duff menus.
816 (unless (assoc menu-title index-alist)
817 (push (list menu-title) index-alist))
818 (if imenu-use-markers
819 (setq beg (copy-marker beg)))
820 (let ((item
821 (if function
822 (nconc (list (match-string-no-properties index)
823 beg function)
824 rest)
825 (cons (match-string-no-properties index)
826 beg)))
827 ;; This is the desired submenu,
828 ;; starting with its title (or nil).
829 (menu (assoc menu-title index-alist)))
830 ;; Insert the item unless it is already present.
831 (unless (member item (cdr menu))
832 (setcdr menu
833 (cons item (cdr menu)))))
834 ;; Go to the start of the match, to make sure we
835 ;; keep making progress backwards.
836 (goto-char start))))
837 (set-syntax-table old-table)))
838 (imenu-progress-message prev-pos 100 t)
839 ;; Sort each submenu by position.
840 ;; This is in case one submenu gets items from two different regexps.
841 (dolist (item index-alist)
842 (when (listp item)
843 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
844 (let ((main-element (assq nil index-alist)))
845 (nconc (delq main-element (delq 'dummy index-alist))
846 (cdr main-element)))))
848 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
850 ;;; The main functions for this package!
852 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
854 ;; See also info-lookup-find-item
855 (defun imenu-find-default (guess completions)
856 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
857 (catch 'found
858 (let ((case-fold-search t))
859 (if (assoc guess completions) guess
860 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
861 (concat "\\`" (regexp-quote guess))
862 (concat (regexp-quote guess) "\\'")
863 (regexp-quote guess)))
864 (dolist (x completions)
865 (if (string-match re (car x)) (throw 'found (car x)))))))))
867 (defun imenu--completion-buffer (index-alist &optional prompt)
868 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
870 Return one of the entries in index-alist or nil."
871 ;; Create a list for this buffer only when needed.
872 (let ((name (thing-at-point 'symbol))
873 choice
874 (prepared-index-alist
875 (if (not imenu-space-replacement) index-alist
876 (mapcar
877 (lambda (item)
878 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
879 (car item))
880 (cdr item)))
881 index-alist))))
882 (when (stringp name)
883 (setq name (or (imenu-find-default name prepared-index-alist) name)))
884 (cond (prompt)
885 ((and name (imenu--in-alist name prepared-index-alist))
886 (setq prompt (format "Index item (default %s): " name)))
887 (t (setq prompt "Index item: ")))
888 (let ((minibuffer-setup-hook minibuffer-setup-hook))
889 ;; Display the completion buffer.
890 (if (not imenu-eager-completion-buffer)
891 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
892 (setq name (completing-read prompt
893 prepared-index-alist
894 nil t nil 'imenu--history-list name)))
896 (when (stringp name)
897 (setq choice (assoc name prepared-index-alist))
898 (if (imenu--subalist-p choice)
899 (imenu--completion-buffer (cdr choice) prompt)
900 choice))))
902 (defun imenu--mouse-menu (index-alist event &optional title)
903 "Let the user select from a buffer index from a mouse menu.
905 INDEX-ALIST is the buffer index and EVENT is a mouse event.
907 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
908 (setq index-alist (imenu--split-submenus index-alist))
909 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
910 (map (imenu--create-keymap (car menu)
911 (cdr (if (< 1 (length (cdr menu)))
912 menu
913 (car (cdr menu)))))))
914 (popup-menu map event)))
916 (defun imenu-choose-buffer-index (&optional prompt alist)
917 "Let the user select from a buffer index and return the chosen index.
919 If the user originally activated this function with the mouse, a mouse
920 menu is used. Otherwise a completion buffer is used and the user is
921 prompted with PROMPT.
923 If you call this function with index alist ALIST, then it lets the user
924 select from ALIST.
926 With no index alist ALIST, it calls `imenu--make-index-alist' to
927 create the index alist.
929 If `imenu-use-popup-menu' is nil, then the completion buffer
930 is always used, no matter if the mouse was used or not.
932 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
933 (let (index-alist
934 (mouse-triggered (listp last-nonmenu-event))
935 (result t))
936 ;; If selected by mouse, see to that the window where the mouse is
937 ;; really is selected.
938 (and mouse-triggered
939 (not (equal last-nonmenu-event '(menu-bar)))
940 (let ((window (posn-window (event-start last-nonmenu-event))))
941 (or (framep window) (null window) (select-window window))))
942 ;; Create a list for this buffer only when needed.
943 (while (eq result t)
944 (setq index-alist (if alist alist (imenu--make-index-alist)))
945 (setq result
946 (if (and imenu-use-popup-menu
947 (or (eq imenu-use-popup-menu t) mouse-triggered))
948 (imenu--mouse-menu index-alist last-nonmenu-event)
949 (imenu--completion-buffer index-alist prompt)))
950 (and (equal result imenu--rescan-item)
951 (imenu--cleanup)
952 (setq result t imenu--index-alist nil)))
953 result))
955 ;;;###autoload
956 (defun imenu-add-to-menubar (name)
957 "Add an `imenu' entry to the menu bar for the current buffer.
958 NAME is a string used to name the menu bar item.
959 See the command `imenu' for more information."
960 (interactive "sImenu menu item name: ")
961 (if (or (and imenu-prev-index-position-function
962 imenu-extract-index-name-function)
963 imenu-generic-expression
964 (not (eq imenu-create-index-function
965 'imenu-default-create-index-function)))
966 (unless (keymapp (lookup-key (current-local-map) [menu-bar index]))
967 (let ((newmap (make-sparse-keymap)))
968 (set-keymap-parent newmap (current-local-map))
969 (setq imenu--last-menubar-index-alist nil)
970 (define-key newmap [menu-bar index]
971 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
972 (use-local-map newmap)
973 (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
974 (error "The mode `%s' does not support Imenu"
975 (format-mode-line mode-name))))
977 ;;;###autoload
978 (defun imenu-add-menubar-index ()
979 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
981 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
982 (interactive)
983 (imenu-add-to-menubar "Index"))
985 (defvar imenu-buffer-menubar nil)
987 (defvar imenu-menubar-modified-tick 0
988 "The value of (buffer-chars-modified-tick) as of the last call
989 to `imenu-update-menubar'.")
990 (make-variable-buffer-local 'imenu-menubar-modified-tick)
992 (defun imenu-update-menubar ()
993 (when (and (current-local-map)
994 (keymapp (lookup-key (current-local-map) [menu-bar index]))
995 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
996 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
997 (let ((index-alist (imenu--make-index-alist t)))
998 ;; Don't bother updating if the index-alist has not changed
999 ;; since the last time we did it.
1000 (unless (equal index-alist imenu--last-menubar-index-alist)
1001 (let (menu menu1 old)
1002 (setq imenu--last-menubar-index-alist index-alist)
1003 (setq index-alist (imenu--split-submenus index-alist))
1004 (setq menu (imenu--split-menu index-alist
1005 (buffer-name)))
1006 (setq menu1 (imenu--create-keymap (car menu)
1007 (cdr (if (< 1 (length (cdr menu)))
1008 menu
1009 (car (cdr menu))))
1010 'imenu--menubar-select))
1011 (setq old (lookup-key (current-local-map) [menu-bar index]))
1012 ;; This should never happen, but in some odd cases, potentially,
1013 ;; lookup-key may return a dynamically composed keymap.
1014 (if (keymapp (cadr old)) (setq old (cadr old)))
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 ;;; imenu.el ends here