* textmodes/reftex-vars.el (reftex-label-alist): Docfix.
[emacs.git] / lisp / imenu.el
blob8cef5161a37324ddca55f536eaa74bec80f67d01
1 ;;; imenu.el --- framework for mode-specific buffer indexes -*- lexical-binding: t -*-
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-lib))
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 (defmacro imenu-progress-message (_prevpos &optional _relpos _reverse)
270 "Macro to display a progress message.
271 RELPOS is the relative position to display.
272 If RELPOS is nil, then the relative position in the buffer
273 is calculated.
274 PREVPOS is the variable in which we store the last position displayed."
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 (goto-char (point-max))
343 ;; Search for the function
344 (while (beginning-of-defun)
345 (save-match-data
346 (and (looking-at "(def")
347 (save-excursion
348 (down-list 1)
349 (cond
350 ((looking-at "def\\(var\\|const\\)")
351 (forward-sexp 2)
352 (push (imenu-example--name-and-position)
353 index-var-alist))
354 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
355 (forward-sexp 2)
356 (push (imenu-example--name-and-position)
357 index-alist))
358 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
359 (forward-sexp 2)
360 (if (= (char-after (1- (point))) ?\))
361 (progn
362 (forward-sexp -1)
363 (down-list 1)
364 (forward-sexp 1)))
365 (push (imenu-example--name-and-position)
366 index-type-alist))
368 (forward-sexp 2)
369 (push (imenu-example--name-and-position)
370 index-unknown-alist)))))))
371 (and index-var-alist
372 (push (cons "Variables" index-var-alist)
373 index-alist))
374 (and index-type-alist
375 (push (cons "Types" index-type-alist)
376 index-alist))
377 (and index-unknown-alist
378 (push (cons "Syntax-unknown" index-unknown-alist)
379 index-alist))
380 index-alist))
381 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
383 ;; Regular expression to find C functions
384 (defvar imenu-example--function-name-regexp-c
385 (concat
386 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
387 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
388 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
389 "\\([*&]+[ \t]*\\)?" ; pointer
390 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
393 (defun imenu-example--create-c-index (&optional regexp)
394 (let ((index-alist '())
395 char)
396 (goto-char (point-min))
397 ;; Search for the function
398 (save-match-data
399 (while (re-search-forward
400 (or regexp imenu-example--function-name-regexp-c)
401 nil t)
402 (backward-up-list 1)
403 (save-excursion
404 (goto-char (scan-sexps (point) 1))
405 (setq char (following-char)))
406 ;; Skip this function name if it is a prototype declaration.
407 (if (not (eq char ?\;))
408 (push (imenu-example--name-and-position) index-alist))))
409 (nreverse index-alist)))
410 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
414 ;;; Internal variables
416 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
418 ;; The item to use in the index for rescanning the buffer.
419 (defconst imenu--rescan-item '("*Rescan*" . -99))
421 ;; The latest buffer index.
422 (defvar-local imenu--index-alist nil
423 "The buffer index alist computed for this buffer in Imenu.
425 Simple elements in the alist look like (INDEX-NAME . POSITION).
426 POSITION is the buffer position of the item; to go to the item
427 is simply to move point to that position.
429 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
430 To \"go to\" a special element means applying FUNCTION
431 to INDEX-NAME, POSITION, and the ARGUMENTS.
433 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
434 The function `imenu--subalist-p' tests an element and returns t
435 if it is a sub-alist.
437 There is one simple element with negative POSITION; selecting that
438 element recalculates the buffer's index alist.")
439 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
441 (defvar-local imenu--last-menubar-index-alist nil
442 "The latest buffer index alist used to update the menu bar menu.")
444 (defvar imenu--history-list nil
445 ;; Making this buffer local caused it not to work!
446 "History list for 'jump-to-function-in-buffer'.")
448 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
450 ;;; Internal support functions
452 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
454 (defun imenu--sort-by-name (item1 item2)
455 "Comparison function to sort items depending on their index name.
456 An item looks like (NAME . POSITION)."
457 (string-lessp (car item1) (car item2)))
459 (defun imenu--sort-by-position (item1 item2)
460 (< (cdr item1) (cdr item2)))
462 (defun imenu--relative-position (&optional reverse)
463 "Support function to calculate relative position in buffer.
464 Beginning of buffer is 0 and end of buffer is 100
465 If REVERSE is non-nil then the beginning is 100 and the end is 0."
466 (let ((pos (point))
467 (total (buffer-size)))
468 (and reverse (setq pos (- total pos)))
469 (if (> total 50000)
470 ;; Avoid overflow from multiplying by 100!
471 (/ (1- pos) (max (/ total 100) 1))
472 (/ (* 100 (1- pos)) (max total 1)))))
474 (defun imenu--split (list n)
475 "Split LIST into sublists of max length N.
476 Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
477 The returned list DOES NOT share structure with LIST."
478 (let ((remain list)
479 (result '())
480 (sublist '())
481 (i 0))
482 (while remain
483 (push (pop remain) sublist)
484 (cl-incf i)
485 (and (= i n)
486 ;; We have finished a sublist
487 (progn (push (nreverse sublist) result)
488 (setq i 0)
489 (setq sublist '()))))
490 ;; There might be a sublist (if the length of LIST mod n is != 0)
491 ;; that has to be added to the result list.
492 (and sublist
493 (push (nreverse sublist) result))
494 (nreverse result)))
496 (defun imenu--split-menu (menulist title)
497 "Split the alist MENULIST into a nested alist, if it is long enough.
498 In any case, add TITLE to the front of the alist.
499 If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
500 beginning of the returned alist.
501 The returned alist DOES NOT share structure with MENULIST."
502 (let ((menulist (copy-sequence menulist))
503 keep-at-top)
504 (if (memq imenu--rescan-item menulist)
505 (setq keep-at-top (list imenu--rescan-item)
506 menulist (delq imenu--rescan-item menulist)))
507 (dolist (item menulist)
508 (when (imenu--subalist-p item)
509 (push item keep-at-top)
510 (setq menulist (delq item menulist))))
511 (if imenu-sort-function
512 (setq menulist (sort menulist imenu-sort-function)))
513 (if (> (length menulist) imenu-max-items)
514 (setq menulist
515 (mapcar
516 (lambda (menu)
517 (cons (format "From: %s" (caar menu)) menu))
518 (imenu--split menulist imenu-max-items))))
519 (cons title
520 (nconc (nreverse keep-at-top) menulist))))
522 (defun imenu--split-submenus (alist)
523 "Split up each long alist that are nested within ALIST into nested alists.
524 Return a split and sorted copy of ALIST. The returned alist DOES
525 NOT share structure with ALIST."
526 (mapcar (lambda (elt)
527 (if (and (consp elt)
528 (stringp (car elt))
529 (listp (cdr elt)))
530 (imenu--split-menu (cdr elt) (car elt))
531 elt))
532 alist))
534 (defun imenu--truncate-items (menulist)
535 "Truncate all strings in MENULIST to `imenu-max-item-length'."
536 (mapcar (lambda (item)
537 (cond
538 ((consp (cdr item))
539 (imenu--truncate-items (cdr item)))
540 ;; truncate if necessary
541 ((and (numberp imenu-max-item-length)
542 (> (length (car item)) imenu-max-item-length))
543 (setcar item (substring (car item) 0 imenu-max-item-length)))))
544 menulist))
547 (defun imenu--make-index-alist (&optional noerror)
548 "Create an index alist for the definitions in the current buffer.
549 This works by using the hook function `imenu-create-index-function'.
550 Report an error if the list is empty unless NOERROR is supplied and
551 non-nil.
553 See `imenu--index-alist' for the format of the index alist."
554 (or (and imenu--index-alist
555 (or (not imenu-auto-rescan)
556 (and imenu-auto-rescan
557 (> (buffer-size) imenu-auto-rescan-maxout))))
558 ;; Get the index; truncate if necessary
559 (progn
560 (setq imenu--index-alist
561 (save-excursion
562 (save-restriction
563 (widen)
564 (funcall imenu-create-index-function))))
565 (imenu--truncate-items imenu--index-alist)))
566 (or imenu--index-alist noerror
567 (user-error "No items suitable for an index found in this buffer"))
568 (or imenu--index-alist
569 (setq imenu--index-alist (list nil)))
570 ;; Add a rescan option to the index.
571 (cons imenu--rescan-item imenu--index-alist))
573 (defvar imenu--cleanup-seen nil)
575 (defun imenu--cleanup (&optional alist)
576 "Find all markers in ALIST and make them point nowhere.
577 If ALIST is nil (the normal case), use `imenu--index-alist'.
578 Non-nil arguments are in recursive calls."
579 ;; If alist is provided use that list.
580 ;; If not, empty the table of lists already seen
581 ;; and use imenu--index-alist.
582 (if alist
583 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
584 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
586 (when alist
587 (dolist (item alist)
588 (cond
589 ((markerp (cdr item)) (set-marker (cdr item) nil))
590 ;; Don't process one alist twice.
591 ((memq (cdr item) imenu--cleanup-seen))
592 ((imenu--subalist-p item) (imenu--cleanup (cdr item)))))
595 (defun imenu--create-keymap (title alist &optional cmd)
596 `(keymap ,title
597 ,@(mapcar
598 (lambda (item)
599 `(,(car item) ,(car item)
600 ,@(cond
601 ((imenu--subalist-p item)
602 (imenu--create-keymap (car item) (cdr item) cmd))
604 `(lambda () (interactive)
605 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
606 alist)))
608 (defun imenu--in-alist (str alist)
609 "Check whether the string STR is contained in multi-level ALIST."
610 (let (elt head tail res)
611 (setq res nil)
612 (while alist
613 (setq elt (car alist)
614 tail (cdr elt)
615 alist (cdr alist)
616 head (car elt))
617 ;; A nested ALIST element looks like
618 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
619 ;; while a bottom-level element looks like
620 ;; (INDEX-NAME . INDEX-POSITION)
621 ;; We are only interested in the bottom-level elements, so we need to
622 ;; recurse if TAIL is a list.
623 (cond ((listp tail)
624 (if (setq res (imenu--in-alist str tail))
625 (setq alist nil)))
626 ((if imenu-name-lookup-function
627 (funcall imenu-name-lookup-function str head)
628 (string= str head))
629 (setq alist nil res elt))))
630 res))
632 (defvar imenu-syntax-alist nil
633 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
635 The car of the assocs may be either a character or a string and the
636 cdr is a syntax description appropriate for `modify-syntax-entry'. For
637 a string, all the characters in the string get the specified syntax.
639 This is typically used to give word syntax to characters which
640 normally have symbol syntax to simplify `imenu-expression'
641 and speed-up matching.")
642 ;;;###autoload
643 (make-variable-buffer-local 'imenu-syntax-alist)
645 (defun imenu-default-create-index-function ()
646 "Default function to create an index alist of the current buffer.
648 The most general method is to move point to end of buffer, then repeatedly call
649 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
650 All the results returned by the latter are gathered into an index alist.
651 This method is used if those two variables are non-nil.
653 The alternate method, which is the one most often used, is to call
654 `imenu--generic-function' with `imenu-generic-expression' as argument."
655 ;; These should really be done by setting imenu-create-index-function
656 ;; in these major modes. But save that change for later.
657 (cond ((and imenu-prev-index-position-function
658 imenu-extract-index-name-function)
659 (let ((index-alist '()) (pos (point))
660 name)
661 (goto-char (point-max))
662 ;; Search for the function
663 (while (funcall imenu-prev-index-position-function)
664 (when (= pos (point))
665 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
666 (setq pos (point))
667 (save-excursion
668 (setq name (funcall imenu-extract-index-name-function)))
669 (and (stringp name)
670 ;; [ydi] updated for imenu-use-markers
671 (push (cons name (if imenu-use-markers (point-marker) (point)))
672 index-alist)))
673 index-alist))
674 ;; Use generic expression if possible.
675 ((and imenu-generic-expression)
676 (imenu--generic-function imenu-generic-expression))
678 (user-error "This buffer cannot use `imenu-default-create-index-function'"))))
681 ;;; Generic index gathering function.
684 (defvar imenu-case-fold-search t
685 "Defines whether `imenu--generic-function' should fold case when matching.
687 This variable should be set (only) by initialization code
688 for modes which use `imenu--generic-function'. If it is not set, but
689 `font-lock-defaults' is set, then font-lock's setting is used.")
690 ;;;###autoload
691 (make-variable-buffer-local 'imenu-case-fold-search)
693 ;; This function can be called with quitting disabled,
694 ;; so it needs to be careful never to loop!
695 (defun imenu--generic-function (patterns)
696 "Return an index alist of the current buffer based on PATTERNS.
698 PATTERNS is an alist with elements that look like this:
699 (MENU-TITLE REGEXP INDEX)
700 or like this:
701 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
702 with zero or more ARGUMENTS. The former format creates a simple
703 element in the index alist when it matches; the latter creates a
704 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
705 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
707 MENU-TITLE is a string used as the title for the submenu or nil
708 if the entries are not nested.
710 REGEXP is a regexp that should match a construct in the buffer
711 that is to be displayed in the menu; i.e., function or variable
712 definitions, etc. It contains a substring which is the name to
713 appear in the menu. See the info section on Regexps for more
714 information. REGEXP may also be a function, called without
715 arguments. It is expected to search backwards. It shall return
716 true and set `match-data' if it finds another element.
718 INDEX points to the substring in REGEXP that contains the
719 name (of the function, variable or type) that is to appear in the
720 menu.
722 The variable `imenu-case-fold-search' determines whether or not the
723 regexp matches are case sensitive, and `imenu-syntax-alist' can be
724 used to alter the syntax table for the search.
726 See `lisp-imenu-generic-expression' for an example of PATTERNS.
728 Returns an index of the current buffer as an alist. The elements in
729 the alist look like:
730 (INDEX-NAME . INDEX-POSITION)
731 or like:
732 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
733 They may also be nested index alists like:
734 (INDEX-NAME . INDEX-ALIST)
735 depending on PATTERNS."
737 (let ((index-alist (list 'dummy))
738 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
739 (not (local-variable-p 'font-lock-defaults)))
740 imenu-case-fold-search
741 (nth 2 font-lock-defaults)))
742 (old-table (syntax-table))
743 (table (copy-syntax-table (syntax-table)))
744 (slist imenu-syntax-alist))
745 ;; Modify the syntax table used while matching regexps.
746 (dolist (syn slist)
747 ;; The character(s) to modify may be a single char or a string.
748 (if (numberp (car syn))
749 (modify-syntax-entry (car syn) (cdr syn) table)
750 (mapc (lambda (c)
751 (modify-syntax-entry c (cdr syn) table))
752 (car syn))))
753 (goto-char (point-max))
754 (unwind-protect ; for syntax table
755 (save-match-data
756 (set-syntax-table table)
758 ;; map over the elements of imenu-generic-expression
759 ;; (typically functions, variables ...)
760 (dolist (pat patterns)
761 (let ((menu-title (car pat))
762 (regexp (nth 1 pat))
763 (index (nth 2 pat))
764 (function (nth 3 pat))
765 (rest (nthcdr 4 pat))
766 start beg)
767 ;; Go backwards for convenience of adding items in order.
768 (goto-char (point-max))
769 (while (and (if (functionp regexp)
770 (funcall regexp)
771 (and
772 (re-search-backward regexp nil t)
773 ;; Do not count invisible definitions.
774 (let ((invis (invisible-p (point))))
775 (or (not invis)
776 (progn
777 (while (and invis
778 (not (bobp)))
779 (setq invis (not (re-search-backward
780 regexp nil 'move))))
781 (not invis))))))
782 ;; Exit the loop if we get an empty match,
783 ;; because it means a bad regexp was specified.
784 (not (= (match-beginning 0) (match-end 0))))
785 (setq start (point))
786 ;; Record the start of the line in which the match starts.
787 ;; That's the official position of this definition.
788 (goto-char (match-beginning index))
789 (beginning-of-line)
790 (setq beg (point))
791 ;; Add this sort of submenu only when we've found an
792 ;; item for it, avoiding empty, duff menus.
793 (unless (assoc menu-title index-alist)
794 (push (list menu-title) index-alist))
795 (if imenu-use-markers
796 (setq beg (copy-marker beg)))
797 (let ((item
798 (if function
799 (nconc (list (match-string-no-properties index)
800 beg function)
801 rest)
802 (cons (match-string-no-properties index)
803 beg)))
804 ;; This is the desired submenu,
805 ;; starting with its title (or nil).
806 (menu (assoc menu-title index-alist)))
807 ;; Insert the item unless it is already present.
808 (unless (member item (cdr menu))
809 (setcdr menu
810 (cons item (cdr menu)))))
811 ;; Go to the start of the match, to make sure we
812 ;; keep making progress backwards.
813 (goto-char start))))
814 (set-syntax-table old-table)))
815 ;; Sort each submenu by position.
816 ;; This is in case one submenu gets items from two different regexps.
817 (dolist (item index-alist)
818 (when (listp item)
819 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
820 (let ((main-element (assq nil index-alist)))
821 (nconc (delq main-element (delq 'dummy index-alist))
822 (cdr main-element)))))
824 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
826 ;;; The main functions for this package!
828 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
830 ;; See also info-lookup-find-item
831 (defun imenu-find-default (guess completions)
832 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
833 (catch 'found
834 (let ((case-fold-search t))
835 (if (assoc guess completions) guess
836 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
837 (concat "\\`" (regexp-quote guess))
838 (concat (regexp-quote guess) "\\'")
839 (regexp-quote guess)))
840 (dolist (x completions)
841 (if (string-match re (car x)) (throw 'found (car x)))))))))
843 (defun imenu--completion-buffer (index-alist &optional prompt)
844 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
846 Return one of the entries in index-alist or nil."
847 ;; Create a list for this buffer only when needed.
848 (let ((name (thing-at-point 'symbol))
849 choice
850 (prepared-index-alist
851 (if (not imenu-space-replacement) index-alist
852 (mapcar
853 (lambda (item)
854 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
855 (car item))
856 (cdr item)))
857 index-alist))))
858 (when (stringp name)
859 (setq name (or (imenu-find-default name prepared-index-alist) name)))
860 (cond (prompt)
861 ((and name (imenu--in-alist name prepared-index-alist))
862 (setq prompt (format "Index item (default %s): " name)))
863 (t (setq prompt "Index item: ")))
864 (let ((minibuffer-setup-hook minibuffer-setup-hook))
865 ;; Display the completion buffer.
866 (if (not imenu-eager-completion-buffer)
867 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
868 (setq name (completing-read prompt
869 prepared-index-alist
870 nil t nil 'imenu--history-list name)))
872 (when (stringp name)
873 (setq choice (assoc name prepared-index-alist))
874 (if (imenu--subalist-p choice)
875 (imenu--completion-buffer (cdr choice) prompt)
876 choice))))
878 (defun imenu--mouse-menu (index-alist event &optional title)
879 "Let the user select from a buffer index from a mouse menu.
881 INDEX-ALIST is the buffer index and EVENT is a mouse event.
883 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
884 (setq index-alist (imenu--split-submenus index-alist))
885 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
886 (map (imenu--create-keymap (car menu)
887 (cdr (if (< 1 (length (cdr menu)))
888 menu
889 (car (cdr menu)))))))
890 (popup-menu map event)))
892 (defun imenu-choose-buffer-index (&optional prompt alist)
893 "Let the user select from a buffer index and return the chosen index.
895 If the user originally activated this function with the mouse, a mouse
896 menu is used. Otherwise a completion buffer is used and the user is
897 prompted with PROMPT.
899 If you call this function with index alist ALIST, then it lets the user
900 select from ALIST.
902 With no index alist ALIST, it calls `imenu--make-index-alist' to
903 create the index alist.
905 If `imenu-use-popup-menu' is nil, then the completion buffer
906 is always used, no matter if the mouse was used or not.
908 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
909 (let (index-alist
910 (mouse-triggered (listp last-nonmenu-event))
911 (result t))
912 ;; If selected by mouse, see to that the window where the mouse is
913 ;; really is selected.
914 (and mouse-triggered
915 (not (equal last-nonmenu-event '(menu-bar)))
916 (let ((window (posn-window (event-start last-nonmenu-event))))
917 (or (framep window) (null window) (select-window window))))
918 ;; Create a list for this buffer only when needed.
919 (while (eq result t)
920 (setq index-alist (if alist alist (imenu--make-index-alist)))
921 (setq result
922 (if (and imenu-use-popup-menu
923 (or (eq imenu-use-popup-menu t) mouse-triggered))
924 (imenu--mouse-menu index-alist last-nonmenu-event)
925 (imenu--completion-buffer index-alist prompt)))
926 (and (equal result imenu--rescan-item)
927 (imenu--cleanup)
928 (setq result t imenu--index-alist nil)))
929 result))
931 ;;;###autoload
932 (defun imenu-add-to-menubar (name)
933 "Add an `imenu' entry to the menu bar for the current buffer.
934 NAME is a string used to name the menu bar item.
935 See the command `imenu' for more information."
936 (interactive "sImenu menu item name: ")
937 (if (or (and imenu-prev-index-position-function
938 imenu-extract-index-name-function)
939 imenu-generic-expression
940 (not (eq imenu-create-index-function
941 'imenu-default-create-index-function)))
942 (unless (and (current-local-map)
943 (keymapp (lookup-key (current-local-map) [menu-bar index])))
944 (let ((newmap (make-sparse-keymap)))
945 (set-keymap-parent newmap (current-local-map))
946 (setq imenu--last-menubar-index-alist nil)
947 (define-key newmap [menu-bar index]
948 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
949 (use-local-map newmap)
950 (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
951 (user-error "The mode `%s' does not support Imenu"
952 (format-mode-line mode-name))))
954 ;;;###autoload
955 (defun imenu-add-menubar-index ()
956 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
958 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
959 (interactive)
960 (imenu-add-to-menubar "Index"))
962 (defvar imenu-buffer-menubar nil)
964 (defvar-local imenu-menubar-modified-tick 0
965 "The value of (buffer-chars-modified-tick) as of the last call
966 to `imenu-update-menubar'.")
968 (defun imenu-update-menubar ()
969 (when (and (current-local-map)
970 (keymapp (lookup-key (current-local-map) [menu-bar index]))
971 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
972 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
973 (let ((index-alist (imenu--make-index-alist t)))
974 ;; Don't bother updating if the index-alist has not changed
975 ;; since the last time we did it.
976 (unless (equal index-alist imenu--last-menubar-index-alist)
977 (let (menu menu1 old)
978 (setq imenu--last-menubar-index-alist index-alist)
979 (setq index-alist (imenu--split-submenus index-alist))
980 (setq menu (imenu--split-menu index-alist
981 (buffer-name)))
982 (setq menu1 (imenu--create-keymap (car menu)
983 (cdr (if (< 1 (length (cdr menu)))
984 menu
985 (car (cdr menu))))
986 'imenu--menubar-select))
987 (setq old (lookup-key (current-local-map) [menu-bar index]))
988 ;; This should never happen, but in some odd cases, potentially,
989 ;; lookup-key may return a dynamically composed keymap.
990 (if (keymapp (cadr old)) (setq old (cadr old)))
991 (setcdr old (cdr menu1)))))))
993 (defun imenu--menubar-select (item)
994 "Use Imenu to select the function or variable named in this menu ITEM."
995 (if (equal item imenu--rescan-item)
996 (progn
997 (imenu--cleanup)
998 ;; Make sure imenu-update-menubar redoes everything.
999 (setq imenu-menubar-modified-tick -1)
1000 (setq imenu--index-alist nil)
1001 (setq imenu--last-menubar-index-alist nil)
1002 (imenu-update-menubar)
1004 (imenu item)
1005 nil))
1007 (defun imenu-default-goto-function (_name position &optional _rest)
1008 "Move to the given position.
1010 NAME is ignored. POSITION is where to move. REST is also ignored.
1011 The ignored args just make this function have the same interface as a
1012 function placed in a special index-item."
1013 (if (or (< position (point-min))
1014 (> position (point-max)))
1015 ;; widen if outside narrowing
1016 (widen))
1017 (goto-char position))
1019 ;;;###autoload
1020 (defun imenu (index-item)
1021 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1022 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1023 for more information."
1024 (interactive (list (imenu-choose-buffer-index)))
1025 ;; Convert a string to an alist element.
1026 (if (stringp index-item)
1027 (setq index-item (assoc index-item (imenu--make-index-alist))))
1028 (when index-item
1029 (push-mark)
1030 (let* ((is-special-item (listp (cdr index-item)))
1031 (function
1032 (if is-special-item
1033 (nth 2 index-item) imenu-default-goto-function))
1034 (position (if is-special-item
1035 (cadr index-item) (cdr index-item)))
1036 (rest (if is-special-item (cddr index-item))))
1037 (apply function (car index-item) position rest))
1038 (run-hooks 'imenu-after-jump-hook)))
1040 (provide 'imenu)
1042 ;;; imenu.el ends here