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