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