]> code.delx.au - gnu-emacs/blob - lisp/imenu.el
57db68626e1e5b4c925c12b0efdba8bc2027d0fa
[gnu-emacs] / lisp / imenu.el
1 ;;; imenu.el --- framework for mode-specific buffer indexes -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1994-1998, 2001-2015 Free Software Foundation, Inc.
4
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
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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.
32 ;;
33 ;; It is documented in the Emacs Lisp manual.
34 ;;
35 ;; How it works:
36
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.
39 ;;
40 ;; The package comes with a set of example functions for how to
41 ;; utilize this package.
42
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.
47
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
59
60 ;;; Code:
61
62 (eval-when-compile (require 'cl-lib))
63
64 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
65 ;;;
66 ;;; Customizable variables
67 ;;;
68 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
69
70 (defgroup imenu nil
71 "Mode-specific buffer indexes."
72 :group 'matching
73 :group 'frames
74 :group 'convenience
75 :link '(custom-manual "(elisp)Imenu"))
76
77 (defcustom imenu-use-markers t
78 "Non-nil means use markers instead of integers for Imenu buffer positions.
79
80 Setting this to nil makes Imenu work a little faster but editing the
81 buffer will make the generated index positions wrong.
82
83 This might not yet be honored by all index-building functions."
84 :type 'boolean
85 :group 'imenu)
86
87
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)
93
94 (defcustom imenu-auto-rescan nil
95 "Non-nil means Imenu should always rescan the buffers."
96 :type 'boolean
97 :group 'imenu)
98
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)
104
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")
108
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)
121
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")
128
129 (defcustom imenu-after-jump-hook nil
130 "Hooks called after jumping to a place in the buffer.
131
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)
136
137 ;;;###autoload
138 (defcustom imenu-sort-function nil
139 "The function to use for sorting the index mouse-menu.
140
141 Affects only the mouse index menu.
142
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.
146
147 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
148
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)
156
157 (defcustom imenu-max-items 25
158 "Maximum number of elements in a mouse menu for Imenu."
159 :type 'integer
160 :group 'imenu)
161
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.
166 ;;
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)
173
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)
180
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)
187
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")
194
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
199
200 (MENU-TITLE REGEXP INDEX [FUNCTION] [ARGUMENTS...])
201
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.
218
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.
222
223 If non-nil this pattern is passed to `imenu--generic-function' to
224 create a buffer index.
225
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)
231
232 ;;;###autoload
233 (make-variable-buffer-local 'imenu-generic-expression)
234
235 ;;;; Hooks
236
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.
240
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'.
244
245 See `imenu--index-alist' for the format of the buffer index alist.")
246 ;;;###autoload
247 (make-variable-buffer-local 'imenu-create-index-function)
248
249 ;;;###autoload
250 (defvar imenu-prev-index-position-function 'beginning-of-defun
251 "Function for finding the next index position.
252
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.
257
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)
262
263 ;;;###autoload
264 (defvar imenu-extract-index-name-function nil
265 "Function for extracting the index item name, given a position.
266
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)
272
273 ;;;###autoload
274 (defvar imenu-name-lookup-function nil
275 "Function to compare string with index item.
276
277 This function will be called with two strings, and should return
278 non-nil if they match.
279
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)
286
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)
293
294
295 (defun imenu--subalist-p (item)
296 (and (consp item)
297 (consp (cdr item))
298 (listp (cadr item))
299 (not (functionp (cadr item)))))
300
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."
307
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.
311
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)))))
322 )
323
324
325 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
326 ;;;;
327 ;;;; Some examples of functions utilizing the framework of this
328 ;;;; package.
329 ;;;;
330 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
331
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))))
346
347 ;;;
348 ;;; Lisp
349 ;;;
350
351 (define-error 'imenu-unavailable "imenu unavailable")
352
353 (defun imenu-unavailable-error (format &rest args)
354 (signal 'imenu-unavailable
355 (list (apply #'format-message format args))))
356
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)))))
371
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))
405 (t
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))
419
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.
428 ))
429
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)))
448
449 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
450 ;;;
451 ;;; Internal variables
452 ;;;
453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
454
455 ;; The item to use in the index for rescanning the buffer.
456 (defconst imenu--rescan-item '("*Rescan*" . -99))
457
458 ;; The latest buffer index.
459 (defvar-local imenu--index-alist nil
460 "The buffer index alist computed for this buffer in Imenu.
461
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.
465 POSITION is passed to `imenu-default-goto-function', so it can be a non-number
466 if that variable has been changed (e.g. Semantic uses overlays for POSITIONs).
467
468 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
469 To \"go to\" a special element means applying FUNCTION
470 to INDEX-NAME, POSITION, and the ARGUMENTS.
471
472 A nested sub-alist element looks like (INDEX-NAME . SUB-ALIST).
473 The function `imenu--subalist-p' tests an element and returns t
474 if it is a sub-alist.
475
476 There is one simple element with negative POSITION; selecting that
477 element recalculates the buffer's index alist.")
478 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
479
480 (defvar-local imenu--last-menubar-index-alist nil
481 "The latest buffer index alist used to update the menu bar menu.")
482
483 (defvar imenu--history-list nil
484 ;; Making this buffer local caused it not to work!
485 "History list for `jump-to-function-in-buffer'.")
486
487 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
488 ;;;
489 ;;; Internal support functions
490 ;;;
491 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
492
493 (defun imenu--sort-by-name (item1 item2)
494 "Comparison function to sort items depending on their index name.
495 An item looks like (NAME . POSITION)."
496 (string-lessp (car item1) (car item2)))
497
498 (defun imenu--sort-by-position (item1 item2)
499 (< (cdr item1) (cdr item2)))
500
501 (defun imenu--relative-position (&optional reverse)
502 "Support function to calculate relative position in buffer.
503 Beginning of buffer is 0 and end of buffer is 100
504 If REVERSE is non-nil then the beginning is 100 and the end is 0."
505 (let ((pos (point))
506 (total (buffer-size)))
507 (and reverse (setq pos (- total pos)))
508 (floor (* 100.0 (1- pos)) (max total 1))))
509
510 (defun imenu--split (list n)
511 "Split LIST into sublists of max length N.
512 Example (imenu--split \\='(1 2 3 4 5 6 7 8) 3) => ((1 2 3) (4 5 6) (7 8))
513 The returned list DOES NOT share structure with LIST."
514 (let ((remain list)
515 (result '())
516 (sublist '())
517 (i 0))
518 (while remain
519 (push (pop remain) sublist)
520 (cl-incf i)
521 (and (= i n)
522 ;; We have finished a sublist
523 (progn (push (nreverse sublist) result)
524 (setq i 0)
525 (setq sublist '()))))
526 ;; There might be a sublist (if the length of LIST mod n is != 0)
527 ;; that has to be added to the result list.
528 (and sublist
529 (push (nreverse sublist) result))
530 (nreverse result)))
531
532 (defun imenu--split-menu (menulist title)
533 "Split the alist MENULIST into a nested alist, if it is long enough.
534 In any case, add TITLE to the front of the alist.
535 If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
536 beginning of the returned alist.
537 The returned alist DOES NOT share structure with MENULIST."
538 (let ((menulist (copy-sequence menulist))
539 keep-at-top)
540 (if (memq imenu--rescan-item menulist)
541 (setq keep-at-top (list imenu--rescan-item)
542 menulist (delq imenu--rescan-item menulist)))
543 (dolist (item menulist)
544 (when (imenu--subalist-p item)
545 (push item keep-at-top)
546 (setq menulist (delq item menulist))))
547 (if imenu-sort-function
548 (setq menulist (sort menulist imenu-sort-function)))
549 (if (> (length menulist) imenu-max-items)
550 (setq menulist
551 (mapcar
552 (lambda (menu)
553 (cons (format "From: %s" (caar menu)) menu))
554 (imenu--split menulist imenu-max-items))))
555 (cons title
556 (nconc (nreverse keep-at-top) menulist))))
557
558 (defun imenu--split-submenus (alist)
559 "Split up each long alist that are nested within ALIST into nested alists.
560 Return a split and sorted copy of ALIST. The returned alist DOES
561 NOT share structure with ALIST."
562 (mapcar (lambda (elt)
563 (if (imenu--subalist-p elt)
564 (imenu--split-menu (cdr elt) (car elt))
565 elt))
566 alist))
567
568 (defun imenu--truncate-items (menulist)
569 "Truncate all strings in MENULIST to `imenu-max-item-length'."
570 (mapc (lambda (item)
571 ;; Truncate if necessary.
572 (when (and (numberp imenu-max-item-length)
573 (> (length (car item)) imenu-max-item-length))
574 (setcar item (substring (car item) 0 imenu-max-item-length)))
575 (when (imenu--subalist-p item)
576 (imenu--truncate-items (cdr item))))
577 menulist))
578
579 (defun imenu--make-index-alist (&optional noerror)
580 "Create an index alist for the definitions in the current buffer.
581 This works by using the hook function `imenu-create-index-function'.
582 Report an error if the list is empty unless NOERROR is supplied and
583 non-nil.
584
585 See `imenu--index-alist' for the format of the index alist."
586 (or (and imenu--index-alist
587 (or (not imenu-auto-rescan)
588 (and imenu-auto-rescan
589 (> (buffer-size) imenu-auto-rescan-maxout))))
590 ;; Get the index; truncate if necessary.
591 (progn
592 (setq imenu--index-alist
593 (save-excursion
594 (save-restriction
595 (widen)
596 (funcall imenu-create-index-function))))
597 (imenu--truncate-items imenu--index-alist)))
598 (or imenu--index-alist noerror
599 (imenu-unavailable-error
600 "No items suitable for an index found in this buffer"))
601 (or imenu--index-alist
602 (setq imenu--index-alist (list nil)))
603 ;; Add a rescan option to the index.
604 (cons imenu--rescan-item imenu--index-alist))
605
606 (defvar imenu--cleanup-seen nil)
607
608 (defun imenu--cleanup (&optional alist)
609 "Find all markers in ALIST and make them point nowhere.
610 If ALIST is nil (the normal case), use `imenu--index-alist'.
611 Non-nil arguments are in recursive calls."
612 ;; If alist is provided use that list.
613 ;; If not, empty the table of lists already seen
614 ;; and use imenu--index-alist.
615 (if alist
616 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
617 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
618
619 (when alist
620 (dolist (item alist)
621 (cond
622 ((markerp (cdr item)) (set-marker (cdr item) nil))
623 ;; Don't process one alist twice.
624 ((memq (cdr item) imenu--cleanup-seen))
625 ((imenu--subalist-p item) (imenu--cleanup (cdr item)))))
626 t))
627
628 (defun imenu--create-keymap (title alist &optional cmd)
629 `(keymap ,title
630 ,@(mapcar
631 (lambda (item)
632 `(,(car item) ,(car item)
633 ,@(cond
634 ((imenu--subalist-p item)
635 (imenu--create-keymap (car item) (cdr item) cmd))
636 (t
637 `(lambda () (interactive)
638 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
639 alist)))
640
641 (defun imenu--in-alist (str alist)
642 "Check whether the string STR is contained in multi-level ALIST."
643 (let (elt head tail res)
644 (setq res nil)
645 (while alist
646 (setq elt (car alist)
647 tail (cdr elt)
648 alist (cdr alist)
649 head (car elt))
650 ;; A nested ALIST element looks like
651 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
652 ;; while a bottom-level element looks like
653 ;; (INDEX-NAME . INDEX-POSITION)
654 ;; or
655 ;; (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
656 ;; We are only interested in the bottom-level elements, so we need to
657 ;; recurse if TAIL is a nested ALIST.
658 (cond ((imenu--subalist-p elt)
659 (if (setq res (imenu--in-alist str tail))
660 (setq alist nil)))
661 ((if imenu-name-lookup-function
662 (funcall imenu-name-lookup-function str head)
663 (string= str head))
664 (setq alist nil res elt))))
665 res))
666
667 (defvar imenu-syntax-alist nil
668 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
669
670 The car of the assocs may be either a character or a string and the
671 cdr is a syntax description appropriate for `modify-syntax-entry'. For
672 a string, all the characters in the string get the specified syntax.
673
674 This is typically used to give word syntax to characters which
675 normally have symbol syntax to simplify `imenu-expression'
676 and speed-up matching.")
677 ;;;###autoload
678 (make-variable-buffer-local 'imenu-syntax-alist)
679
680 (defun imenu-default-create-index-function ()
681 "Default function to create an index alist of the current buffer.
682
683 The most general method is to move point to end of buffer, then repeatedly call
684 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
685 All the results returned by the latter are gathered into an index alist.
686 This method is used if those two variables are non-nil.
687
688 The alternate method, which is the one most often used, is to call
689 `imenu--generic-function' with `imenu-generic-expression' as argument."
690 ;; These should really be done by setting imenu-create-index-function
691 ;; in these major modes. But save that change for later.
692 (cond ((and imenu-prev-index-position-function
693 imenu-extract-index-name-function)
694 (let ((index-alist '()) (pos (point-max))
695 name)
696 (goto-char pos)
697 ;; Search for the function
698 (while (funcall imenu-prev-index-position-function)
699 (unless (< (point) pos)
700 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
701 (setq pos (point))
702 (save-excursion
703 (setq name (funcall imenu-extract-index-name-function)))
704 (and (stringp name)
705 ;; [ydi] Updated for imenu-use-markers.
706 (push (cons name
707 (if imenu-use-markers (point-marker) (point)))
708 index-alist)))
709 index-alist))
710 ;; Use generic expression if possible.
711 ((and imenu-generic-expression)
712 (imenu--generic-function imenu-generic-expression))
713 (t
714 (imenu-unavailable-error "This buffer cannot use `imenu-default-create-index-function'"))))
715
716 ;;;
717 ;;; Generic index gathering function.
718 ;;;
719
720 (defvar imenu-case-fold-search t
721 "Defines whether `imenu--generic-function' should fold case when matching.
722
723 This variable should be set (only) by initialization code
724 for modes which use `imenu--generic-function'. If it is not set, but
725 `font-lock-defaults' is set, then font-lock's setting is used.")
726 ;;;###autoload
727 (make-variable-buffer-local 'imenu-case-fold-search)
728
729 ;; This function can be called with quitting disabled,
730 ;; so it needs to be careful never to loop!
731 (defun imenu--generic-function (patterns)
732 "Return an index alist of the current buffer based on PATTERNS.
733 PATTERNS should be an alist with the same form as `imenu-generic-expression'.
734
735 If `imenu-generic-skip-comments-and-strings' is non-nil, this ignores
736 text inside comments and strings.
737
738 If `imenu-case-fold-search' is non-nil, this ignores case.
739
740 The return value is an alist of the form
741 (INDEX-NAME . INDEX-POSITION)
742 or
743 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
744 The return value may also consist of nested index alists like:
745 (INDEX-NAME . INDEX-ALIST)
746 depending on PATTERNS."
747 (let ((index-alist (list 'dummy))
748 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
749 (not (local-variable-p 'font-lock-defaults)))
750 imenu-case-fold-search
751 (nth 2 font-lock-defaults)))
752 (old-table (syntax-table))
753 (table (copy-syntax-table (syntax-table)))
754 (slist imenu-syntax-alist))
755 ;; Modify the syntax table used while matching regexps.
756 (dolist (syn slist)
757 ;; The character(s) to modify may be a single char or a string.
758 (if (numberp (car syn))
759 (modify-syntax-entry (car syn) (cdr syn) table)
760 (mapc (lambda (c)
761 (modify-syntax-entry c (cdr syn) table))
762 (car syn))))
763 (goto-char (point-max))
764 (unwind-protect ; For syntax table.
765 (save-match-data
766 (set-syntax-table table)
767
768 ;; Map over the elements of imenu-generic-expression
769 ;; (typically functions, variables ...).
770 (dolist (pat patterns)
771 (let ((menu-title (car pat))
772 (regexp (nth 1 pat))
773 (index (nth 2 pat))
774 (function (nth 3 pat))
775 (rest (nthcdr 4 pat))
776 start beg)
777 ;; Go backwards for convenience of adding items in order.
778 (goto-char (point-max))
779 (while (and (if (functionp regexp)
780 (funcall regexp)
781 (and
782 (re-search-backward regexp nil t)
783 ;; Do not count invisible definitions.
784 (let ((invis (invisible-p (point))))
785 (or (not invis)
786 (progn
787 (while (and invis
788 (not (bobp)))
789 (setq invis (not (re-search-backward
790 regexp nil 'move))))
791 (not invis))))))
792 ;; Exit the loop if we get an empty match,
793 ;; because it means a bad regexp was specified.
794 (not (= (match-beginning 0) (match-end 0))))
795 (setq start (point))
796 ;; Record the start of the line in which the match starts.
797 ;; That's the official position of this definition.
798 (goto-char (match-beginning index))
799 (beginning-of-line)
800 (setq beg (point))
801 ;; Add this sort of submenu only when we've found an
802 ;; item for it, avoiding empty, duff menus.
803 (unless (assoc menu-title index-alist)
804 (push (list menu-title) index-alist))
805 (if imenu-use-markers
806 (setq beg (copy-marker beg)))
807 (let ((item
808 (if function
809 (nconc (list (match-string-no-properties index)
810 beg function)
811 rest)
812 (cons (match-string-no-properties index)
813 beg)))
814 ;; This is the desired submenu,
815 ;; starting with its title (or nil).
816 (menu (assoc menu-title index-alist)))
817 ;; Insert the item unless it is already present.
818 (unless (or (member item (cdr menu))
819 (and imenu-generic-skip-comments-and-strings
820 (nth 8 (syntax-ppss))))
821 (setcdr menu
822 (cons item (cdr menu)))))
823 ;; Go to the start of the match, to make sure we
824 ;; keep making progress backwards.
825 (goto-char start))))
826 (set-syntax-table old-table)))
827 ;; Sort each submenu by position.
828 ;; This is in case one submenu gets items from two different regexps.
829 (dolist (item index-alist)
830 (when (listp item)
831 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
832 (let ((main-element (assq nil index-alist)))
833 (nconc (delq main-element (delq 'dummy index-alist))
834 (cdr main-element)))))
835
836 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
837 ;;;
838 ;;; The main functions for this package!
839 ;;;
840 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
841
842 ;; See also info-lookup-find-item
843 (defun imenu-find-default (guess completions)
844 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
845 (catch 'found
846 (let ((case-fold-search t))
847 (if (assoc guess completions) guess
848 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
849 (concat "\\`" (regexp-quote guess))
850 (concat (regexp-quote guess) "\\'")
851 (regexp-quote guess)))
852 (dolist (x completions)
853 (if (string-match re (car x)) (throw 'found (car x)))))))))
854
855 (defun imenu--completion-buffer (index-alist &optional prompt)
856 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
857
858 Return one of the entries in index-alist or nil."
859 ;; Create a list for this buffer only when needed.
860 (let ((name (thing-at-point 'symbol))
861 choice
862 (prepared-index-alist
863 (if (not imenu-space-replacement) index-alist
864 (mapcar
865 (lambda (item)
866 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
867 (car item))
868 (cdr item)))
869 index-alist))))
870 (when (stringp name)
871 (setq name (or (imenu-find-default name prepared-index-alist) name)))
872 (cond (prompt)
873 ((and name (imenu--in-alist name prepared-index-alist))
874 (setq prompt (format "Index item (default %s): " name)))
875 (t (setq prompt "Index item: ")))
876 (let ((minibuffer-setup-hook minibuffer-setup-hook))
877 ;; Display the completion buffer.
878 (if (not imenu-eager-completion-buffer)
879 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
880 (setq name (completing-read prompt
881 prepared-index-alist
882 nil t nil 'imenu--history-list name)))
883
884 (when (stringp name)
885 (setq choice (assoc name prepared-index-alist))
886 (if (imenu--subalist-p choice)
887 (imenu--completion-buffer (cdr choice) prompt)
888 choice))))
889
890 (defun imenu--mouse-menu (index-alist event &optional title)
891 "Let the user select from a buffer index from a mouse menu.
892
893 INDEX-ALIST is the buffer index and EVENT is a mouse event.
894
895 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
896 (setq index-alist (imenu--split-submenus index-alist))
897 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
898 (map (imenu--create-keymap (car menu)
899 (cdr (if (< 1 (length (cdr menu)))
900 menu
901 (car (cdr menu)))))))
902 (popup-menu map event)))
903
904 (defun imenu-choose-buffer-index (&optional prompt alist)
905 "Let the user select from a buffer index and return the chosen index.
906
907 If the user originally activated this function with the mouse, a mouse
908 menu is used. Otherwise a completion buffer is used and the user is
909 prompted with PROMPT.
910
911 If you call this function with index alist ALIST, then it lets the user
912 select from ALIST.
913
914 With no index alist ALIST, it calls `imenu--make-index-alist' to
915 create the index alist.
916
917 If `imenu-use-popup-menu' is nil, then the completion buffer
918 is always used, no matter if the mouse was used or not.
919
920 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
921 (let (index-alist
922 (mouse-triggered (listp last-nonmenu-event))
923 (result t))
924 ;; If selected by mouse, see to that the window where the mouse is
925 ;; really is selected.
926 (and mouse-triggered
927 (not (equal last-nonmenu-event '(menu-bar)))
928 (let ((window (posn-window (event-start last-nonmenu-event))))
929 (or (framep window) (null window) (select-window window))))
930 ;; Create a list for this buffer only when needed.
931 (while (eq result t)
932 (setq index-alist (if alist alist (imenu--make-index-alist)))
933 (setq result
934 (if (and imenu-use-popup-menu
935 (or (eq imenu-use-popup-menu t) mouse-triggered))
936 (imenu--mouse-menu index-alist last-nonmenu-event)
937 (imenu--completion-buffer index-alist prompt)))
938 (and (equal result imenu--rescan-item)
939 (imenu--cleanup)
940 (setq result t imenu--index-alist nil)))
941 result))
942
943 (defvar-local imenu--menubar-keymap nil)
944
945 ;;;###autoload
946 (defun imenu-add-to-menubar (name)
947 "Add an `imenu' entry to the menu bar for the current buffer.
948 NAME is a string used to name the menu bar item.
949 See the command `imenu' for more information."
950 (interactive "sImenu menu item name: ")
951 (if (or (and imenu-prev-index-position-function
952 imenu-extract-index-name-function)
953 imenu-generic-expression
954 (not (eq imenu-create-index-function
955 'imenu-default-create-index-function)))
956 (unless (and (current-local-map)
957 (keymapp (lookup-key (current-local-map) [menu-bar index])))
958 (let ((newmap (make-sparse-keymap)))
959 (set-keymap-parent newmap (current-local-map))
960 (setq imenu--last-menubar-index-alist nil)
961 (setq imenu--menubar-keymap (make-sparse-keymap "Imenu"))
962 (define-key newmap [menu-bar index]
963 `(menu-item ,name ,imenu--menubar-keymap))
964 (use-local-map newmap)
965 (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
966 (imenu-unavailable-error "The mode `%s' does not support Imenu"
967 (format-mode-line mode-name))))
968
969 ;;;###autoload
970 (defun imenu-add-menubar-index ()
971 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
972
973 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
974 (interactive)
975 (imenu-add-to-menubar "Index"))
976
977 (defvar imenu-buffer-menubar nil)
978
979 (defvar-local imenu-menubar-modified-tick 0
980 "The value of (buffer-chars-modified-tick) as of the last call
981 to `imenu-update-menubar'.")
982
983 (defun imenu-update-menubar ()
984 (when (and (current-local-map)
985 imenu--menubar-keymap
986 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
987 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
988 (let ((index-alist (imenu--make-index-alist t)))
989 ;; Don't bother updating if the index-alist has not changed
990 ;; since the last time we did it.
991 (unless (equal index-alist imenu--last-menubar-index-alist)
992 (setq imenu--last-menubar-index-alist index-alist)
993 (setq index-alist (imenu--split-submenus index-alist))
994 (let* ((menu (imenu--split-menu index-alist
995 (buffer-name)))
996 (menu1 (imenu--create-keymap (car menu)
997 (cdr (if (< 1 (length (cdr menu)))
998 menu
999 (car (cdr menu))))
1000 'imenu--menubar-select)))
1001 (setcdr imenu--menubar-keymap (cdr menu1)))))))
1002
1003 (defun imenu--menubar-select (item)
1004 "Use Imenu to select the function or variable named in this menu ITEM."
1005 (if (equal item imenu--rescan-item)
1006 (progn
1007 (imenu--cleanup)
1008 ;; Make sure imenu-update-menubar redoes everything.
1009 (setq imenu-menubar-modified-tick -1)
1010 (setq imenu--index-alist nil)
1011 (setq imenu--last-menubar-index-alist nil)
1012 (imenu-update-menubar)
1013 t)
1014 (imenu item)
1015 nil))
1016
1017 (defun imenu-default-goto-function (_name position &rest _rest)
1018 "Move to the given position.
1019
1020 NAME is ignored. POSITION is where to move. REST is also ignored.
1021 The ignored args just make this function have the same interface as a
1022 function placed in a special index-item."
1023 (if (or (< position (point-min))
1024 (> position (point-max)))
1025 ;; Widen if outside narrowing.
1026 (widen))
1027 (goto-char position))
1028
1029 ;;;###autoload
1030 (defun imenu (index-item)
1031 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1032 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1033 for more information."
1034 (interactive (list (imenu-choose-buffer-index)))
1035 ;; Convert a string to an alist element.
1036 (if (stringp index-item)
1037 (setq index-item (assoc index-item (imenu--make-index-alist))))
1038 (when index-item
1039 (pcase index-item
1040 (`(,name ,pos ,fn . ,args)
1041 (push-mark nil t)
1042 (apply fn name pos args)
1043 (run-hooks 'imenu-after-jump-hook))
1044 (`(,name . ,pos) (imenu (list name pos imenu-default-goto-function)))
1045 (_ (error "Unknown imenu item: %S" index-item)))))
1046
1047 (provide 'imenu)
1048
1049 ;;; imenu.el ends here