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