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