(byte-compile-file-form-defvar)
[bpt/emacs.git] / lisp / imenu.el
1 ;;; imenu.el --- framework for mode-specific buffer indexes
2
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
7 ;; Lars Lindberg <lli@sypro.cap.se>
8 ;; Maintainer: FSF
9 ;; Created: 8 Feb 1994
10 ;; Keywords: tools convenience
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Purpose of this package:
30 ;; To present a framework for mode-specific buffer indexes.
31 ;; A buffer index is an alist of names and buffer positions.
32 ;; For instance all functions in a C-file and their positions.
33 ;;
34 ;; It is documented in the Emacs Lisp manual.
35 ;;
36 ;; How it works:
37
38 ;; A mode-specific function is called to generate the index. It is
39 ;; then presented to the user, who can choose from this index.
40 ;;
41 ;; The package comes with a set of example functions for how to
42 ;; utilize this package.
43
44 ;; There are *examples* for index gathering functions/regular
45 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
46 ;; customize for other modes. A function for jumping to the chosen
47 ;; index position is also supplied.
48
49 ;;; History:
50 ;; Thanks go to
51 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
52 ;; [dean] - Dean Andrews ada@unison.com
53 ;; [alon] - Alon Albert al@mercury.co.il
54 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
55 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
56 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
57 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
58 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
59 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
60
61 ;;; Code:
62
63 (eval-when-compile (require 'cl))
64
65 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
66 ;;;
67 ;;; Customizable variables
68 ;;;
69 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70
71 (defgroup imenu nil
72 "Mode-specific buffer indexes."
73 :group 'matching
74 :group 'frames
75 :group 'convenience
76 :link '(custom-manual "(elisp)Imenu"))
77
78 (defcustom imenu-use-markers t
79 "Non-nil means use markers instead of integers for Imenu buffer positions.
80
81 Setting this to nil makes Imenu work a little faster but editing the
82 buffer will make the generated index positions wrong.
83
84 This might not yet be honored by all index-building functions."
85 :type 'boolean
86 :group 'imenu)
87
88
89 (defcustom imenu-max-item-length 60
90 "If a number, truncate Imenu entries to that length."
91 :type '(choice integer
92 (const :tag "Unlimited"))
93 :group 'imenu)
94
95 (defcustom imenu-auto-rescan nil
96 "Non-nil means Imenu should always rescan the buffers."
97 :type 'boolean
98 :group 'imenu)
99
100 (defcustom imenu-auto-rescan-maxout 60000
101 "Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
102 This variable is buffer-local."
103 :type 'integer
104 :group 'imenu)
105
106 (defvar imenu-always-use-completion-buffer-p nil)
107 (make-obsolete-variable 'imenu-always-use-completion-buffer-p
108 'imenu-use-popup-menu "22.1")
109
110 (defcustom imenu-use-popup-menu
111 (if imenu-always-use-completion-buffer-p
112 (not (eq imenu-always-use-completion-buffer-p 'never))
113 'on-mouse)
114 "Use a popup menu rather than a minibuffer prompt.
115 If nil, always use a minibuffer prompt.
116 If t, always use a popup menu,
117 If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
118 :type '(choice (const :tag "On Mouse" on-mouse)
119 (const :tag "Never" nil)
120 (other :tag "Always" t))
121 :group 'imenu)
122
123 (defcustom imenu-eager-completion-buffer
124 (not (eq imenu-always-use-completion-buffer-p 'never))
125 "If non-nil, eagerly popup the completion buffer."
126 :type 'boolean
127 :group 'imenu
128 :version "22.1")
129
130 (defcustom imenu-after-jump-hook nil
131 "Hooks called after jumping to a place in the buffer.
132
133 Useful things to use here include `reposition-window', `recenter', and
134 \(lambda () (recenter 0)) to show at top of screen."
135 :type 'hook
136 :group 'imenu)
137
138 ;;;###autoload
139 (defcustom imenu-sort-function nil
140 "The function to use for sorting the index mouse-menu.
141
142 Affects only the mouse index menu.
143
144 Set this to nil if you don't want any sorting (faster).
145 The items in the menu are then presented in the order they were found
146 in the buffer.
147
148 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
149
150 The function should take two arguments and return t if the first
151 element should come before the second. The arguments are cons cells;
152 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
153 :type '(choice (const :tag "No sorting" nil)
154 (const :tag "Sort by name" imenu--sort-by-name)
155 (function :tag "Another function"))
156 :group 'imenu)
157
158 (defcustom imenu-max-items 25
159 "Maximum number of elements in a mouse menu for Imenu."
160 :type 'integer
161 :group 'imenu)
162
163 ;; No longer used. KFS 2004-10-27
164 ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
165 ;; "*Progress message during the index scanning of the buffer.
166 ;; If non-nil, user gets a message during the scanning of the buffer.
167 ;;
168 ;; Relevant only if the mode-specific function that creates the buffer
169 ;; index use `imenu-progress-message', and not useful if that is fast, in
170 ;; which case you might as well set this to nil."
171 ;; :type '(choice string
172 ;; (const :tag "None" nil))
173 ;; :group 'imenu)
174
175 (defcustom imenu-space-replacement "."
176 "The replacement string for spaces in index names.
177 Used when presenting the index in a completion buffer to make the
178 names work as tokens."
179 :type '(choice string (const nil))
180 :group 'imenu)
181
182 (defcustom imenu-level-separator ":"
183 "The separator between index names of different levels.
184 Used for making mouse-menu titles and for flattening nested indexes
185 with name concatenation."
186 :type 'string
187 :group 'imenu)
188
189 ;;;###autoload
190 (defvar imenu-generic-expression nil
191 "The regex pattern to use for creating a buffer index.
192
193 If non-nil this pattern is passed to `imenu--generic-function' to
194 create a buffer index. Look there for the documentation of this
195 pattern's structure.
196
197 For example, see the value of `fortran-imenu-generic-expression' used by
198 `fortran-mode' with `imenu-syntax-alist' set locally to give the
199 characters which normally have \"symbol\" syntax \"word\" syntax
200 during matching.")
201 ;;;###autoload(put 'imenu-generic-expression 'risky-local-variable t)
202
203 ;;;###autoload
204 (make-variable-buffer-local 'imenu-generic-expression)
205
206 ;;;; Hooks
207
208 ;;;###autoload
209 (defvar imenu-create-index-function 'imenu-default-create-index-function
210 "The function to use for creating an index alist of the current buffer.
211
212 It should be a function that takes no arguments and returns
213 an index alist of the current buffer. The function is
214 called within a `save-excursion'.
215
216 See `imenu--index-alist' for the format of the buffer index alist.")
217 ;;;###autoload
218 (make-variable-buffer-local 'imenu-create-index-function)
219
220 ;;;###autoload
221 (defvar imenu-prev-index-position-function 'beginning-of-defun
222 "Function for finding the next index position.
223
224 If `imenu-create-index-function' is set to
225 `imenu-default-create-index-function', then you must set this variable
226 to a function that will find the next index, looking backwards in the
227 file.
228
229 The function should leave point at the place to be connected to the
230 index and it should return nil when it doesn't find another index.")
231 ;;;###autoload
232 (make-variable-buffer-local 'imenu-prev-index-position-function)
233
234 ;;;###autoload
235 (defvar imenu-extract-index-name-function nil
236 "Function for extracting the index item name, given a position.
237
238 This function is called after `imenu-prev-index-position-function'
239 finds a position for an index item, with point at that position.
240 It should return the name for that index item.")
241 ;;;###autoload
242 (make-variable-buffer-local 'imenu-extract-index-name-function)
243
244 ;;;###autoload
245 (defvar imenu-name-lookup-function nil
246 "Function to compare string with index item.
247
248 This function will be called with two strings, and should return
249 non-nil if they match.
250
251 If nil, comparison is done with `string='.
252 Set this to some other function for more advanced comparisons,
253 such as \"begins with\" or \"name matches and number of
254 arguments match\".")
255 ;;;###autoload
256 (make-variable-buffer-local 'imenu-name-lookup-function)
257
258 ;;;###autoload
259 (defvar imenu-default-goto-function 'imenu-default-goto-function
260 "The default function called when selecting an Imenu item.
261 The function in this variable is called when selecting a normal index-item.")
262 ;;;###autoload
263 (make-variable-buffer-local 'imenu-default-goto-function)
264
265
266 (defun imenu--subalist-p (item)
267 (and (consp (cdr item)) (listp (cadr item))
268 (not (eq (car (cadr item)) 'lambda))))
269
270 ;; Macro to display a progress message.
271 ;; RELPOS is the relative position to display.
272 ;; If RELPOS is nil, then the relative position in the buffer
273 ;; is calculated.
274 ;; PREVPOS is the variable in which we store the last position displayed.
275 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
276
277 ;; Made obsolete/empty, as computers are now faster than the eye, and
278 ;; it had problems updating the messages correctly, and could shadow
279 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
280
281 ;; `(and
282 ;; imenu-scanning-message
283 ;; (let ((pos ,(if relpos
284 ;; relpos
285 ;; `(imenu--relative-position ,reverse))))
286 ;; (if ,(if relpos t
287 ;; `(> pos (+ 5 ,prevpos)))
288 ;; (progn
289 ;; (message imenu-scanning-message pos)
290 ;; (setq ,prevpos pos)))))
291 )
292
293
294 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
295 ;;;;
296 ;;;; Some examples of functions utilizing the framework of this
297 ;;;; package.
298 ;;;;
299 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
300
301 ;; FIXME: This was the only imenu-example-* definition actually used,
302 ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
303 ;; all be removed.
304 (defun imenu-example--name-and-position ()
305 "Return the current/previous sexp and its (beginning) location.
306 Don't move point."
307 (save-excursion
308 (forward-sexp -1)
309 ;; [ydi] modified for imenu-use-markers
310 (let ((beg (if imenu-use-markers (point-marker) (point)))
311 (end (progn (forward-sexp) (point))))
312 (cons (buffer-substring beg end)
313 beg))))
314 (make-obsolete 'imenu-example--name-and-position
315 "use your own function instead." "23.2")
316
317 ;;;
318 ;;; Lisp
319 ;;;
320
321 (defun imenu-example--lisp-extract-index-name ()
322 ;; Example of a candidate for `imenu-extract-index-name-function'.
323 ;; This will generate a flat index of definitions in a lisp file.
324 (save-match-data
325 (and (looking-at "(def")
326 (condition-case nil
327 (progn
328 (down-list 1)
329 (forward-sexp 2)
330 (let ((beg (point))
331 (end (progn (forward-sexp -1) (point))))
332 (buffer-substring beg end)))
333 (error nil)))))
334 (make-obsolete 'imenu-example--lisp-extract-index-name "your own" "23.2")
335
336 (defun imenu-example--create-lisp-index ()
337 ;; Example of a candidate for `imenu-create-index-function'.
338 ;; It will generate a nested index of definitions.
339 (let ((index-alist '())
340 (index-var-alist '())
341 (index-type-alist '())
342 (index-unknown-alist '())
343 prev-pos)
344 (goto-char (point-max))
345 (imenu-progress-message prev-pos 0)
346 ;; Search for the function
347 (while (beginning-of-defun)
348 (imenu-progress-message prev-pos nil t)
349 (save-match-data
350 (and (looking-at "(def")
351 (save-excursion
352 (down-list 1)
353 (cond
354 ((looking-at "def\\(var\\|const\\)")
355 (forward-sexp 2)
356 (push (imenu-example--name-and-position)
357 index-var-alist))
358 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
359 (forward-sexp 2)
360 (push (imenu-example--name-and-position)
361 index-alist))
362 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
363 (forward-sexp 2)
364 (if (= (char-after (1- (point))) ?\))
365 (progn
366 (forward-sexp -1)
367 (down-list 1)
368 (forward-sexp 1)))
369 (push (imenu-example--name-and-position)
370 index-type-alist))
371 (t
372 (forward-sexp 2)
373 (push (imenu-example--name-and-position)
374 index-unknown-alist)))))))
375 (imenu-progress-message prev-pos 100)
376 (and index-var-alist
377 (push (cons "Variables" index-var-alist)
378 index-alist))
379 (and index-type-alist
380 (push (cons "Types" index-type-alist)
381 index-alist))
382 (and index-unknown-alist
383 (push (cons "Syntax-unknown" index-unknown-alist)
384 index-alist))
385 index-alist))
386 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
387
388 ;; Regular expression to find C functions
389 (defvar imenu-example--function-name-regexp-c
390 (concat
391 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
392 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
393 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
394 "\\([*&]+[ \t]*\\)?" ; pointer
395 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
396 ))
397
398 (defun imenu-example--create-c-index (&optional regexp)
399 (let ((index-alist '())
400 prev-pos char)
401 (goto-char (point-min))
402 (imenu-progress-message prev-pos 0)
403 ;; Search for the function
404 (save-match-data
405 (while (re-search-forward
406 (or regexp imenu-example--function-name-regexp-c)
407 nil t)
408 (imenu-progress-message prev-pos)
409 (backward-up-list 1)
410 (save-excursion
411 (goto-char (scan-sexps (point) 1))
412 (setq char (following-char)))
413 ;; Skip this function name if it is a prototype declaration.
414 (if (not (eq char ?\;))
415 (push (imenu-example--name-and-position) index-alist))))
416 (imenu-progress-message prev-pos 100)
417 (nreverse index-alist)))
418 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
419
420 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
421 ;;;
422 ;;; Internal variables
423 ;;;
424 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
425
426 ;; The item to use in the index for rescanning the buffer.
427 (defconst imenu--rescan-item '("*Rescan*" . -99))
428
429 ;; The latest buffer index.
430 ;; Buffer local.
431 (defvar imenu--index-alist nil
432 "The buffer index alist computed for this buffer in Imenu.
433
434 Simple elements in the alist look like (INDEX-NAME . POSITION).
435 POSITION is the buffer position of the item; to go to the item
436 is simply to move point to that position.
437
438 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
439 To \"go to\" a special element means applying FUNCTION
440 to INDEX-NAME, POSITION, and the ARGUMENTS.
441
442 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
443 The function `imenu--subalist-p' tests an element and returns t
444 if it is a sub-alist.
445
446 There is one simple element with negative POSITION; selecting that
447 element recalculates the buffer's index alist.")
448 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
449
450 (make-variable-buffer-local 'imenu--index-alist)
451
452 (defvar imenu--last-menubar-index-alist nil
453 "The latest buffer index alist used to update the menu bar menu.")
454
455 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
456
457 ;; History list for 'jump-to-function-in-buffer'.
458 ;; Making this buffer local caused it not to work!
459 (defvar imenu--history-list nil)
460
461 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
462 ;;;
463 ;;; Internal support functions
464 ;;;
465 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
466
467 ;;;
468 ;;; Sort function
469 ;;; Sorts the items depending on their index name.
470 ;;; An item looks like (NAME . POSITION).
471 ;;;
472 (defun imenu--sort-by-name (item1 item2)
473 (string-lessp (car item1) (car item2)))
474
475 (defun imenu--sort-by-position (item1 item2)
476 (< (cdr item1) (cdr item2)))
477
478 (defun imenu--relative-position (&optional reverse)
479 ;; Support function to calculate relative position in buffer
480 ;; Beginning of buffer is 0 and end of buffer is 100
481 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
482 (let ((pos (point))
483 (total (buffer-size)))
484 (and reverse (setq pos (- total pos)))
485 (if (> total 50000)
486 ;; Avoid overflow from multiplying by 100!
487 (/ (1- pos) (max (/ total 100) 1))
488 (/ (* 100 (1- pos)) (max total 1)))))
489
490 ;; Split LIST into sublists of max length N.
491 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
492 ;;
493 ;; The returned list DOES NOT share structure with LIST.
494 (defun imenu--split (list n)
495 (let ((remain list)
496 (result '())
497 (sublist '())
498 (i 0))
499 (while remain
500 (push (pop remain) sublist)
501 (incf i)
502 (and (= i n)
503 ;; We have finished a sublist
504 (progn (push (nreverse sublist) result)
505 (setq i 0)
506 (setq sublist '()))))
507 ;; There might be a sublist (if the length of LIST mod n is != 0)
508 ;; that has to be added to the result list.
509 (and sublist
510 (push (nreverse sublist) result))
511 (nreverse result)))
512
513 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
514 ;;; In any case, add TITLE to the front of the alist.
515 ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
516 ;;; beginning of the returned alist.
517 ;;;
518 ;;; The returned alist DOES NOT share structure with MENULIST.
519 (defun imenu--split-menu (menulist title)
520 (let ((menulist (copy-sequence menulist))
521 keep-at-top tail)
522 (if (memq imenu--rescan-item menulist)
523 (setq keep-at-top (list imenu--rescan-item)
524 menulist (delq imenu--rescan-item menulist)))
525 (setq tail menulist)
526 (dolist (item tail)
527 (when (imenu--subalist-p item)
528 (push item keep-at-top)
529 (setq menulist (delq item menulist))))
530 (if imenu-sort-function
531 (setq menulist (sort menulist imenu-sort-function)))
532 (if (> (length menulist) imenu-max-items)
533 (setq menulist
534 (mapcar
535 (lambda (menu)
536 (cons (format "From: %s" (caar menu)) menu))
537 (imenu--split menulist imenu-max-items))))
538 (cons title
539 (nconc (nreverse keep-at-top) menulist))))
540
541 ;;; Split up each long alist that are nested within ALIST
542 ;;; into nested alists.
543 ;;;
544 ;;; Return a split and sorted copy of ALIST. The returned alist DOES
545 ;;; NOT share structure with ALIST.
546 (defun imenu--split-submenus (alist)
547 (mapcar (function
548 (lambda (elt)
549 (if (and (consp elt)
550 (stringp (car elt))
551 (listp (cdr elt)))
552 (imenu--split-menu (cdr elt) (car elt))
553 elt)))
554 alist))
555
556 ;;; Truncate all strings in MENULIST to imenu-max-item-length
557 (defun imenu--truncate-items (menulist)
558 (mapcar (function
559 (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))
568
569
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.
575
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 (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))
595
596 ;;; Find all markers in alist and makes
597 ;;; them point nowhere.
598 ;;; The top-level call uses nil as the argument;
599 ;;; non-nil arguments are in recursivecalls.
600 (defvar imenu--cleanup-seen)
601
602 (defun imenu--cleanup (&optional alist)
603 ;; If alist is provided use that list.
604 ;; If not, empty the table of lists already seen
605 ;; and use imenu--index-alist.
606 (if alist
607 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
608 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
609
610 (and alist
611 (mapc
612 (lambda (item)
613 (cond
614 ((markerp (cdr item))
615 (set-marker (cdr item) nil))
616 ;; Don't process one alist twice.
617 ((memq (cdr item) imenu--cleanup-seen))
618 ((imenu--subalist-p item)
619 (imenu--cleanup (cdr item)))))
620 alist)
621 t))
622
623 (defun imenu--create-keymap (title alist &optional cmd)
624 (list* 'keymap title
625 (mapcar
626 (lambda (item)
627 (list* (car item) (car item)
628 (cond
629 ((imenu--subalist-p item)
630 (imenu--create-keymap (car item) (cdr item) cmd))
631 (t
632 `(lambda () (interactive)
633 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
634 alist)))
635
636 (defun imenu--in-alist (str alist)
637 "Check whether the string STR is contained in multi-level ALIST."
638 (let (elt head tail res)
639 (setq res nil)
640 (while alist
641 (setq elt (car alist)
642 tail (cdr elt)
643 alist (cdr alist)
644 head (car elt))
645 ;; A nested ALIST element looks like
646 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
647 ;; while a bottom-level element looks like
648 ;; (INDEX-NAME . INDEX-POSITION)
649 ;; We are only interested in the bottom-level elements, so we need to
650 ;; recurse if TAIL is a list.
651 (cond ((listp tail)
652 (if (setq res (imenu--in-alist str tail))
653 (setq alist nil)))
654 ((if imenu-name-lookup-function
655 (funcall imenu-name-lookup-function str head)
656 (string= str head))
657 (setq alist nil res elt))))
658 res))
659
660 (defvar imenu-syntax-alist nil
661 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
662
663 The car of the assocs may be either a character or a string and the
664 cdr is a syntax description appropriate for `modify-syntax-entry'. For
665 a string, all the characters in the string get the specified syntax.
666
667 This is typically used to give word syntax to characters which
668 normally have symbol syntax to simplify `imenu-expression'
669 and speed-up matching.")
670 ;;;###autoload
671 (make-variable-buffer-local 'imenu-syntax-alist)
672
673 (defun imenu-default-create-index-function ()
674 "Default function to create an index alist of the current buffer.
675
676 The most general method is to move point to end of buffer, then repeatedly call
677 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
678 All the results returned by the latter are gathered into an index alist.
679 This method is used if those two variables are non-nil.
680
681 The alternate method, which is the one most often used, is to call
682 `imenu--generic-function' with `imenu-generic-expression' as argument."
683 ;; These should really be done by setting imenu-create-index-function
684 ;; in these major modes. But save that change for later.
685 (cond ((and imenu-prev-index-position-function
686 imenu-extract-index-name-function)
687 (let ((index-alist '())
688 prev-pos name)
689 (goto-char (point-max))
690 (imenu-progress-message prev-pos 0 t)
691 ;; Search for the function
692 (while (funcall imenu-prev-index-position-function)
693 (imenu-progress-message prev-pos nil t)
694 (save-excursion
695 (setq name (funcall imenu-extract-index-name-function)))
696 (and (stringp name)
697 ;; [ydi] updated for imenu-use-markers
698 (push (cons name (if imenu-use-markers (point-marker) (point)))
699 index-alist)))
700 (imenu-progress-message prev-pos 100 t)
701 index-alist))
702 ;; Use generic expression if possible.
703 ((and imenu-generic-expression)
704 (imenu--generic-function imenu-generic-expression))
705 (t
706 (error "This buffer cannot use `imenu-default-create-index-function'"))))
707
708 ;;;
709 ;;; Generic index gathering function.
710 ;;;
711
712 (defvar imenu-case-fold-search t
713 "Defines whether `imenu--generic-function' should fold case when matching.
714
715 This variable should be set (only) by initialization code
716 for modes which use `imenu--generic-function'. If it is not set, but
717 `font-lock-defaults' is set, then font-lock's setting is used.")
718 ;;;###autoload
719 (make-variable-buffer-local 'imenu-case-fold-search)
720
721 ;; This function can be called with quitting disabled,
722 ;; so it needs to be careful never to loop!
723 (defun imenu--generic-function (patterns)
724 "Return an index alist of the current buffer based on PATTERNS.
725
726 PATTERNS is an alist with elements that look like this:
727 (MENU-TITLE REGEXP INDEX)
728 or like this:
729 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
730 with zero or more ARGUMENTS. The former format creates a simple
731 element in the index alist when it matches; the latter creates a
732 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
733 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
734
735 MENU-TITLE is a string used as the title for the submenu or nil
736 if the entries are not nested.
737
738 REGEXP is a regexp that should match a construct in the buffer
739 that is to be displayed in the menu; i.e., function or variable
740 definitions, etc. It contains a substring which is the name to
741 appear in the menu. See the info section on Regexps for more
742 information. REGEXP may also be a function, called without
743 arguments. It is expected to search backwards. It shall return
744 true and set `match-data' if it finds another element.
745
746 INDEX points to the substring in REGEXP that contains the
747 name (of the function, variable or type) that is to appear in the
748 menu.
749
750 The variable `imenu-case-fold-search' determines whether or not the
751 regexp matches are case sensitive, and `imenu-syntax-alist' can be
752 used to alter the syntax table for the search.
753
754 See `lisp-imenu-generic-expression' for an example of PATTERNS.
755
756 Returns an index of the current buffer as an alist. The elements in
757 the alist look like:
758 (INDEX-NAME . INDEX-POSITION)
759 or like:
760 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
761 They may also be nested index alists like:
762 (INDEX-NAME . INDEX-ALIST)
763 depending on PATTERNS."
764
765 (let ((index-alist (list 'dummy))
766 prev-pos
767 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
768 (not (local-variable-p 'font-lock-defaults)))
769 imenu-case-fold-search
770 (nth 2 font-lock-defaults)))
771 (old-table (syntax-table))
772 (table (copy-syntax-table (syntax-table)))
773 (slist imenu-syntax-alist))
774 ;; Modify the syntax table used while matching regexps.
775 (dolist (syn slist)
776 ;; The character(s) to modify may be a single char or a string.
777 (if (numberp (car syn))
778 (modify-syntax-entry (car syn) (cdr syn) table)
779 (mapc (lambda (c)
780 (modify-syntax-entry c (cdr syn) table))
781 (car syn))))
782 (goto-char (point-max))
783 (imenu-progress-message prev-pos 0 t)
784 (unwind-protect ; for syntax table
785 (save-match-data
786 (set-syntax-table table)
787
788 ;; map over the elements of imenu-generic-expression
789 ;; (typically functions, variables ...)
790 (dolist (pat patterns)
791 (let ((menu-title (car pat))
792 (regexp (nth 1 pat))
793 (index (nth 2 pat))
794 (function (nth 3 pat))
795 (rest (nthcdr 4 pat))
796 start beg)
797 ;; Go backwards for convenience of adding items in order.
798 (goto-char (point-max))
799 (while (and (if (functionp regexp)
800 (funcall regexp)
801 (re-search-backward regexp nil t))
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 (imenu-progress-message prev-pos nil t)
812 ;; Add this sort of submenu only when we've found an
813 ;; item for it, avoiding empty, duff menus.
814 (unless (assoc menu-title index-alist)
815 (push (list menu-title) index-alist))
816 (if imenu-use-markers
817 (setq beg (copy-marker beg)))
818 (let ((item
819 (if function
820 (nconc (list (match-string-no-properties index)
821 beg function)
822 rest)
823 (cons (match-string-no-properties index)
824 beg)))
825 ;; This is the desired submenu,
826 ;; starting with its title (or nil).
827 (menu (assoc menu-title index-alist)))
828 ;; Insert the item unless it is already present.
829 (unless (member item (cdr menu))
830 (setcdr menu
831 (cons item (cdr menu)))))
832 ;; Go to the start of the match, to make sure we
833 ;; keep making progress backwards.
834 (goto-char start))))
835 (set-syntax-table old-table)))
836 (imenu-progress-message prev-pos 100 t)
837 ;; Sort each submenu by position.
838 ;; This is in case one submenu gets items from two different regexps.
839 (dolist (item index-alist)
840 (when (listp item)
841 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
842 (let ((main-element (assq nil index-alist)))
843 (nconc (delq main-element (delq 'dummy index-alist))
844 (cdr main-element)))))
845
846 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
847 ;;;
848 ;;; The main functions for this package!
849 ;;;
850 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
851
852 ;; See also info-lookup-find-item
853 (defun imenu-find-default (guess completions)
854 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
855 (catch 'found
856 (let ((case-fold-search t))
857 (if (assoc guess completions) guess
858 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
859 (concat "\\`" (regexp-quote guess))
860 (concat (regexp-quote guess) "\\'")
861 (regexp-quote guess)))
862 (dolist (x completions)
863 (if (string-match re (car x)) (throw 'found (car x)))))))))
864
865 (defun imenu--completion-buffer (index-alist &optional prompt)
866 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
867
868 Return one of the entries in index-alist or nil."
869 ;; Create a list for this buffer only when needed.
870 (let ((name (thing-at-point 'symbol))
871 choice
872 (prepared-index-alist
873 (if (not imenu-space-replacement) index-alist
874 (mapcar
875 (lambda (item)
876 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
877 (car item))
878 (cdr item)))
879 index-alist))))
880 (when (stringp name)
881 (setq name (or (imenu-find-default name prepared-index-alist) name)))
882 (cond (prompt)
883 ((and name (imenu--in-alist name prepared-index-alist))
884 (setq prompt (format "Index item (default %s): " name)))
885 (t (setq prompt "Index item: ")))
886 (let ((minibuffer-setup-hook minibuffer-setup-hook))
887 ;; Display the completion buffer.
888 (if (not imenu-eager-completion-buffer)
889 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
890 (setq name (completing-read prompt
891 prepared-index-alist
892 nil t nil 'imenu--history-list name)))
893
894 (when (stringp name)
895 (setq choice (assoc name prepared-index-alist))
896 (if (imenu--subalist-p choice)
897 (imenu--completion-buffer (cdr choice) prompt)
898 choice))))
899
900 (defun imenu--mouse-menu (index-alist event &optional title)
901 "Let the user select from a buffer index from a mouse menu.
902
903 INDEX-ALIST is the buffer index and EVENT is a mouse event.
904
905 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
906 (setq index-alist (imenu--split-submenus index-alist))
907 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
908 (map (imenu--create-keymap (car menu)
909 (cdr (if (< 1 (length (cdr menu)))
910 menu
911 (car (cdr menu)))))))
912 (popup-menu map event)))
913
914 (defun imenu-choose-buffer-index (&optional prompt alist)
915 "Let the user select from a buffer index and return the chosen index.
916
917 If the user originally activated this function with the mouse, a mouse
918 menu is used. Otherwise a completion buffer is used and the user is
919 prompted with PROMPT.
920
921 If you call this function with index alist ALIST, then it lets the user
922 select from ALIST.
923
924 With no index alist ALIST, it calls `imenu--make-index-alist' to
925 create the index alist.
926
927 If `imenu-use-popup-menu' is nil, then the completion buffer
928 is always used, no matter if the mouse was used or not.
929
930 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
931 (let (index-alist
932 (mouse-triggered (listp last-nonmenu-event))
933 (result t))
934 ;; If selected by mouse, see to that the window where the mouse is
935 ;; really is selected.
936 (and mouse-triggered
937 (not (equal last-nonmenu-event '(menu-bar)))
938 (let ((window (posn-window (event-start last-nonmenu-event))))
939 (or (framep window) (null window) (select-window window))))
940 ;; Create a list for this buffer only when needed.
941 (while (eq result t)
942 (setq index-alist (if alist alist (imenu--make-index-alist)))
943 (setq result
944 (if (and imenu-use-popup-menu
945 (or (eq imenu-use-popup-menu t) mouse-triggered))
946 (imenu--mouse-menu index-alist last-nonmenu-event)
947 (imenu--completion-buffer index-alist prompt)))
948 (and (equal result imenu--rescan-item)
949 (imenu--cleanup)
950 (setq result t imenu--index-alist nil)))
951 result))
952
953 ;;;###autoload
954 (defun imenu-add-to-menubar (name)
955 "Add an `imenu' entry to the menu bar for the current buffer.
956 NAME is a string used to name the menu bar item.
957 See the command `imenu' for more information."
958 (interactive "sImenu menu item name: ")
959 (if (or (and imenu-prev-index-position-function
960 imenu-extract-index-name-function)
961 imenu-generic-expression
962 (not (eq imenu-create-index-function
963 'imenu-default-create-index-function)))
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 (setcdr old (cdr menu1)))))))
1010
1011 (defun imenu--menubar-select (item)
1012 "Use Imenu to select the function or variable named in this menu ITEM."
1013 (if (equal item imenu--rescan-item)
1014 (progn
1015 (imenu--cleanup)
1016 ;; Make sure imenu-update-menubar redoes everything.
1017 (setq imenu-menubar-modified-tick -1)
1018 (setq imenu--index-alist nil)
1019 (setq imenu--last-menubar-index-alist nil)
1020 (imenu-update-menubar)
1021 t)
1022 (imenu item)
1023 nil))
1024
1025 (defun imenu-default-goto-function (name position &optional rest)
1026 "Move to the given position.
1027
1028 NAME is ignored. POSITION is where to move. REST is also ignored.
1029 The ignored args just make this function have the same interface as a
1030 function placed in a special index-item."
1031 (if (or (< position (point-min))
1032 (> position (point-max)))
1033 ;; widen if outside narrowing
1034 (widen))
1035 (goto-char position))
1036
1037 ;;;###autoload
1038 (defun imenu (index-item)
1039 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1040 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1041 for more information."
1042 (interactive (list (imenu-choose-buffer-index)))
1043 ;; Convert a string to an alist element.
1044 (if (stringp index-item)
1045 (setq index-item (assoc index-item (imenu--make-index-alist))))
1046 (when index-item
1047 (push-mark)
1048 (let* ((is-special-item (listp (cdr index-item)))
1049 (function
1050 (if is-special-item
1051 (nth 2 index-item) imenu-default-goto-function))
1052 (position (if is-special-item
1053 (cadr index-item) (cdr index-item)))
1054 (rest (if is-special-item (cddr index-item))))
1055 (apply function (car index-item) position rest))
1056 (run-hooks 'imenu-after-jump-hook)))
1057
1058 (dolist (mess
1059 '("^No items suitable for an index found in this buffer$"
1060 "^This buffer cannot use `imenu-default-create-index-function'$"
1061 "^The mode `.*' does not support Imenu$"))
1062 (add-to-list 'debug-ignored-errors mess))
1063
1064 (provide 'imenu)
1065
1066 ;; arch-tag: 98a2f5f5-4b91-4704-b18c-3aacf77d77a7
1067 ;;; imenu.el ends here