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