Merge branch 'master' into comment-cache
[emacs.git] / lisp / imenu.el
blob0f47a92734ea656b9067d372bc0faad6098bc68a
1 ;;; imenu.el --- framework for mode-specific buffer indexes -*- lexical-binding: t -*-
3 ;; Copyright (C) 1994-1998, 2001-2017 Free Software Foundation, Inc.
5 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
6 ;; Lars Lindberg <lli@sypro.cap.se>
7 ;; Maintainer: emacs-devel@gnu.org
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 (defcustom imenu-generic-skip-comments-and-strings t
189 "When non-nil, ignore text inside comments and strings.
190 Only affects `imenu--generic-function'."
191 :type 'boolean
192 :group 'imenu
193 :version "24.4")
195 ;;;###autoload
196 (defvar imenu-generic-expression nil
197 "List of definition matchers for creating an Imenu index.
198 Each element of this list should have the form
200 (MENU-TITLE REGEXP INDEX [FUNCTION] [ARGUMENTS...])
202 MENU-TITLE should be nil (in which case the matches for this
203 element are put in the top level of the buffer index) or a
204 string (which specifies the title of a submenu into which the
205 matches are put).
206 REGEXP is a regular expression matching a definition construct
207 which is to be displayed in the menu. REGEXP may also be a
208 function, called without arguments. It is expected to search
209 backwards. It must return true and set `match-data' if it finds
210 another element.
211 INDEX is an integer specifying which subexpression of REGEXP
212 matches the definition's name; this subexpression is displayed as
213 the menu item.
214 FUNCTION, if present, specifies a function to call when the index
215 item is selected by the user. This function is called with
216 arguments consisting of the item name, the buffer position, and
217 the ARGUMENTS.
219 The variable `imenu-case-fold-search' determines whether or not
220 the regexp matches are case sensitive, and `imenu-syntax-alist'
221 can be used to alter the syntax table for the search.
223 If non-nil this pattern is passed to `imenu--generic-function' to
224 create a buffer index.
226 For example, see the value of `fortran-imenu-generic-expression'
227 used by `fortran-mode' with `imenu-syntax-alist' set locally to
228 give the characters which normally have \"symbol\" syntax
229 \"word\" syntax during matching.")
230 ;;;###autoload(put 'imenu-generic-expression 'risky-local-variable t)
232 ;;;###autoload
233 (make-variable-buffer-local 'imenu-generic-expression)
235 ;;;; Hooks
237 ;;;###autoload
238 (defvar imenu-create-index-function 'imenu-default-create-index-function
239 "The function to use for creating an index alist of the current buffer.
241 It should be a function that takes no arguments and returns
242 an index alist of the current buffer. The function is
243 called within a `save-excursion'.
245 See `imenu--index-alist' for the format of the buffer index alist.")
246 ;;;###autoload
247 (make-variable-buffer-local 'imenu-create-index-function)
249 ;;;###autoload
250 (defvar imenu-prev-index-position-function 'beginning-of-defun
251 "Function for finding the next index position.
253 If `imenu-create-index-function' is set to
254 `imenu-default-create-index-function', then you must set this variable
255 to a function that will find the next index, looking backwards in the
256 file.
258 The function should leave point at the place to be connected to the
259 index and it should return nil when it doesn't find another index.")
260 ;;;###autoload
261 (make-variable-buffer-local 'imenu-prev-index-position-function)
263 ;;;###autoload
264 (defvar imenu-extract-index-name-function nil
265 "Function for extracting the index item name, given a position.
267 This function is called after `imenu-prev-index-position-function'
268 finds a position for an index item, with point at that position.
269 It should return the name for that index item.")
270 ;;;###autoload
271 (make-variable-buffer-local 'imenu-extract-index-name-function)
273 ;;;###autoload
274 (defvar imenu-name-lookup-function nil
275 "Function to compare string with index item.
277 This function will be called with two strings, and should return
278 non-nil if they match.
280 If nil, comparison is done with `string='.
281 Set this to some other function for more advanced comparisons,
282 such as \"begins with\" or \"name matches and number of
283 arguments match\".")
284 ;;;###autoload
285 (make-variable-buffer-local 'imenu-name-lookup-function)
287 ;;;###autoload
288 (defvar imenu-default-goto-function 'imenu-default-goto-function
289 "The default function called when selecting an Imenu item.
290 The function in this variable is called when selecting a normal index-item.")
291 ;;;###autoload
292 (make-variable-buffer-local 'imenu-default-goto-function)
295 (defun imenu--subalist-p (item)
296 (and (consp item)
297 (consp (cdr item))
298 (listp (cadr item))
299 (not (functionp (cadr item)))))
301 (defmacro imenu-progress-message (_prevpos &optional _relpos _reverse)
302 "Macro to display a progress message.
303 RELPOS is the relative position to display.
304 If RELPOS is nil, then the relative position in the buffer
305 is calculated.
306 PREVPOS is the variable in which we store the last position displayed."
308 ;; Made obsolete/empty, as computers are now faster than the eye, and
309 ;; it had problems updating the messages correctly, and could shadow
310 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
312 ;; `(and
313 ;; imenu-scanning-message
314 ;; (let ((pos ,(if relpos
315 ;; relpos
316 ;; `(imenu--relative-position ,reverse))))
317 ;; (if ,(if relpos t
318 ;; `(> pos (+ 5 ,prevpos)))
319 ;; (progn
320 ;; (message imenu-scanning-message pos)
321 ;; (setq ,prevpos pos)))))
325 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
326 ;;;;
327 ;;;; Some examples of functions utilizing the framework of this
328 ;;;; package.
329 ;;;;
330 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
332 ;; FIXME: This was the only imenu-example-* definition actually used,
333 ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
334 ;; all be removed.
335 (defun imenu-example--name-and-position ()
336 "Return the current/previous sexp and its (beginning) location.
337 Don't move point."
338 (declare (obsolete "use your own function instead." "23.2"))
339 (save-excursion
340 (forward-sexp -1)
341 ;; [ydi] modified for imenu-use-markers
342 (let ((beg (if imenu-use-markers (point-marker) (point)))
343 (end (progn (forward-sexp) (point))))
344 (cons (buffer-substring beg end)
345 beg))))
348 ;;; Lisp
351 (define-error 'imenu-unavailable "imenu unavailable")
353 (defun imenu-unavailable-error (format &rest args)
354 (signal 'imenu-unavailable
355 (list (apply #'format-message format args))))
357 (defun imenu-example--lisp-extract-index-name ()
358 ;; Example of a candidate for `imenu-extract-index-name-function'.
359 ;; This will generate a flat index of definitions in a lisp file.
360 (declare (obsolete nil "23.2"))
361 (save-match-data
362 (and (looking-at "(def")
363 (condition-case nil
364 (progn
365 (down-list 1)
366 (forward-sexp 2)
367 (let ((beg (point))
368 (end (progn (forward-sexp -1) (point))))
369 (buffer-substring beg end)))
370 (error nil)))))
372 (defun imenu-example--create-lisp-index ()
373 ;; Example of a candidate for `imenu-create-index-function'.
374 ;; It will generate a nested index of definitions.
375 (declare (obsolete nil "23.2"))
376 (let ((index-alist '())
377 (index-var-alist '())
378 (index-type-alist '())
379 (index-unknown-alist '()))
380 (goto-char (point-max))
381 ;; Search for the function
382 (while (beginning-of-defun)
383 (save-match-data
384 (and (looking-at "(def")
385 (save-excursion
386 (down-list 1)
387 (cond
388 ((looking-at "def\\(var\\|const\\)")
389 (forward-sexp 2)
390 (push (imenu-example--name-and-position)
391 index-var-alist))
392 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
393 (forward-sexp 2)
394 (push (imenu-example--name-and-position)
395 index-alist))
396 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
397 (forward-sexp 2)
398 (if (= (char-after (1- (point))) ?\))
399 (progn
400 (forward-sexp -1)
401 (down-list 1)
402 (forward-sexp 1)))
403 (push (imenu-example--name-and-position)
404 index-type-alist))
406 (forward-sexp 2)
407 (push (imenu-example--name-and-position)
408 index-unknown-alist)))))))
409 (and index-var-alist
410 (push (cons "Variables" index-var-alist)
411 index-alist))
412 (and index-type-alist
413 (push (cons "Types" index-type-alist)
414 index-alist))
415 (and index-unknown-alist
416 (push (cons "Syntax-unknown" index-unknown-alist)
417 index-alist))
418 index-alist))
420 ;; Regular expression to find C functions
421 (defvar imenu-example--function-name-regexp-c
422 (concat
423 "^[a-zA-Z0-9]+[ \t]?" ; Type specs; there can be no
424 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
425 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
426 "\\([*&]+[ \t]*\\)?" ; Pointer.
427 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; Name.
430 (defun imenu-example--create-c-index (&optional regexp)
431 (declare (obsolete nil "23.2"))
432 (let ((index-alist '())
433 char)
434 (goto-char (point-min))
435 ;; Search for the function
436 (save-match-data
437 (while (re-search-forward
438 (or regexp imenu-example--function-name-regexp-c)
439 nil t)
440 (backward-up-list 1)
441 (save-excursion
442 (goto-char (scan-sexps (point) 1))
443 (setq char (following-char)))
444 ;; Skip this function name if it is a prototype declaration.
445 (if (not (eq char ?\;))
446 (push (imenu-example--name-and-position) index-alist))))
447 (nreverse index-alist)))
449 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
451 ;;; Internal variables
453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
455 ;; The item to use in the index for rescanning the buffer.
456 (defconst imenu--rescan-item '("*Rescan*" . -99))
458 ;; The latest buffer index.
459 (defvar-local imenu--index-alist nil
460 "The buffer index alist computed for this buffer in Imenu.
462 Simple elements in the alist look like (INDEX-NAME . POSITION).
463 POSITION is the buffer position of the item; to go to the item
464 is simply to move point to that position.
466 POSITION is passed to `imenu-default-goto-function', so it can be
467 a non-number if that variable has been changed (e.g. Semantic
468 uses overlays for POSITIONs).
470 Special elements look like
471 \(INDEX-NAME POSITION FUNCTION ARGUMENTS...).
472 To \"go to\" a special element means applying FUNCTION to
473 INDEX-NAME, POSITION, and the ARGUMENTS.
475 A nested sub-alist element looks like (INDEX-NAME . SUB-ALIST).
476 The function `imenu--subalist-p' tests an element and returns t
477 if it is a sub-alist.
479 There is one simple element with negative POSITION; selecting that
480 element recalculates the buffer's index alist.")
481 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
483 (defvar-local imenu--last-menubar-index-alist nil
484 "The latest buffer index alist used to update the menu bar menu.")
486 (defvar imenu--history-list nil
487 ;; Making this buffer local caused it not to work!
488 "History list for `jump-to-function-in-buffer'.")
490 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
492 ;;; Internal support functions
494 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
496 (defun imenu--sort-by-name (item1 item2)
497 "Comparison function to sort items depending on their index name.
498 An item looks like (NAME . POSITION)."
499 (string-lessp (car item1) (car item2)))
501 (defun imenu--sort-by-position (item1 item2)
502 (< (cdr item1) (cdr item2)))
504 (defun imenu--relative-position (&optional reverse)
505 "Support function to calculate relative position in buffer.
506 Beginning of buffer is 0 and end of buffer is 100
507 If REVERSE is non-nil then the beginning is 100 and the end is 0."
508 (let ((pos (point))
509 (total (buffer-size)))
510 (and reverse (setq pos (- total pos)))
511 (floor (* 100.0 (1- pos)) (max total 1))))
513 (defun imenu--split (list n)
514 "Split LIST into sublists of max length N.
515 Example (imenu--split \\='(1 2 3 4 5 6 7 8) 3) => ((1 2 3) (4 5 6) (7 8))
516 The returned list DOES NOT share structure with LIST."
517 (let ((remain list)
518 (result '())
519 (sublist '())
520 (i 0))
521 (while remain
522 (push (pop remain) sublist)
523 (cl-incf i)
524 (and (= i n)
525 ;; We have finished a sublist
526 (progn (push (nreverse sublist) result)
527 (setq i 0)
528 (setq sublist '()))))
529 ;; There might be a sublist (if the length of LIST mod n is != 0)
530 ;; that has to be added to the result list.
531 (and sublist
532 (push (nreverse sublist) result))
533 (nreverse result)))
535 (defun imenu--split-menu (menulist title)
536 "Split the alist MENULIST into a nested alist, if it is long enough.
537 In any case, add TITLE to the front of the alist.
538 If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
539 beginning of the returned alist.
540 The returned alist DOES NOT share structure with MENULIST."
541 (let ((menulist (copy-sequence menulist))
542 keep-at-top)
543 (if (memq imenu--rescan-item menulist)
544 (setq keep-at-top (list imenu--rescan-item)
545 menulist (delq imenu--rescan-item menulist)))
546 (dolist (item menulist)
547 (when (imenu--subalist-p item)
548 (push item keep-at-top)
549 (setq menulist (delq item menulist))))
550 (if imenu-sort-function
551 (setq menulist (sort menulist imenu-sort-function)))
552 (if (> (length menulist) imenu-max-items)
553 (setq menulist
554 (mapcar
555 (lambda (menu)
556 (cons (format "From: %s" (caar menu)) menu))
557 (imenu--split menulist imenu-max-items))))
558 (cons title
559 (nconc (nreverse keep-at-top) menulist))))
561 (defun imenu--split-submenus (alist)
562 "Split up each long alist that are nested within ALIST into nested alists.
563 Return a split and sorted copy of ALIST. The returned alist DOES
564 NOT share structure with ALIST."
565 (mapcar (lambda (elt)
566 (if (imenu--subalist-p elt)
567 (imenu--split-menu (cdr elt) (car elt))
568 elt))
569 alist))
571 (defun imenu--truncate-items (menulist)
572 "Truncate all strings in MENULIST to `imenu-max-item-length'."
573 (mapc (lambda (item)
574 ;; Truncate if necessary.
575 (when (and (numberp imenu-max-item-length)
576 (> (length (car item)) imenu-max-item-length))
577 (setcar item (substring (car item) 0 imenu-max-item-length)))
578 (when (imenu--subalist-p item)
579 (imenu--truncate-items (cdr item))))
580 menulist))
582 (defun imenu--make-index-alist (&optional noerror)
583 "Create an index alist for the definitions in the current buffer.
584 This works by using the hook function `imenu-create-index-function'.
585 Report an error if the list is empty unless NOERROR is supplied and
586 non-nil.
588 See `imenu--index-alist' for the format of the index alist."
589 (or (and imenu--index-alist
590 (or (not imenu-auto-rescan)
591 (and imenu-auto-rescan
592 (> (buffer-size) imenu-auto-rescan-maxout))))
593 ;; Get the index; truncate if necessary.
594 (progn
595 (setq imenu--index-alist
596 (save-excursion
597 (save-restriction
598 (widen)
599 (funcall imenu-create-index-function))))
600 (imenu--truncate-items imenu--index-alist)))
601 (or imenu--index-alist noerror
602 (imenu-unavailable-error
603 "No items suitable for an index found in this buffer"))
604 (or imenu--index-alist
605 (setq imenu--index-alist (list nil)))
606 ;; Add a rescan option to the index.
607 (cons imenu--rescan-item imenu--index-alist))
609 (defvar imenu--cleanup-seen nil)
611 (defun imenu--cleanup (&optional alist)
612 "Find all markers in ALIST and make them point nowhere.
613 If ALIST is nil (the normal case), use `imenu--index-alist'.
614 Non-nil arguments are in recursive calls."
615 ;; If alist is provided use that list.
616 ;; If not, empty the table of lists already seen
617 ;; and use imenu--index-alist.
618 (if alist
619 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
620 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
622 (when alist
623 (dolist (item alist)
624 (cond
625 ((markerp (cdr item)) (set-marker (cdr item) nil))
626 ;; Don't process one alist twice.
627 ((memq (cdr item) imenu--cleanup-seen))
628 ((imenu--subalist-p item) (imenu--cleanup (cdr item)))))
631 (defun imenu--create-keymap (title alist &optional cmd)
632 `(keymap ,title
633 ,@(mapcar
634 (lambda (item)
635 `(,(car item) ,(car item)
636 ,@(cond
637 ((imenu--subalist-p item)
638 (imenu--create-keymap (car item) (cdr item) cmd))
640 `(lambda () (interactive)
641 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
642 alist)))
644 (defun imenu--in-alist (str alist)
645 "Check whether the string STR is contained in multi-level ALIST."
646 (let (elt head tail res)
647 (setq res nil)
648 (while alist
649 (setq elt (car alist)
650 tail (cdr elt)
651 alist (cdr alist)
652 head (car elt))
653 ;; A nested ALIST element looks like
654 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
655 ;; while a bottom-level element looks like
656 ;; (INDEX-NAME . INDEX-POSITION)
657 ;; or
658 ;; (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
659 ;; We are only interested in the bottom-level elements, so we need to
660 ;; recurse if TAIL is a nested ALIST.
661 (cond ((imenu--subalist-p elt)
662 (if (setq res (imenu--in-alist str tail))
663 (setq alist nil)))
664 ((if imenu-name-lookup-function
665 (funcall imenu-name-lookup-function str head)
666 (string= str head))
667 (setq alist nil res elt))))
668 res))
670 (defvar imenu-syntax-alist nil
671 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
673 The car of the assocs may be either a character or a string and the
674 cdr is a syntax description appropriate for `modify-syntax-entry'. For
675 a string, all the characters in the string get the specified syntax.
677 This is typically used to give word syntax to characters which
678 normally have symbol syntax to simplify `imenu-expression'
679 and speed-up matching.")
680 ;;;###autoload
681 (make-variable-buffer-local 'imenu-syntax-alist)
683 (defun imenu-default-create-index-function ()
684 "Default function to create an index alist of the current buffer.
686 The most general method is to move point to end of buffer, then repeatedly call
687 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
688 All the results returned by the latter are gathered into an index alist.
689 This method is used if those two variables are non-nil.
691 The alternate method, which is the one most often used, is to call
692 `imenu--generic-function' with `imenu-generic-expression' as argument."
693 ;; These should really be done by setting imenu-create-index-function
694 ;; in these major modes. But save that change for later.
695 (cond ((and imenu-prev-index-position-function
696 imenu-extract-index-name-function)
697 (let ((index-alist '()) (pos (point-max))
698 name)
699 (goto-char pos)
700 ;; Search for the function
701 (while (funcall imenu-prev-index-position-function)
702 (unless (< (point) pos)
703 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
704 (setq pos (point))
705 (save-excursion
706 (setq name (funcall imenu-extract-index-name-function)))
707 (and (stringp name)
708 ;; [ydi] Updated for imenu-use-markers.
709 (push (cons name
710 (if imenu-use-markers (point-marker) (point)))
711 index-alist)))
712 index-alist))
713 ;; Use generic expression if possible.
714 ((and imenu-generic-expression)
715 (imenu--generic-function imenu-generic-expression))
717 (imenu-unavailable-error "This buffer cannot use `imenu-default-create-index-function'"))))
720 ;;; Generic index gathering function.
723 (defvar imenu-case-fold-search t
724 "Defines whether `imenu--generic-function' should fold case when matching.
726 This variable should be set (only) by initialization code
727 for modes which use `imenu--generic-function'. If it is not set, but
728 `font-lock-defaults' is set, then font-lock's setting is used.")
729 ;;;###autoload
730 (make-variable-buffer-local 'imenu-case-fold-search)
732 ;; This function can be called with quitting disabled,
733 ;; so it needs to be careful never to loop!
734 (defun imenu--generic-function (patterns)
735 "Return an index alist of the current buffer based on PATTERNS.
736 PATTERNS should be an alist with the same form as `imenu-generic-expression'.
738 If `imenu-generic-skip-comments-and-strings' is non-nil, this ignores
739 text inside comments and strings.
741 If `imenu-case-fold-search' is non-nil, this ignores case.
743 The return value is an alist of the form
744 (INDEX-NAME . INDEX-POSITION)
746 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
747 The return value may also consist of nested index alists like:
748 (INDEX-NAME . INDEX-ALIST)
749 depending on PATTERNS."
750 (let ((index-alist (list 'dummy))
751 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
752 (not (local-variable-p 'font-lock-defaults)))
753 imenu-case-fold-search
754 (nth 2 font-lock-defaults)))
755 (old-table (syntax-table))
756 (table (copy-syntax-table (syntax-table)))
757 (slist imenu-syntax-alist))
758 ;; Modify the syntax table used while matching regexps.
759 (dolist (syn slist)
760 ;; The character(s) to modify may be a single char or a string.
761 (if (numberp (car syn))
762 (modify-syntax-entry (car syn) (cdr syn) table)
763 (mapc (lambda (c)
764 (modify-syntax-entry c (cdr syn) table))
765 (car syn))))
766 (goto-char (point-max))
767 (unwind-protect ; For syntax table.
768 (save-match-data
769 (set-syntax-table table)
771 ;; Map over the elements of imenu-generic-expression
772 ;; (typically functions, variables ...).
773 (dolist (pat patterns)
774 (let ((menu-title (car pat))
775 (regexp (nth 1 pat))
776 (index (nth 2 pat))
777 (function (nth 3 pat))
778 (rest (nthcdr 4 pat))
779 start beg)
780 ;; Go backwards for convenience of adding items in order.
781 (goto-char (point-max))
782 (while (and (if (functionp regexp)
783 (funcall regexp)
784 (and
785 (re-search-backward regexp nil t)
786 ;; Do not count invisible definitions.
787 (let ((invis (invisible-p (point))))
788 (or (not invis)
789 (progn
790 (while (and invis
791 (not (bobp)))
792 (setq invis (not (re-search-backward
793 regexp nil 'move))))
794 (not invis))))))
795 ;; Exit the loop if we get an empty match,
796 ;; because it means a bad regexp was specified.
797 (not (= (match-beginning 0) (match-end 0))))
798 (setq start (point))
799 ;; Record the start of the line in which the match starts.
800 ;; That's the official position of this definition.
801 (goto-char (match-beginning index))
802 (beginning-of-line)
803 (setq beg (point))
804 ;; Add this sort of submenu only when we've found an
805 ;; item for it, avoiding empty, duff menus.
806 (unless (assoc menu-title index-alist)
807 (push (list menu-title) index-alist))
808 (if imenu-use-markers
809 (setq beg (copy-marker beg)))
810 (let ((item
811 (if function
812 (nconc (list (match-string-no-properties index)
813 beg function)
814 rest)
815 (cons (match-string-no-properties index)
816 beg)))
817 ;; This is the desired submenu,
818 ;; starting with its title (or nil).
819 (menu (assoc menu-title index-alist)))
820 ;; Insert the item unless it is already present.
821 (unless (or (member item (cdr menu))
822 (and imenu-generic-skip-comments-and-strings
823 (nth 8 (syntax-ppss))))
824 (setcdr menu
825 (cons item (cdr menu)))))
826 ;; Go to the start of the match, to make sure we
827 ;; keep making progress backwards.
828 (goto-char start))))
829 (set-syntax-table old-table)))
830 ;; Sort each submenu by position.
831 ;; This is in case one submenu gets items from two different regexps.
832 (dolist (item index-alist)
833 (when (listp item)
834 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
835 (let ((main-element (assq nil index-alist)))
836 (nconc (delq main-element (delq 'dummy index-alist))
837 (cdr main-element)))))
839 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
841 ;;; The main functions for this package!
843 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
845 ;; See also info-lookup-find-item
846 (defun imenu-find-default (guess completions)
847 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
848 (catch 'found
849 (let ((case-fold-search t))
850 (if (assoc guess completions) guess
851 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
852 (concat "\\`" (regexp-quote guess))
853 (concat (regexp-quote guess) "\\'")
854 (regexp-quote guess)))
855 (dolist (x completions)
856 (if (string-match re (car x)) (throw 'found (car x)))))))))
858 (defun imenu--completion-buffer (index-alist &optional prompt)
859 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
861 Return one of the entries in index-alist or nil."
862 ;; Create a list for this buffer only when needed.
863 (let ((name (thing-at-point 'symbol))
864 choice
865 (prepared-index-alist
866 (if (not imenu-space-replacement) index-alist
867 (mapcar
868 (lambda (item)
869 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
870 (car item))
871 (cdr item)))
872 index-alist))))
873 (when (stringp name)
874 (setq name (or (imenu-find-default name prepared-index-alist) name)))
875 (cond (prompt)
876 ((and name (imenu--in-alist name prepared-index-alist))
877 (setq prompt (format "Index item (default %s): " name)))
878 (t (setq prompt "Index item: ")))
879 (let ((minibuffer-setup-hook minibuffer-setup-hook))
880 ;; Display the completion buffer.
881 (if (not imenu-eager-completion-buffer)
882 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
883 (setq name (completing-read prompt
884 prepared-index-alist
885 nil t nil 'imenu--history-list name)))
887 (when (stringp name)
888 (setq choice (assoc name prepared-index-alist))
889 (if (imenu--subalist-p choice)
890 (imenu--completion-buffer (cdr choice) prompt)
891 choice))))
893 (defun imenu--mouse-menu (index-alist event &optional title)
894 "Let the user select from a buffer index from a mouse menu.
896 INDEX-ALIST is the buffer index and EVENT is a mouse event.
898 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
899 (setq index-alist (imenu--split-submenus index-alist))
900 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
901 (map (imenu--create-keymap (car menu)
902 (cdr (if (< 1 (length (cdr menu)))
903 menu
904 (car (cdr menu)))))))
905 (popup-menu map event)))
907 (defun imenu-choose-buffer-index (&optional prompt alist)
908 "Let the user select from a buffer index and return the chosen index.
910 If the user originally activated this function with the mouse, a mouse
911 menu is used. Otherwise a completion buffer is used and the user is
912 prompted with PROMPT.
914 If you call this function with index alist ALIST, then it lets the user
915 select from ALIST.
917 With no index alist ALIST, it calls `imenu--make-index-alist' to
918 create the index alist.
920 If `imenu-use-popup-menu' is nil, then the completion buffer
921 is always used, no matter if the mouse was used or not.
923 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
924 (let (index-alist
925 (mouse-triggered (listp last-nonmenu-event))
926 (result t))
927 ;; If selected by mouse, see to that the window where the mouse is
928 ;; really is selected.
929 (and mouse-triggered
930 (not (equal last-nonmenu-event '(menu-bar)))
931 (let ((window (posn-window (event-start last-nonmenu-event))))
932 (or (framep window) (null window) (select-window window))))
933 ;; Create a list for this buffer only when needed.
934 (while (eq result t)
935 (setq index-alist (if alist alist (imenu--make-index-alist)))
936 (setq result
937 (if (and imenu-use-popup-menu
938 (or (eq imenu-use-popup-menu t) mouse-triggered))
939 (imenu--mouse-menu index-alist last-nonmenu-event)
940 (imenu--completion-buffer index-alist prompt)))
941 (and (equal result imenu--rescan-item)
942 (imenu--cleanup)
943 (setq result t imenu--index-alist nil)))
944 result))
946 (defvar-local imenu--menubar-keymap nil)
948 ;;;###autoload
949 (defun imenu-add-to-menubar (name)
950 "Add an `imenu' entry to the menu bar for the current buffer.
951 NAME is a string used to name the menu bar item.
952 See the command `imenu' for more information."
953 (interactive "sImenu menu item name: ")
954 (if (or (and imenu-prev-index-position-function
955 imenu-extract-index-name-function)
956 imenu-generic-expression
957 (not (eq imenu-create-index-function
958 'imenu-default-create-index-function)))
959 (unless (and (current-local-map)
960 (keymapp (lookup-key (current-local-map) [menu-bar index])))
961 (let ((newmap (make-sparse-keymap)))
962 (set-keymap-parent newmap (current-local-map))
963 (setq imenu--last-menubar-index-alist nil)
964 (setq imenu--menubar-keymap (make-sparse-keymap "Imenu"))
965 (define-key newmap [menu-bar index]
966 `(menu-item ,name ,imenu--menubar-keymap))
967 (use-local-map newmap)
968 (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
969 (imenu-unavailable-error "The mode `%s' does not support Imenu"
970 (format-mode-line mode-name))))
972 ;;;###autoload
973 (defun imenu-add-menubar-index ()
974 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
976 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
977 (interactive)
978 (imenu-add-to-menubar "Index"))
980 (defvar imenu-buffer-menubar nil)
982 (defvar-local imenu-menubar-modified-tick 0
983 "The value of (buffer-chars-modified-tick) as of the last call
984 to `imenu-update-menubar'.")
986 (defun imenu-update-menubar ()
987 (when (and (current-local-map)
988 imenu--menubar-keymap
989 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
990 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
991 (let ((index-alist (imenu--make-index-alist t)))
992 ;; Don't bother updating if the index-alist has not changed
993 ;; since the last time we did it.
994 (unless (equal index-alist imenu--last-menubar-index-alist)
995 (setq imenu--last-menubar-index-alist index-alist)
996 (setq index-alist (imenu--split-submenus index-alist))
997 (let* ((menu (imenu--split-menu index-alist
998 (buffer-name)))
999 (menu1 (imenu--create-keymap (car menu)
1000 (cdr (if (< 1 (length (cdr menu)))
1001 menu
1002 (car (cdr menu))))
1003 'imenu--menubar-select)))
1004 (setcdr imenu--menubar-keymap (cdr menu1)))))))
1006 (defun imenu--menubar-select (item)
1007 "Use Imenu to select the function or variable named in this menu ITEM."
1008 (if (equal item imenu--rescan-item)
1009 (progn
1010 (imenu--cleanup)
1011 ;; Make sure imenu-update-menubar redoes everything.
1012 (setq imenu-menubar-modified-tick -1)
1013 (setq imenu--index-alist nil)
1014 (setq imenu--last-menubar-index-alist nil)
1015 (imenu-update-menubar)
1017 (imenu item)
1018 nil))
1020 (defun imenu-default-goto-function (_name position &rest _rest)
1021 "Move to the given position.
1023 NAME is ignored. POSITION is where to move. REST is also ignored.
1024 The ignored args just make this function have the same interface as a
1025 function placed in a special index-item."
1026 (if (or (< position (point-min))
1027 (> position (point-max)))
1028 ;; Widen if outside narrowing.
1029 (widen))
1030 (goto-char position))
1032 ;;;###autoload
1033 (defun imenu (index-item)
1034 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1035 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1036 for more information."
1037 (interactive (list (imenu-choose-buffer-index)))
1038 ;; Convert a string to an alist element.
1039 (if (stringp index-item)
1040 (setq index-item (assoc index-item (imenu--make-index-alist))))
1041 (when index-item
1042 (pcase index-item
1043 (`(,name ,pos ,fn . ,args)
1044 (push-mark nil t)
1045 (apply fn name pos args)
1046 (run-hooks 'imenu-after-jump-hook))
1047 (`(,name . ,pos) (imenu (list name pos imenu-default-goto-function)))
1048 (_ (error "Unknown imenu item: %S" index-item)))))
1050 (provide 'imenu)
1052 ;;; imenu.el ends here