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