(mark_char_table): New function.
[emacs.git] / lisp / imenu.el
blob3873136f6935330d7838fabbb7355c53ad6417ba
1 ;;; imenu.el --- framework for mode-specific buffer indexes
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
7 ;; Lars Lindberg <lli@sypro.cap.se>
8 ;; Maintainer: FSF
9 ;; Created: 8 Feb 1994
10 ;; Keywords: tools convenience
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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 ;; It is documented in the Emacs Lisp manual.
36 ;; How it works:
38 ;; A mode-specific function is called to generate the index. It is
39 ;; then presented to the user, who can choose from this index.
41 ;; The package comes with a set of example functions for how to
42 ;; utilize this package.
44 ;; There are *examples* for index gathering functions/regular
45 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
46 ;; customize for other modes. A function for jumping to the chosen
47 ;; index position is also supplied.
49 ;;; History:
50 ;; Thanks go to
51 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
52 ;; [dean] - Dean Andrews ada@unison.com
53 ;; [alon] - Alon Albert al@mercury.co.il
54 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
55 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
56 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
57 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
58 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
59 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
61 ;;; Code:
63 (eval-when-compile (require 'cl))
65 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
66 ;;;
67 ;;; Customizable variables
68 ;;;
69 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
71 (defgroup imenu nil
72 "Mode-specific buffer indexes."
73 :group 'matching
74 :group 'frames
75 :group 'convenience
76 :link '(custom-manual "(elisp)Imenu"))
78 (defcustom imenu-use-markers t
79 "Non-nil means use markers instead of integers for Imenu buffer positions.
81 Setting this to nil makes Imenu work a little faster but editing the
82 buffer will make the generated index positions wrong.
84 This might not yet be honored by all index-building functions."
85 :type 'boolean
86 :group 'imenu)
89 (defcustom imenu-max-item-length 60
90 "If a number, truncate Imenu entries to that length."
91 :type '(choice integer
92 (const :tag "Unlimited"))
93 :group 'imenu)
95 (defcustom imenu-auto-rescan nil
96 "Non-nil means Imenu should always rescan the buffers."
97 :type 'boolean
98 :group 'imenu)
100 (defcustom imenu-auto-rescan-maxout 60000
101 "Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
102 This variable is buffer-local."
103 :type 'integer
104 :group 'imenu)
106 (defvar imenu-always-use-completion-buffer-p nil)
107 (make-obsolete-variable 'imenu-always-use-completion-buffer-p
108 'imenu-use-popup-menu "22.1")
110 (defcustom imenu-use-popup-menu
111 (if imenu-always-use-completion-buffer-p
112 (not (eq imenu-always-use-completion-buffer-p 'never))
113 'on-mouse)
114 "Use a popup menu rather than a minibuffer prompt.
115 If nil, always use a minibuffer prompt.
116 If t, always use a popup menu,
117 If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
118 :type '(choice (const :tag "On Mouse" on-mouse)
119 (const :tag "Never" nil)
120 (other :tag "Always" t))
121 :group 'imenu)
123 (defcustom imenu-eager-completion-buffer
124 (not (eq imenu-always-use-completion-buffer-p 'never))
125 "If non-nil, eagerly popup the completion buffer."
126 :type 'boolean
127 :group 'imenu
128 :version "22.1")
130 (defcustom imenu-after-jump-hook nil
131 "Hooks called after jumping to a place in the buffer.
133 Useful things to use here include `reposition-window', `recenter', and
134 \(lambda () (recenter 0)) to show at top of screen."
135 :type 'hook
136 :group 'imenu)
138 ;;;###autoload
139 (defcustom imenu-sort-function nil
140 "The function to use for sorting the index mouse-menu.
142 Affects only the mouse index menu.
144 Set this to nil if you don't want any sorting (faster).
145 The items in the menu are then presented in the order they were found
146 in the buffer.
148 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
150 The function should take two arguments and return t if the first
151 element should come before the second. The arguments are cons cells;
152 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
153 :type '(choice (const :tag "No sorting" nil)
154 (const :tag "Sort by name" imenu--sort-by-name)
155 (function :tag "Another function"))
156 :group 'imenu)
158 (defcustom imenu-max-items 25
159 "Maximum number of elements in a mouse menu for Imenu."
160 :type 'integer
161 :group 'imenu)
163 ;; No longer used. KFS 2004-10-27
164 ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
165 ;; "*Progress message during the index scanning of the buffer.
166 ;; If non-nil, user gets a message during the scanning of the buffer.
168 ;; Relevant only if the mode-specific function that creates the buffer
169 ;; index use `imenu-progress-message', and not useful if that is fast, in
170 ;; which case you might as well set this to nil."
171 ;; :type '(choice string
172 ;; (const :tag "None" nil))
173 ;; :group 'imenu)
175 (defcustom imenu-space-replacement "."
176 "The replacement string for spaces in index names.
177 Used when presenting the index in a completion buffer to make the
178 names work as tokens."
179 :type '(choice string (const nil))
180 :group 'imenu)
182 (defcustom imenu-level-separator ":"
183 "The separator between index names of different levels.
184 Used for making mouse-menu titles and for flattening nested indexes
185 with name concatenation."
186 :type 'string
187 :group 'imenu)
189 ;;;###autoload
190 (defvar imenu-generic-expression nil
191 "The regex pattern to use for creating a buffer index.
193 If non-nil this pattern is passed to `imenu--generic-function' to
194 create a buffer index. Look there for the documentation of this
195 pattern's structure.
197 For example, see the value of `fortran-imenu-generic-expression' used by
198 `fortran-mode' with `imenu-syntax-alist' set locally to give the
199 characters which normally have \"symbol\" syntax \"word\" syntax
200 during matching.")
202 ;;;###autoload
203 (make-variable-buffer-local 'imenu-generic-expression)
205 ;;;; Hooks
207 ;;;###autoload
208 (defvar imenu-create-index-function 'imenu-default-create-index-function
209 "The function to use for creating an index alist of the current buffer.
211 It should be a function that takes no arguments and returns
212 an index alist of the current buffer. The function is
213 called within a `save-excursion'.
215 See `imenu--index-alist' for the format of the buffer index alist.")
216 ;;;###autoload
217 (make-variable-buffer-local 'imenu-create-index-function)
219 ;;;###autoload
220 (defvar imenu-prev-index-position-function 'beginning-of-defun
221 "Function for finding the next index position.
223 If `imenu-create-index-function' is set to
224 `imenu-default-create-index-function', then you must set this variable
225 to a function that will find the next index, looking backwards in the
226 file.
228 The function should leave point at the place to be connected to the
229 index and it should return nil when it doesn't find another index.")
230 ;;;###autoload
231 (make-variable-buffer-local 'imenu-prev-index-position-function)
233 ;;;###autoload
234 (defvar imenu-extract-index-name-function nil
235 "Function for extracting the index item name, given a position.
237 This function is called after `imenu-prev-index-position-function'
238 finds a position for an index item, with point at that position.
239 It should return the name for that index item.")
240 ;;;###autoload
241 (make-variable-buffer-local 'imenu-extract-index-name-function)
243 ;;;###autoload
244 (defvar imenu-name-lookup-function nil
245 "Function to compare string with index item.
247 This function will be called with two strings, and should return
248 non-nil if they match.
250 If nil, comparison is done with `string='.
251 Set this to some other function for more advanced comparisons,
252 such as \"begins with\" or \"name matches and number of
253 arguments match\".")
254 ;;;###autoload
255 (make-variable-buffer-local 'imenu-name-lookup-function)
257 ;;;###autoload
258 (defvar imenu-default-goto-function 'imenu-default-goto-function
259 "The default function called when selecting an Imenu item.
260 The function in this variable is called when selecting a normal index-item.")
261 ;;;###autoload
262 (make-variable-buffer-local 'imenu-default-goto-function)
265 (defun imenu--subalist-p (item)
266 (and (consp (cdr item)) (listp (cadr item))
267 (not (eq (car (cadr item)) 'lambda))))
269 ;; Macro to display a progress message.
270 ;; RELPOS is the relative position to display.
271 ;; If RELPOS is nil, then the relative position in the buffer
272 ;; is calculated.
273 ;; PREVPOS is the variable in which we store the last position displayed.
274 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
276 ;; Made obsolete/empty, as computers are now faster than the eye, and
277 ;; it had problems updating the messages correctly, and could shadow
278 ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
280 ;; `(and
281 ;; imenu-scanning-message
282 ;; (let ((pos ,(if relpos
283 ;; relpos
284 ;; `(imenu--relative-position ,reverse))))
285 ;; (if ,(if relpos t
286 ;; `(> pos (+ 5 ,prevpos)))
287 ;; (progn
288 ;; (message imenu-scanning-message pos)
289 ;; (setq ,prevpos pos)))))
293 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
294 ;;;;
295 ;;;; Some examples of functions utilizing the framework of this
296 ;;;; package.
297 ;;;;
298 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
300 ;; FIXME: This was the only imenu-example-* definition actually used,
301 ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
302 ;; all be removed.
303 (defun imenu-example--name-and-position ()
304 "Return the current/previous sexp and its (beginning) location.
305 Don't move point."
306 (save-excursion
307 (forward-sexp -1)
308 ;; [ydi] modified for imenu-use-markers
309 (let ((beg (if imenu-use-markers (point-marker) (point)))
310 (end (progn (forward-sexp) (point))))
311 (cons (buffer-substring beg end)
312 beg))))
313 (make-obsolete 'imenu-example--name-and-position
314 "use your own function instead." "23.2")
317 ;;; Lisp
320 (defun imenu-example--lisp-extract-index-name ()
321 ;; Example of a candidate for `imenu-extract-index-name-function'.
322 ;; This will generate a flat index of definitions in a lisp file.
323 (save-match-data
324 (and (looking-at "(def")
325 (condition-case nil
326 (progn
327 (down-list 1)
328 (forward-sexp 2)
329 (let ((beg (point))
330 (end (progn (forward-sexp -1) (point))))
331 (buffer-substring beg end)))
332 (error nil)))))
333 (make-obsolete 'imenu-example--lisp-extract-index-name "your own" "23.2")
335 (defun imenu-example--create-lisp-index ()
336 ;; Example of a candidate for `imenu-create-index-function'.
337 ;; It will generate a nested index of definitions.
338 (let ((index-alist '())
339 (index-var-alist '())
340 (index-type-alist '())
341 (index-unknown-alist '())
342 prev-pos)
343 (goto-char (point-max))
344 (imenu-progress-message prev-pos 0)
345 ;; Search for the function
346 (while (beginning-of-defun)
347 (imenu-progress-message prev-pos nil t)
348 (save-match-data
349 (and (looking-at "(def")
350 (save-excursion
351 (down-list 1)
352 (cond
353 ((looking-at "def\\(var\\|const\\)")
354 (forward-sexp 2)
355 (push (imenu-example--name-and-position)
356 index-var-alist))
357 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
358 (forward-sexp 2)
359 (push (imenu-example--name-and-position)
360 index-alist))
361 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
362 (forward-sexp 2)
363 (if (= (char-after (1- (point))) ?\))
364 (progn
365 (forward-sexp -1)
366 (down-list 1)
367 (forward-sexp 1)))
368 (push (imenu-example--name-and-position)
369 index-type-alist))
371 (forward-sexp 2)
372 (push (imenu-example--name-and-position)
373 index-unknown-alist)))))))
374 (imenu-progress-message prev-pos 100)
375 (and index-var-alist
376 (push (cons "Variables" index-var-alist)
377 index-alist))
378 (and index-type-alist
379 (push (cons "Types" index-type-alist)
380 index-alist))
381 (and index-unknown-alist
382 (push (cons "Syntax-unknown" index-unknown-alist)
383 index-alist))
384 index-alist))
385 (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
387 ;; Regular expression to find C functions
388 (defvar imenu-example--function-name-regexp-c
389 (concat
390 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
391 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
392 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
393 "\\([*&]+[ \t]*\\)?" ; pointer
394 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
397 (defun imenu-example--create-c-index (&optional regexp)
398 (let ((index-alist '())
399 prev-pos char)
400 (goto-char (point-min))
401 (imenu-progress-message prev-pos 0)
402 ;; Search for the function
403 (save-match-data
404 (while (re-search-forward
405 (or regexp imenu-example--function-name-regexp-c)
406 nil t)
407 (imenu-progress-message prev-pos)
408 (backward-up-list 1)
409 (save-excursion
410 (goto-char (scan-sexps (point) 1))
411 (setq char (following-char)))
412 ;; Skip this function name if it is a prototype declaration.
413 (if (not (eq char ?\;))
414 (push (imenu-example--name-and-position) index-alist))))
415 (imenu-progress-message prev-pos 100)
416 (nreverse index-alist)))
417 (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
419 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
421 ;;; Internal variables
423 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
425 ;; The item to use in the index for rescanning the buffer.
426 (defconst imenu--rescan-item '("*Rescan*" . -99))
428 ;; The latest buffer index.
429 ;; Buffer local.
430 (defvar imenu--index-alist nil
431 "The buffer index alist computed for this buffer in Imenu.
433 Simple elements in the alist look like (INDEX-NAME . POSITION).
434 POSITION is the buffer position of the item; to go to the item
435 is simply to move point to that position.
437 Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
438 To \"go to\" a special element means applying FUNCTION
439 to INDEX-NAME, POSITION, and the ARGUMENTS.
441 A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
442 The function `imenu--subalist-p' tests an element and returns t
443 if it is a sub-alist.
445 There is one simple element with negative POSITION; selecting that
446 element recalculates the buffer's index alist.")
448 (make-variable-buffer-local 'imenu--index-alist)
450 (defvar imenu--last-menubar-index-alist nil
451 "The latest buffer index alist used to update the menu bar menu.")
453 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
455 ;; History list for 'jump-to-function-in-buffer'.
456 ;; Making this buffer local caused it not to work!
457 (defvar imenu--history-list nil)
459 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
461 ;;; Internal support functions
463 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
466 ;;; Sort function
467 ;;; Sorts the items depending on their index name.
468 ;;; An item looks like (NAME . POSITION).
470 (defun imenu--sort-by-name (item1 item2)
471 (string-lessp (car item1) (car item2)))
473 (defun imenu--sort-by-position (item1 item2)
474 (< (cdr item1) (cdr item2)))
476 (defun imenu--relative-position (&optional reverse)
477 ;; Support function to calculate relative position in buffer
478 ;; Beginning of buffer is 0 and end of buffer is 100
479 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
480 (let ((pos (point))
481 (total (buffer-size)))
482 (and reverse (setq pos (- total pos)))
483 (if (> total 50000)
484 ;; Avoid overflow from multiplying by 100!
485 (/ (1- pos) (max (/ total 100) 1))
486 (/ (* 100 (1- pos)) (max total 1)))))
488 ;; Split LIST into sublists of max length N.
489 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
491 ;; The returned list DOES NOT share structure with LIST.
492 (defun imenu--split (list n)
493 (let ((remain list)
494 (result '())
495 (sublist '())
496 (i 0))
497 (while remain
498 (push (pop remain) sublist)
499 (incf i)
500 (and (= i n)
501 ;; We have finished a sublist
502 (progn (push (nreverse sublist) result)
503 (setq i 0)
504 (setq sublist '()))))
505 ;; There might be a sublist (if the length of LIST mod n is != 0)
506 ;; that has to be added to the result list.
507 (and sublist
508 (push (nreverse sublist) result))
509 (nreverse result)))
511 ;;; Split the alist MENULIST into a nested alist, if it is long enough.
512 ;;; In any case, add TITLE to the front of the alist.
513 ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
514 ;;; beginning of the returned alist.
516 ;;; The returned alist DOES NOT share structure with MENULIST.
517 (defun imenu--split-menu (menulist title)
518 (let ((menulist (copy-sequence menulist))
519 keep-at-top tail)
520 (if (memq imenu--rescan-item menulist)
521 (setq keep-at-top (list imenu--rescan-item)
522 menulist (delq imenu--rescan-item menulist)))
523 (setq tail menulist)
524 (dolist (item tail)
525 (when (imenu--subalist-p item)
526 (push item keep-at-top)
527 (setq menulist (delq item menulist))))
528 (if imenu-sort-function
529 (setq menulist (sort menulist imenu-sort-function)))
530 (if (> (length menulist) imenu-max-items)
531 (setq menulist
532 (mapcar
533 (lambda (menu)
534 (cons (format "From: %s" (caar menu)) menu))
535 (imenu--split menulist imenu-max-items))))
536 (cons title
537 (nconc (nreverse keep-at-top) menulist))))
539 ;;; Split up each long alist that are nested within ALIST
540 ;;; into nested alists.
542 ;;; Return a split and sorted copy of ALIST. The returned alist DOES
543 ;;; NOT share structure with ALIST.
544 (defun imenu--split-submenus (alist)
545 (mapcar (function
546 (lambda (elt)
547 (if (and (consp elt)
548 (stringp (car elt))
549 (listp (cdr elt)))
550 (imenu--split-menu (cdr elt) (car elt))
551 elt)))
552 alist))
554 ;;; Truncate all strings in MENULIST to imenu-max-item-length
555 (defun imenu--truncate-items (menulist)
556 (mapcar (function
557 (lambda (item)
558 (cond
559 ((consp (cdr item))
560 (imenu--truncate-items (cdr item)))
561 ;; truncate if necessary
562 ((and (numberp imenu-max-item-length)
563 (> (length (car item)) imenu-max-item-length))
564 (setcar item (substring (car item) 0 imenu-max-item-length))))))
565 menulist))
568 (defun imenu--make-index-alist (&optional noerror)
569 "Create an index alist for the definitions in the current buffer.
570 This works by using the hook function `imenu-create-index-function'.
571 Report an error if the list is empty unless NOERROR is supplied and
572 non-nil.
574 See `imenu--index-alist' for the format of the index alist."
575 (or (and imenu--index-alist
576 (or (not imenu-auto-rescan)
577 (and imenu-auto-rescan
578 (> (buffer-size) imenu-auto-rescan-maxout))))
579 ;; Get the index; truncate if necessary
580 (progn
581 (setq imenu--index-alist
582 (save-excursion
583 (save-restriction
584 (widen)
585 (funcall imenu-create-index-function))))
586 (imenu--truncate-items imenu--index-alist)))
587 (or imenu--index-alist noerror
588 (error "No items suitable for an index found in this buffer"))
589 (or imenu--index-alist
590 (setq imenu--index-alist (list nil)))
591 ;; Add a rescan option to the index.
592 (cons imenu--rescan-item imenu--index-alist))
594 ;;; Find all markers in alist and makes
595 ;;; them point nowhere.
596 ;;; The top-level call uses nil as the argument;
597 ;;; non-nil arguments are in recursivecalls.
598 (defvar imenu--cleanup-seen)
600 (defun imenu--cleanup (&optional alist)
601 ;; If alist is provided use that list.
602 ;; If not, empty the table of lists already seen
603 ;; and use imenu--index-alist.
604 (if alist
605 (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
606 (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
608 (and alist
609 (mapc
610 (lambda (item)
611 (cond
612 ((markerp (cdr item))
613 (set-marker (cdr item) nil))
614 ;; Don't process one alist twice.
615 ((memq (cdr item) imenu--cleanup-seen))
616 ((imenu--subalist-p item)
617 (imenu--cleanup (cdr item)))))
618 alist)
621 (defun imenu--create-keymap (title alist &optional cmd)
622 (list* 'keymap title
623 (mapcar
624 (lambda (item)
625 (list* (car item) (car item)
626 (cond
627 ((imenu--subalist-p item)
628 (imenu--create-keymap (car item) (cdr item) cmd))
630 `(lambda () (interactive)
631 ,(if cmd `(,cmd ',item) (list 'quote item)))))))
632 alist)))
634 (defun imenu--in-alist (str alist)
635 "Check whether the string STR is contained in multi-level ALIST."
636 (let (elt head tail res)
637 (setq res nil)
638 (while alist
639 (setq elt (car alist)
640 tail (cdr elt)
641 alist (cdr alist)
642 head (car elt))
643 ;; A nested ALIST element looks like
644 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
645 ;; while a bottom-level element looks like
646 ;; (INDEX-NAME . INDEX-POSITION)
647 ;; We are only interested in the bottom-level elements, so we need to
648 ;; recurse if TAIL is a list.
649 (cond ((listp tail)
650 (if (setq res (imenu--in-alist str tail))
651 (setq alist nil)))
652 ((if imenu-name-lookup-function
653 (funcall imenu-name-lookup-function str head)
654 (string= str head))
655 (setq alist nil res elt))))
656 res))
658 (defvar imenu-syntax-alist nil
659 "Alist of syntax table modifiers to use while in `imenu--generic-function'.
661 The car of the assocs may be either a character or a string and the
662 cdr is a syntax description appropriate for `modify-syntax-entry'. For
663 a string, all the characters in the string get the specified syntax.
665 This is typically used to give word syntax to characters which
666 normally have symbol syntax to simplify `imenu-expression'
667 and speed-up matching.")
668 ;;;###autoload
669 (make-variable-buffer-local 'imenu-syntax-alist)
671 (defun imenu-default-create-index-function ()
672 "Default function to create an index alist of the current buffer.
674 The most general method is to move point to end of buffer, then repeatedly call
675 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
676 All the results returned by the latter are gathered into an index alist.
677 This method is used if those two variables are non-nil.
679 The alternate method, which is the one most often used, is to call
680 `imenu--generic-function' with `imenu-generic-expression' as argument."
681 ;; These should really be done by setting imenu-create-index-function
682 ;; in these major modes. But save that change for later.
683 (cond ((and imenu-prev-index-position-function
684 imenu-extract-index-name-function)
685 (let ((index-alist '())
686 prev-pos name)
687 (goto-char (point-max))
688 (imenu-progress-message prev-pos 0 t)
689 ;; Search for the function
690 (while (funcall imenu-prev-index-position-function)
691 (imenu-progress-message prev-pos nil t)
692 (save-excursion
693 (setq name (funcall imenu-extract-index-name-function)))
694 (and (stringp name)
695 ;; [ydi] updated for imenu-use-markers
696 (push (cons name (if imenu-use-markers (point-marker) (point)))
697 index-alist)))
698 (imenu-progress-message prev-pos 100 t)
699 index-alist))
700 ;; Use generic expression if possible.
701 ((and imenu-generic-expression)
702 (imenu--generic-function imenu-generic-expression))
704 (error "This buffer cannot use `imenu-default-create-index-function'"))))
707 ;;; Generic index gathering function.
710 (defvar imenu-case-fold-search t
711 "Defines whether `imenu--generic-function' should fold case when matching.
713 This variable should be set (only) by initialization code
714 for modes which use `imenu--generic-function'. If it is not set, but
715 `font-lock-defaults' is set, then font-lock's setting is used.")
716 ;;;###autoload
717 (make-variable-buffer-local 'imenu-case-fold-search)
719 ;; This function can be called with quitting disabled,
720 ;; so it needs to be careful never to loop!
721 (defun imenu--generic-function (patterns)
722 "Return an index alist of the current buffer based on PATTERNS.
724 PATTERNS is an alist with elements that look like this:
725 (MENU-TITLE REGEXP INDEX)
726 or like this:
727 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
728 with zero or more ARGUMENTS. The former format creates a simple
729 element in the index alist when it matches; the latter creates a
730 special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
731 ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
733 MENU-TITLE is a string used as the title for the submenu or nil
734 if the entries are not nested.
736 REGEXP is a regexp that should match a construct in the buffer
737 that is to be displayed in the menu; i.e., function or variable
738 definitions, etc. It contains a substring which is the name to
739 appear in the menu. See the info section on Regexps for more
740 information. REGEXP may also be a function, called without
741 arguments. It is expected to search backwards. It shall return
742 true and set `match-data' if it finds another element.
744 INDEX points to the substring in REGEXP that contains the
745 name (of the function, variable or type) that is to appear in the
746 menu.
748 The variable `imenu-case-fold-search' determines whether or not the
749 regexp matches are case sensitive, and `imenu-syntax-alist' can be
750 used to alter the syntax table for the search.
752 See `lisp-imenu-generic-expression' for an example of PATTERNS.
754 Returns an index of the current buffer as an alist. The elements in
755 the alist look like:
756 (INDEX-NAME . INDEX-POSITION)
757 or like:
758 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
759 They may also be nested index alists like:
760 (INDEX-NAME . INDEX-ALIST)
761 depending on PATTERNS."
763 (let ((index-alist (list 'dummy))
764 prev-pos
765 (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
766 (not (local-variable-p 'font-lock-defaults)))
767 imenu-case-fold-search
768 (nth 2 font-lock-defaults)))
769 (old-table (syntax-table))
770 (table (copy-syntax-table (syntax-table)))
771 (slist imenu-syntax-alist))
772 ;; Modify the syntax table used while matching regexps.
773 (dolist (syn slist)
774 ;; The character(s) to modify may be a single char or a string.
775 (if (numberp (car syn))
776 (modify-syntax-entry (car syn) (cdr syn) table)
777 (mapc (lambda (c)
778 (modify-syntax-entry c (cdr syn) table))
779 (car syn))))
780 (goto-char (point-max))
781 (imenu-progress-message prev-pos 0 t)
782 (unwind-protect ; for syntax table
783 (save-match-data
784 (set-syntax-table table)
786 ;; map over the elements of imenu-generic-expression
787 ;; (typically functions, variables ...)
788 (dolist (pat patterns)
789 (let ((menu-title (car pat))
790 (regexp (nth 1 pat))
791 (index (nth 2 pat))
792 (function (nth 3 pat))
793 (rest (nthcdr 4 pat))
794 start beg)
795 ;; Go backwards for convenience of adding items in order.
796 (goto-char (point-max))
797 (while (and (if (functionp regexp)
798 (funcall regexp)
799 (re-search-backward regexp nil t))
800 ;; Exit the loop if we get an empty match,
801 ;; because it means a bad regexp was specified.
802 (not (= (match-beginning 0) (match-end 0))))
803 (setq start (point))
804 ;; Record the start of the line in which the match starts.
805 ;; That's the official position of this definition.
806 (goto-char (match-beginning index))
807 (beginning-of-line)
808 (setq beg (point))
809 (imenu-progress-message prev-pos nil t)
810 ;; Add this sort of submenu only when we've found an
811 ;; item for it, avoiding empty, duff menus.
812 (unless (assoc menu-title index-alist)
813 (push (list menu-title) index-alist))
814 (if imenu-use-markers
815 (setq beg (copy-marker beg)))
816 (let ((item
817 (if function
818 (nconc (list (match-string-no-properties index)
819 beg function)
820 rest)
821 (cons (match-string-no-properties index)
822 beg)))
823 ;; This is the desired submenu,
824 ;; starting with its title (or nil).
825 (menu (assoc menu-title index-alist)))
826 ;; Insert the item unless it is already present.
827 (unless (member item (cdr menu))
828 (setcdr menu
829 (cons item (cdr menu)))))
830 ;; Go to the start of the match, to make sure we
831 ;; keep making progress backwards.
832 (goto-char start))))
833 (set-syntax-table old-table)))
834 (imenu-progress-message prev-pos 100 t)
835 ;; Sort each submenu by position.
836 ;; This is in case one submenu gets items from two different regexps.
837 (dolist (item index-alist)
838 (when (listp item)
839 (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
840 (let ((main-element (assq nil index-alist)))
841 (nconc (delq main-element (delq 'dummy index-alist))
842 (cdr main-element)))))
844 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
846 ;;; The main functions for this package!
848 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
850 ;; See also info-lookup-find-item
851 (defun imenu-find-default (guess completions)
852 "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
853 (catch 'found
854 (let ((case-fold-search t))
855 (if (assoc guess completions) guess
856 (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
857 (concat "\\`" (regexp-quote guess))
858 (concat (regexp-quote guess) "\\'")
859 (regexp-quote guess)))
860 (dolist (x completions)
861 (if (string-match re (car x)) (throw 'found (car x)))))))))
863 (defun imenu--completion-buffer (index-alist &optional prompt)
864 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
866 Return one of the entries in index-alist or nil."
867 ;; Create a list for this buffer only when needed.
868 (let ((name (thing-at-point 'symbol))
869 choice
870 (prepared-index-alist
871 (if (not imenu-space-replacement) index-alist
872 (mapcar
873 (lambda (item)
874 (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
875 (car item))
876 (cdr item)))
877 index-alist))))
878 (when (stringp name)
879 (setq name (or (imenu-find-default name prepared-index-alist) name)))
880 (cond (prompt)
881 ((and name (imenu--in-alist name prepared-index-alist))
882 (setq prompt (format "Index item (default %s): " name)))
883 (t (setq prompt "Index item: ")))
884 (let ((minibuffer-setup-hook minibuffer-setup-hook))
885 ;; Display the completion buffer.
886 (if (not imenu-eager-completion-buffer)
887 (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
888 (setq name (completing-read prompt
889 prepared-index-alist
890 nil t nil 'imenu--history-list name)))
892 (when (stringp name)
893 (setq choice (assoc name prepared-index-alist))
894 (if (imenu--subalist-p choice)
895 (imenu--completion-buffer (cdr choice) prompt)
896 choice))))
898 (defun imenu--mouse-menu (index-alist event &optional title)
899 "Let the user select from a buffer index from a mouse menu.
901 INDEX-ALIST is the buffer index and EVENT is a mouse event.
903 Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
904 (setq index-alist (imenu--split-submenus index-alist))
905 (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
906 (map (imenu--create-keymap (car menu)
907 (cdr (if (< 1 (length (cdr menu)))
908 menu
909 (car (cdr menu)))))))
910 (popup-menu map event)))
912 (defun imenu-choose-buffer-index (&optional prompt alist)
913 "Let the user select from a buffer index and return the chosen index.
915 If the user originally activated this function with the mouse, a mouse
916 menu is used. Otherwise a completion buffer is used and the user is
917 prompted with PROMPT.
919 If you call this function with index alist ALIST, then it lets the user
920 select from ALIST.
922 With no index alist ALIST, it calls `imenu--make-index-alist' to
923 create the index alist.
925 If `imenu-use-popup-menu' is nil, then the completion buffer
926 is always used, no matter if the mouse was used or not.
928 The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
929 (let (index-alist
930 (mouse-triggered (listp last-nonmenu-event))
931 (result t))
932 ;; If selected by mouse, see to that the window where the mouse is
933 ;; really is selected.
934 (and mouse-triggered
935 (not (equal last-nonmenu-event '(menu-bar)))
936 (let ((window (posn-window (event-start last-nonmenu-event))))
937 (or (framep window) (null window) (select-window window))))
938 ;; Create a list for this buffer only when needed.
939 (while (eq result t)
940 (setq index-alist (if alist alist (imenu--make-index-alist)))
941 (setq result
942 (if (and imenu-use-popup-menu
943 (or (eq imenu-use-popup-menu t) mouse-triggered))
944 (imenu--mouse-menu index-alist last-nonmenu-event)
945 (imenu--completion-buffer index-alist prompt)))
946 (and (equal result imenu--rescan-item)
947 (imenu--cleanup)
948 (setq result t imenu--index-alist nil)))
949 result))
951 ;;;###autoload
952 (defun imenu-add-to-menubar (name)
953 "Add an `imenu' entry to the menu bar for the current buffer.
954 NAME is a string used to name the menu bar item.
955 See the command `imenu' for more information."
956 (interactive "sImenu menu item name: ")
957 (if (or (and imenu-prev-index-position-function
958 imenu-extract-index-name-function)
959 imenu-generic-expression
960 (not (eq imenu-create-index-function
961 'imenu-default-create-index-function)))
962 (let ((newmap (make-sparse-keymap)))
963 (set-keymap-parent newmap (current-local-map))
964 (setq imenu--last-menubar-index-alist nil)
965 (define-key newmap [menu-bar index]
966 `(menu-item ,name ,(make-sparse-keymap "Imenu")))
967 (use-local-map newmap)
968 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
969 (error "The mode `%s' does not support Imenu"
970 (format-mode-line mode-name))))
972 ;;;###autoload
973 (defun imenu-add-menubar-index ()
974 "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
976 A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
977 (interactive)
978 (imenu-add-to-menubar "Index"))
980 (defvar imenu-buffer-menubar nil)
982 (defvar imenu-menubar-modified-tick 0
983 "The value of (buffer-chars-modified-tick) as of the last call
984 to `imenu-update-menubar'.")
985 (make-variable-buffer-local 'imenu-menubar-modified-tick)
987 (defun imenu-update-menubar ()
988 (when (and (current-local-map)
989 (keymapp (lookup-key (current-local-map) [menu-bar index]))
990 (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
991 (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
992 (let ((index-alist (imenu--make-index-alist t)))
993 ;; Don't bother updating if the index-alist has not changed
994 ;; since the last time we did it.
995 (unless (equal index-alist imenu--last-menubar-index-alist)
996 (let (menu menu1 old)
997 (setq imenu--last-menubar-index-alist index-alist)
998 (setq index-alist (imenu--split-submenus index-alist))
999 (setq menu (imenu--split-menu index-alist
1000 (buffer-name)))
1001 (setq menu1 (imenu--create-keymap (car menu)
1002 (cdr (if (< 1 (length (cdr menu)))
1003 menu
1004 (car (cdr menu))))
1005 'imenu--menubar-select))
1006 (setq old (lookup-key (current-local-map) [menu-bar index]))
1007 (setcdr old (cdr menu1)))))))
1009 (defun imenu--menubar-select (item)
1010 "Use Imenu to select the function or variable named in this menu ITEM."
1011 (if (equal item imenu--rescan-item)
1012 (progn
1013 (imenu--cleanup)
1014 ;; Make sure imenu-update-menubar redoes everything.
1015 (setq imenu-menubar-modified-tick -1)
1016 (setq imenu--index-alist nil)
1017 (setq imenu--last-menubar-index-alist nil)
1018 (imenu-update-menubar)
1020 (imenu item)
1021 nil))
1023 (defun imenu-default-goto-function (name position &optional rest)
1024 "Move to the given position.
1026 NAME is ignored. POSITION is where to move. REST is also ignored.
1027 The ignored args just make this function have the same interface as a
1028 function placed in a special index-item."
1029 (if (or (< position (point-min))
1030 (> position (point-max)))
1031 ;; widen if outside narrowing
1032 (widen))
1033 (goto-char position))
1035 ;;;###autoload
1036 (defun imenu (index-item)
1037 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
1038 INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
1039 for more information."
1040 (interactive (list (imenu-choose-buffer-index)))
1041 ;; Convert a string to an alist element.
1042 (if (stringp index-item)
1043 (setq index-item (assoc index-item (imenu--make-index-alist))))
1044 (when index-item
1045 (push-mark)
1046 (let* ((is-special-item (listp (cdr index-item)))
1047 (function
1048 (if is-special-item
1049 (nth 2 index-item) imenu-default-goto-function))
1050 (position (if is-special-item
1051 (cadr index-item) (cdr index-item)))
1052 (rest (if is-special-item (cddr index-item))))
1053 (apply function (car index-item) position rest))
1054 (run-hooks 'imenu-after-jump-hook)))
1056 (dolist (mess
1057 '("^No items suitable for an index found in this buffer$"
1058 "^This buffer cannot use `imenu-default-create-index-function'$"
1059 "^The mode `.*' does not support Imenu$"))
1060 (add-to-list 'debug-ignored-errors mess))
1062 (provide 'imenu)
1064 ;; arch-tag: 98a2f5f5-4b91-4704-b18c-3aacf77d77a7
1065 ;;; imenu.el ends here