]> code.delx.au - gnu-emacs/blob - lisp/imenu.el
6be6b85af8aa3a536ae63389b8df60a40be44b9a
[gnu-emacs] / lisp / imenu.el
1 ;;; imenu.el --- framework for mode-specific buffer indexes
2
3 ;; Copyright (C) 1994-1998, 2001-2011 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 prev-pos)
343 (goto-char (point-max))
344 (imenu-progress-message prev-pos 0)
345 ;; Search for the function
346 (while (beginning-of-defun)
347 (imenu-progress-message prev-pos nil t)
348 (save-match-data
349 (and (looking-at "(def")
350 (save-excursion
351 (down-list 1)
352 (cond
353 ((looking-at "def\\(var\\|const\\)")
354 (forward-sexp 2)
355 (push (imenu-example--name-and-position)
356 index-var-alist))
357 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
358 (forward-sexp 2)
359 (push (imenu-example--name-and-position)
360 index-alist))
361 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
362 (forward-sexp 2)
363 (if (= (char-after (1- (point))) ?\))
364 (progn
365 (forward-sexp -1)
366 (down-list 1)
367 (forward-sexp 1)))
368 (push (imenu-example--name-and-position)
369 index-type-alist))
370 (t
371 (forward-sexp 2)
372 (push (imenu-example--name-and-position)
373 index-unknown-alist)))))))
374 (imenu-progress-message prev-pos 100)
375 (and index-var-alist
376 (push (cons "Variables" index-var-alist)
377 index-alist))
378 (and index-type-alist
379 (push (cons "Types" index-type-alist)
380 index-alist))
381 (and index-unknown-alist
382 (push (cons "Syntax-unknown" index-unknown-alist)
383 index-alist))
384 index-alist))
385 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
386
387 ;; Regular expression to find C functions
388 (defvar imenu-example--function-name-regexp-c
389 (concat
390 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
391 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
392 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
393 "\\([*&]+[ \t]*\\)?" ; pointer
394 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
395 ))
396
397 (defun imenu-example--create-c-index (&optional regexp)
398 (let ((index-alist '())
399 prev-pos char)
400 (goto-char (point-min))
401 (imenu-progress-message prev-pos 0)
402 ;; Search for the function
403 (save-match-data
404 (while (re-search-forward
405 (or regexp imenu-example--function-name-regexp-c)
406 nil t)
407 (imenu-progress-message prev-pos)
408 (backward-up-list 1)
409 (save-excursion
410 (goto-char (scan-sexps (point) 1))
411 (setq char (following-char)))
412 ;; Skip this function name if it is a prototype declaration.
413 (if (not (eq char ?\;))
414 (push (imenu-example--name-and-position) index-alist))))
415 (imenu-progress-message prev-pos 100)
416 (nreverse index-alist)))
417 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
418
419 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
420 ;;;
421 ;;; Internal variables
422 ;;;
423 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
424
425 ;; The item to use in the index for rescanning the buffer.
426 (defconst imenu--rescan-item '("*Rescan*" . -99))
427
428 ;; The latest buffer index.
429 ;; Buffer local.
430 (defvar imenu--index-alist nil
431 "The buffer index alist computed for this buffer in Imenu.
432
433 Simple elements in the alist look like (INDEX-NAME . POSITION).
434 POSITION is the buffer position of the item; to go to the item
435 is simply to move point to that position.
436
437 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
438 To \"go to\" a special element means applying FUNCTION
439 to INDEX-NAME, POSITION, and the ARGUMENTS.
440
441 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
442 The function `imenu--subalist-p' tests an element and returns t
443 if it is a sub-alist.
444
445 There is one simple element with negative POSITION; selecting that
446 element recalculates the buffer's index alist.")
447 ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
448
449 (make-variable-buffer-local 'imenu--index-alist)
450
451 (defvar imenu--last-menubar-index-alist nil
452 "The latest buffer index alist used to update the menu bar menu.")
453
454 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
455
456 ;; History list for 'jump-to-function-in-buffer'.
457 ;; Making this buffer local caused it not to work!
458 (defvar imenu--history-list nil)
459
460 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
461 ;;;
462 ;;; Internal support functions
463 ;;;
464 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
465
466 ;;;
467 ;;; Sort function
468 ;;; Sorts the items depending on their index name.
469 ;;; An item looks like (NAME . POSITION).
470 ;;;
471 (defun imenu--sort-by-name (item1 item2)
472 (string-lessp (car item1) (car item2)))
473
474 (defun imenu--sort-by-position (item1 item2)
475 (< (cdr item1) (cdr item2)))
476
477 (defun imenu--relative-position (&optional reverse)
478 ;; Support function to calculate relative position in buffer
479 ;; Beginning of buffer is 0 and end of buffer is 100
480 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
481 (let ((pos (point))
482 (total (buffer-size)))
483 (and reverse (setq pos (- total pos)))
484 (if (> total 50000)
485 ;; Avoid overflow from multiplying by 100!
486 (/ (1- pos) (max (/ total 100) 1))
487 (/ (* 100 (1- pos)) (max total 1)))))
488
489 ;; Split LIST into sublists of max length N.
490 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
491 ;;
492 ;; The returned list DOES NOT share structure with LIST.
493 (defun imenu--split (list n)
494 (let ((remain list)
495 (result '())
496 (sublist '())
497 (i 0))
498 (while remain
499 (push (pop remain) sublist)
500 (incf i)
501 (and (= i n)
502 ;; We have finished a sublist
503 (progn (push (nreverse sublist) result)
504 (setq i 0)
505 (setq sublist '()))))
506 ;; There might be a sublist (if the length of LIST mod n is != 0)
507 ;; that has to be added to the result list.
508 (and sublist
509 (push (nreverse sublist) result))
510 (nreverse result)))
511
512 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
513 ;;; In any case, add TITLE to the front of the alist.
514 ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
515 ;;; beginning of the returned alist.
516 ;;;
517 ;;; The returned alist DOES NOT share structure with MENULIST.
518 (defun imenu--split-menu (menulist title)
519 (let ((menulist (copy-sequence menulist))
520 keep-at-top tail)
521 (if (memq imenu--rescan-item menulist)
522 (setq keep-at-top (list imenu--rescan-item)
523 menulist (delq imenu--rescan-item menulist)))
524 (setq tail menulist)
525 (dolist (item tail)
526 (when (imenu--subalist-p item)
527 (push item keep-at-top)
528 (setq menulist (delq item menulist))))
529 (if imenu-sort-function
530 (setq menulist (sort menulist imenu-sort-function)))
531 (if (> (length menulist) imenu-max-items)
532 (setq menulist
533 (mapcar
534 (lambda (menu)
535 (cons (format "From: %s" (caar menu)) menu))
536 (imenu--split menulist imenu-max-items))))
537 (cons title
538 (nconc (nreverse keep-at-top) menulist))))
539
540 ;;; Split up each long alist that are nested within ALIST
541 ;;; into nested alists.
542 ;;;
543 ;;; Return a split and sorted copy of ALIST. The returned alist DOES
544 ;;; NOT share structure with ALIST.
545 (defun imenu--split-submenus (alist)
546 (mapcar (function
547 (lambda (elt)
548 (if (and (consp elt)
549 (stringp (car elt))
550 (listp (cdr elt)))
551 (imenu--split-menu (cdr elt) (car elt))
552 elt)))
553 alist))
554
555 ;;; Truncate all strings in MENULIST to imenu-max-item-length
556 (defun imenu--truncate-items (menulist)
557 (mapcar (function
558 (lambda (item)
559 (cond
560 ((consp (cdr item))
561 (imenu--truncate-items (cdr item)))
562 ;; truncate if necessary
563 ((and (numberp imenu-max-item-length)
564 (> (length (car item)) imenu-max-item-length))
565 (setcar item (substring (car item) 0 imenu-max-item-length))))))
566 menulist))
567
568
569 (defun imenu--make-index-alist (&optional noerror)
570 "Create an index alist for the definitions in the current buffer.
571 This works by using the hook function `imenu-create-index-function'.
572 Report an error if the list is empty unless NOERROR is supplied and
573 non-nil.
574
575 See `imenu--index-alist' for the format of the index alist."
576 (or (and imenu--index-alist
577 (or (not imenu-auto-rescan)
578 (and imenu-auto-rescan
579 (> (buffer-size) imenu-auto-rescan-maxout))))
580 ;; Get the index; truncate if necessary
581 (progn
582 (setq imenu--index-alist
583 (save-excursion
584 (save-restriction
585 (widen)
586 (funcall imenu-create-index-function))))
587 (imenu--truncate-items imenu--index-alist)))
588 (or imenu--index-alist noerror
589 (error "No items suitable for an index found in this buffer"))
590 (or imenu--index-alist
591 (setq imenu--index-alist (list nil)))
592 ;; Add a rescan option to the index.
593 (cons imenu--rescan-item imenu--index-alist))
594
595 ;;; Find all markers in alist and makes
596 ;;; them point nowhere.
597 ;;; The top-level call uses nil as the argument;
598 ;;; non-nil arguments are in recursive calls.
599 (defvar imenu--cleanup-seen)
600
601 (defun imenu--cleanup (&optional alist)
602 ;; If alist is provided use that list.
603 ;; If not, empty the table of lists already seen
604 ;; and use imenu--index-alist.
605 (if alist
606 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
607 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
608
609 (and alist
610 (mapc
611 (lambda (item)
612 (cond
613 ((markerp (cdr item))
614 (set-marker (cdr item) nil))
615 ;; Don't process one alist twice.
616 ((memq (cdr item) imenu--cleanup-seen))
617 ((imenu--subalist-p item)
618 (imenu--cleanup (cdr item)))))
619 alist)
620 t))
621
622 (defun imenu--create-keymap (title alist &optional cmd)
623 (list* 'keymap title
624 (mapcar
625 (lambda (item)
626 (list* (car item) (car item)
627 (cond
628 ((imenu--subalist-p item)
629 (imenu--create-keymap (car item) (cdr item) cmd))
630 (t
631 `(lambda () (interactive)
632 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
633 alist)))
634
635 (defun imenu--in-alist (str alist)
636 "Check whether the string STR is contained in multi-level ALIST."
637 (let (elt head tail res)
638 (setq res nil)
639 (while alist
640 (setq elt (car alist)
641 tail (cdr elt)
642 alist (cdr alist)
643 head (car elt))
644 ;; A nested ALIST element looks like
645 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
646 ;; while a bottom-level element looks like
647 ;; (INDEX-NAME . INDEX-POSITION)
648 ;; We are only interested in the bottom-level elements, so we need to
649 ;; recurse if TAIL is a list.
650 (cond ((listp tail)
651 (if (setq res (imenu--in-alist str tail))
652 (setq alist nil)))
653 ((if imenu-name-lookup-function
654 (funcall imenu-name-lookup-function str head)
655 (string= str head))
656 (setq alist nil res elt))))
657 res))
658
659 (defvar imenu-syntax-alist nil
660 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
661
662 The car of the assocs may be either a character or a string and the
663 cdr is a syntax description appropriate for `modify-syntax-entry'. For
664 a string, all the characters in the string get the specified syntax.
665
666 This is typically used to give word syntax to characters which
667 normally have symbol syntax to simplify `imenu-expression'
668 and speed-up matching.")
669 ;;;###autoload
670 (make-variable-buffer-local 'imenu-syntax-alist)
671
672 (defun imenu-default-create-index-function ()
673 "Default function to create an index alist of the current buffer.
674
675 The most general method is to move point to end of buffer, then repeatedly call
676 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
677 All the results returned by the latter are gathered into an index alist.
678 This method is used if those two variables are non-nil.
679
680 The alternate method, which is the one most often used, is to call
681 `imenu--generic-function' with `imenu-generic-expression' as argument."
682 ;; These should really be done by setting imenu-create-index-function
683 ;; in these major modes. But save that change for later.
684 (cond ((and imenu-prev-index-position-function
685 imenu-extract-index-name-function)
686 (let ((index-alist '()) (pos (point))
687 prev-pos name)
688 (goto-char (point-max))
689 (imenu-progress-message prev-pos 0 t)
690 ;; Search for the function
691 (while (funcall imenu-prev-index-position-function)
692 (when (= pos (point))
693 (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
694 (setq pos (point))
695 (imenu-progress-message prev-pos nil t)
696 (save-excursion
697 (setq name (funcall imenu-extract-index-name-function)))
698 (and (stringp name)
699 ;; [ydi] updated for imenu-use-markers
700 (push (cons name (if imenu-use-markers (point-marker) (point)))
701 index-alist)))
702 (imenu-progress-message prev-pos 100 t)
703 index-alist))
704 ;; Use generic expression if possible.
705 ((and imenu-generic-expression)
706 (imenu--generic-function imenu-generic-expression))
707 (t
708 (error "This buffer cannot use `imenu-default-create-index-function'"))))
709
710 ;;;
711 ;;; Generic index gathering function.
712 ;;;
713
714 (defvar imenu-case-fold-search t
715 "Defines whether `imenu--generic-function' should fold case when matching.
716
717 This variable should be set (only) by initialization code
718 for modes which use `imenu--generic-function'. If it is not set, but
719 `font-lock-defaults' is set, then font-lock's setting is used.")
720 ;;;###autoload
721 (make-variable-buffer-local 'imenu-case-fold-search)
722
723 ;; This function can be called with quitting disabled,
724 ;; so it needs to be careful never to loop!
725 (defun imenu--generic-function (patterns)
726 "Return an index alist of the current buffer based on PATTERNS.
727
728 PATTERNS is an alist with elements that look like this:
729 (MENU-TITLE REGEXP INDEX)
730 or like this:
731 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
732 with zero or more ARGUMENTS. The former format creates a simple
733 element in the index alist when it matches; the latter creates a
734 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
735 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
736
737 MENU-TITLE is a string used as the title for the submenu or nil
738 if the entries are not nested.
739
740 REGEXP is a regexp that should match a construct in the buffer
741 that is to be displayed in the menu; i.e., function or variable
742 definitions, etc. It contains a substring which is the name to
743 appear in the menu. See the info section on Regexps for more
744 information. REGEXP may also be a function, called without
745 arguments. It is expected to search backwards. It shall return
746 true and set `match-data' if it finds another element.
747
748 INDEX points to the substring in REGEXP that contains the
749 name (of the function, variable or type) that is to appear in the
750 menu.
751
752 The variable `imenu-case-fold-search' determines whether or not the
753 regexp matches are case sensitive, and `imenu-syntax-alist' can be
754 used to alter the syntax table for the search.
755
756 See `lisp-imenu-generic-expression' for an example of PATTERNS.
757
758 Returns an index of the current buffer as an alist. The elements in
759 the alist look like:
760 (INDEX-NAME . INDEX-POSITION)
761 or like:
762 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
763 They may also be nested index alists like:
764 (INDEX-NAME . INDEX-ALIST)
765 depending on PATTERNS."
766
767 (let ((index-alist (list 'dummy))
768 prev-pos
769 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
770 (not (local-variable-p 'font-lock-defaults)))
771 imenu-case-fold-search
772 (nth 2 font-lock-defaults)))
773 (old-table (syntax-table))
774 (table (copy-syntax-table (syntax-table)))
775 (slist imenu-syntax-alist))
776 ;; Modify the syntax table used while matching regexps.
777 (dolist (syn slist)
778 ;; The character(s) to modify may be a single char or a string.
779 (if (numberp (car syn))
780 (modify-syntax-entry (car syn) (cdr syn) table)
781 (mapc (lambda (c)
782 (modify-syntax-entry c (cdr syn) table))
783 (car syn))))
784 (goto-char (point-max))
785 (imenu-progress-message prev-pos 0 t)
786 (unwind-protect ; for syntax table
787 (save-match-data
788 (set-syntax-table table)
789
790 ;; map over the elements of imenu-generic-expression
791 ;; (typically functions, variables ...)
792 (dolist (pat patterns)
793 (let ((menu-title (car pat))
794 (regexp (nth 1 pat))
795 (index (nth 2 pat))
796 (function (nth 3 pat))
797 (rest (nthcdr 4 pat))
798 start beg)
799 ;; Go backwards for convenience of adding items in order.
800 (goto-char (point-max))
801 (while (and (if (functionp regexp)
802 (funcall regexp)
803 (re-search-backward regexp nil t))
804 ;; Exit the loop if we get an empty match,
805 ;; because it means a bad regexp was specified.
806 (not (= (match-beginning 0) (match-end 0))))
807 (setq start (point))
808 ;; Record the start of the line in which the match starts.
809 ;; That's the official position of this definition.
810 (goto-char (match-beginning index))
811 (beginning-of-line)
812 (setq beg (point))
813 (imenu-progress-message prev-pos nil t)
814 ;; Add this sort of submenu only when we've found an
815 ;; item for it, avoiding empty, duff menus.
816 (unless (assoc menu-title index-alist)
817 (push (list menu-title) index-alist))
818 (if imenu-use-markers
819 (setq beg (copy-marker beg)))
820 (let ((item
821 (if function
822 (nconc (list (match-string-no-properties index)
823 beg function)
824 rest)
825 (cons (match-string-no-properties index)
826 beg)))
827 ;; This is the desired submenu,
828 ;; starting with its title (or nil).
829 (menu (assoc menu-title index-alist)))
830 ;; Insert the item unless it is already present.
831 (unless (member item (cdr menu))
832 (setcdr menu
833 (cons item (cdr menu)))))
834 ;; Go to the start of the match, to make sure we
835 ;; keep making progress backwards.
836 (goto-char start))))
837 (set-syntax-table old-table)))
838 (imenu-progress-message prev-pos 100 t)
839 ;; Sort each submenu by position.
840 ;; This is in case one submenu gets items from two different regexps.
841 (dolist (item index-alist)
842 (when (listp item)
843 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
844 (let ((main-element (assq nil index-alist)))
845 (nconc (delq main-element (delq 'dummy index-alist))
846 (cdr main-element)))))
847
848 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
849 ;;;
850 ;;; The main functions for this package!
851 ;;;
852 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
853
854 ;; See also info-lookup-find-item
855 (defun imenu-find-default (guess completions)
856 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
857 (catch 'found
858 (let ((case-fold-search t))
859 (if (assoc guess completions) guess
860 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
861 (concat "\\`" (regexp-quote guess))
862 (concat (regexp-quote guess) "\\'")
863 (regexp-quote guess)))
864 (dolist (x completions)
865 (if (string-match re (car x)) (throw 'found (car x)))))))))
866
867 (defun imenu--completion-buffer (index-alist &optional prompt)
868 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
869
870 Return one of the entries in index-alist or nil."
871 ;; Create a list for this buffer only when needed.
872 (let ((name (thing-at-point 'symbol))
873 choice
874 (prepared-index-alist
875 (if (not imenu-space-replacement) index-alist
876 (mapcar
877 (lambda (item)
878 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
879 (car item))
880 (cdr item)))
881 index-alist))))
882 (when (stringp name)
883 (setq name (or (imenu-find-default name prepared-index-alist) name)))
884 (cond (prompt)
885 ((and name (imenu--in-alist name prepared-index-alist))
886 (setq prompt (format "Index item (default %s): " name)))
887 (t (setq prompt "Index item: ")))
888 (let ((minibuffer-setup-hook minibuffer-setup-hook))
889 ;; Display the completion buffer.
890 (if (not imenu-eager-completion-buffer)
891 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
892 (setq name (completing-read prompt
893 prepared-index-alist
894 nil t nil 'imenu--history-list name)))
895
896 (when (stringp name)
897 (setq choice (assoc name prepared-index-alist))
898 (if (imenu--subalist-p choice)
899 (imenu--completion-buffer (cdr choice) prompt)
900 choice))))
901
902 (defun imenu--mouse-menu (index-alist event &optional title)
903 "Let the user select from a buffer index from a mouse menu.
904
905 INDEX-ALIST is the buffer index and EVENT is a mouse event.
906
907 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
908 (setq index-alist (imenu--split-submenus index-alist))
909 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
910 (map (imenu--create-keymap (car menu)
911 (cdr (if (< 1 (length (cdr menu)))
912 menu
913 (car (cdr menu)))))))
914 (popup-menu map event)))
915
916 (defun imenu-choose-buffer-index (&optional prompt alist)
917 "Let the user select from a buffer index and return the chosen index.
918
919 If the user originally activated this function with the mouse, a mouse
920 menu is used. Otherwise a completion buffer is used and the user is
921 prompted with PROMPT.
922
923 If you call this function with index alist ALIST, then it lets the user
924 select from ALIST.
925
926 With no index alist ALIST, it calls `imenu--make-index-alist' to
927 create the index alist.
928
929 If `imenu-use-popup-menu' is nil, then the completion buffer
930 is always used, no matter if the mouse was used or not.
931
932 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
933 (let (index-alist
934 (mouse-triggered (listp last-nonmenu-event))
935 (result t))
936 ;; If selected by mouse, see to that the window where the mouse is
937 ;; really is selected.
938 (and mouse-triggered
939 (not (equal last-nonmenu-event '(menu-bar)))
940 (let ((window (posn-window (event-start last-nonmenu-event))))
941 (or (framep window) (null window) (select-window window))))
942 ;; Create a list for this buffer only when needed.
943 (while (eq result t)
944 (setq index-alist (if alist alist (imenu--make-index-alist)))
945 (setq result
946 (if (and imenu-use-popup-menu
947 (or (eq imenu-use-popup-menu t) mouse-triggered))
948 (imenu--mouse-menu index-alist last-nonmenu-event)
949 (imenu--completion-buffer index-alist prompt)))
950 (and (equal result imenu--rescan-item)
951 (imenu--cleanup)
952 (setq result t imenu--index-alist nil)))
953 result))
954
955 ;;;###autoload
956 (defun imenu-add-to-menubar (name)
957 "Add an `imenu' entry to the menu bar for the current buffer.
958 NAME is a string used to name the menu bar item.
959 See the command `imenu' for more information."
960 (interactive "sImenu menu item name: ")
961 (if (or (and imenu-prev-index-position-function
962 imenu-extract-index-name-function)
963 imenu-generic-expression
964 (not (eq imenu-create-index-function
965 'imenu-default-create-index-function)))
966 (let ((newmap (make-sparse-keymap)))
967 (set-keymap-parent newmap (current-local-map))
968 (setq imenu--last-menubar-index-alist nil)
969 (define-key newmap [menu-bar index]
970 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
971 (use-local-map newmap)
972 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
973 (error "The mode `%s' does not support Imenu"
974 (format-mode-line mode-name))))
975
976 ;;;###autoload
977 (defun imenu-add-menubar-index ()
978 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
979
980 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
981 (interactive)
982 (imenu-add-to-menubar "Index"))
983
984 (defvar imenu-buffer-menubar nil)
985
986 (defvar imenu-menubar-modified-tick 0
987 "The value of (buffer-chars-modified-tick) as of the last call
988 to `imenu-update-menubar'.")
989 (make-variable-buffer-local 'imenu-menubar-modified-tick)
990
991 (defun imenu-update-menubar ()
992 (when (and (current-local-map)
993 (keymapp (lookup-key (current-local-map) [menu-bar index]))
994 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
995 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
996 (let ((index-alist (imenu--make-index-alist t)))
997 ;; Don't bother updating if the index-alist has not changed
998 ;; since the last time we did it.
999 (unless (equal index-alist imenu--last-menubar-index-alist)
1000 (let (menu menu1 old)
1001 (setq imenu--last-menubar-index-alist index-alist)
1002 (setq index-alist (imenu--split-submenus index-alist))
1003 (setq menu (imenu--split-menu index-alist
1004 (buffer-name)))
1005 (setq menu1 (imenu--create-keymap (car menu)
1006 (cdr (if (< 1 (length (cdr menu)))
1007 menu
1008 (car (cdr menu))))
1009 'imenu--menubar-select))
1010 (setq old (lookup-key (current-local-map) [menu-bar index]))
1011 (setcdr old (cdr menu1)))))))
1012
1013 (defun imenu--menubar-select (item)
1014 "Use Imenu to select the function or variable named in this menu ITEM."
1015 (if (equal item imenu--rescan-item)
1016 (progn
1017 (imenu--cleanup)
1018 ;; Make sure imenu-update-menubar redoes everything.
1019 (setq imenu-menubar-modified-tick -1)
1020 (setq imenu--index-alist nil)
1021 (setq imenu--last-menubar-index-alist nil)
1022 (imenu-update-menubar)
1023 t)
1024 (imenu item)
1025 nil))
1026
1027 (defun imenu-default-goto-function (name position &optional rest)
1028 "Move to the given position.
1029
1030 NAME is ignored. POSITION is where to move. REST is also ignored.
1031 The ignored args just make this function have the same interface as a
1032 function placed in a special index-item."
1033 (if (or (< position (point-min))
1034 (> position (point-max)))
1035 ;; widen if outside narrowing
1036 (widen))
1037 (goto-char position))
1038
1039 ;;;###autoload
1040 (defun imenu (index-item)
1041 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1042 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1043 for more information."
1044 (interactive (list (imenu-choose-buffer-index)))
1045 ;; Convert a string to an alist element.
1046 (if (stringp index-item)
1047 (setq index-item (assoc index-item (imenu--make-index-alist))))
1048 (when index-item
1049 (push-mark)
1050 (let* ((is-special-item (listp (cdr index-item)))
1051 (function
1052 (if is-special-item
1053 (nth 2 index-item) imenu-default-goto-function))
1054 (position (if is-special-item
1055 (cadr index-item) (cdr index-item)))
1056 (rest (if is-special-item (cddr index-item))))
1057 (apply function (car index-item) position rest))
1058 (run-hooks 'imenu-after-jump-hook)))
1059
1060 (dolist (mess
1061 '("^No items suitable for an index found in this buffer$"
1062 "^This buffer cannot use `imenu-default-create-index-function'$"
1063 "^The mode `.*' does not support Imenu$"))
1064 (add-to-list 'debug-ignored-errors mess))
1065
1066 (provide 'imenu)
1067
1068 ;;; imenu.el ends here