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