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