(vip-add-hook,vip-remove-hook): new functions.
[emacs.git] / lisp / imenu.el
blob6a652f22789dee6050250db94e64b2d46a0784a8
1 ;;; imenu.el --- Framework for mode-specific buffer indexes.
3 ;; Copyright (C) 1994, 1995 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
9 ;;
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program; if not, write to the Free Software
22 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 ;;; Commentary:
26 ;; Purpose of this package:
27 ;; To present a framework for mode-specific buffer indexes.
28 ;; A buffer index is an alist of names and buffer positions.
29 ;; For instance all functions in a C-file and their positions.
31 ;; How it works:
33 ;; A mode-specific function is called to generate the index. It is
34 ;; then presented to the user, who can choose from this index.
36 ;; The package comes with a set of example functions for how to
37 ;; utilize this package.
39 ;; There are *examples* for index gathering functions/regular
40 ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
41 ;; customize for other modes. A function for jumping to the chosen
42 ;; index position is also supplied.
44 ;;; Thanks goes to
45 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
46 ;; [dean] - Dean Andrews ada@unison.com
47 ;; [alon] - Alon Albert al@mercury.co.il
48 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
49 ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
50 ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
51 ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
52 ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
53 ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
55 ;;; Code
56 (eval-when-compile (require 'cl))
58 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
59 ;;;
60 ;;; Customizable variables
61 ;;;
62 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
63 (defvar imenu-use-keymap-menu nil
64 "*Non-nil means use a keymap when making the mouse menu.")
66 (defvar imenu-auto-rescan nil
67 "*Non-nil means Imenu should always rescan the buffers.")
69 (defvar imenu-auto-rescan-maxout 60000
70 "* auto-rescan is disabled in buffers larger than this.
71 This variable is buffer-local.")
73 (defvar imenu-always-use-completion-buffer-p nil
74 "*Set this to non-nil for displaying the index in a completion buffer.
76 Non-nil means always display the index in a completion buffer.
77 Nil means display the index as a mouse menu when the mouse was
78 used to invoke `imenu'.
79 `never' means never automatically display a listing of any kind.")
81 (defvar imenu-sort-function nil
82 "*The function to use for sorting the index mouse-menu.
84 Affects only the mouse index menu.
86 Set this to nil if you don't want any sorting (faster).
87 The items in the menu are then presented in the order they were found
88 in the buffer.
90 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
92 The function should take two arguments and return T if the first
93 element should come before the second. The arguments are cons cells;
94 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example.")
96 (defvar imenu-max-items 25
97 "*Maximum number of elements in an index mouse-menu.")
99 (defvar imenu-scanning-message "Scanning buffer for index (%3d%%)"
100 "*Progress message during the index scanning of the buffer.
101 If non-nil, user gets a message during the scanning of the buffer
103 Relevant only if the mode-specific function that creates the buffer
104 index use `imenu-progress-message'.")
106 (defvar imenu-space-replacement "^"
107 "*The replacement string for spaces in index names.
108 Used when presenting the index in a completion-buffer to make the
109 names work as tokens.")
111 (defvar imenu-level-separator ":"
112 "*The separator between index names of different levels.
113 Used for making mouse-menu titles and for flattening nested indexes
114 with name concatenation.")
116 (defvar imenu-submenu-name-format "%s..."
117 "*The format for making a submenu name.")
119 ;;;###autoload
120 (defvar imenu-generic-expression nil
121 "The regex pattern to use for creating a buffer index.
123 If non-nil this pattern is passed to `imenu-create-index-with-pattern'
124 to create a buffer index.
126 It is an alist with elements that look like this: (MENU-TITLE
127 REGEXP INDEX).
129 MENU-TITLE is a string used as the title for the submenu or nil if the
130 entries are not nested.
132 REGEXP is a regexp that should match a construct in the buffer that is
133 to be displayed in the menu; i.e., function or variable definitions,
134 etc. It contains a substring which is the name to appear in the
135 menu. See the info section on Regexps for more information.
137 INDEX points to the substring in REGEXP that contains the name (of the
138 function, variable or type) that is to appear in the menu.
140 For emacs-lisp-mode for example PATTERN would look like:
142 '((nil \"^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\s-+\\([-A-Za-z0-9+]+\\)\" 2)
143 (\"*Vars*\" \"^\\s-*(def\\(var\\|const\\)\\s-+\\([-A-Za-z0-9+]+\\)\" 2)
144 (\"*Types*\" \"^\\s-*(def\\(type\\|struct\\|class\\|ine-condition\\)\\s-+\\([-A-Za-z0-9+]+\\)\" 2))
146 The variable is buffer-local.")
148 (make-variable-buffer-local 'imenu-generic-expression)
150 ;;;; Hooks
152 (defvar imenu-create-index-function 'imenu-default-create-index-function
153 "The function to use for creating a buffer index.
155 It should be a function that takes no arguments and returns an index
156 of the current buffer as an alist. The elements in the alist look
157 like: (INDEX-NAME . INDEX-POSITION). You may also nest index list like
158 \(INDEX-NAME . INDEX-ALIST).
160 This function is called within a `save-excursion'.
162 The variable is buffer-local.")
163 (make-variable-buffer-local 'imenu-create-index-function)
165 (defvar imenu-prev-index-position-function 'beginning-of-defun
166 "Function for finding the next index position.
168 If `imenu-create-index-function' is set to
169 `imenu-default-create-index-function', then you must set this variable
170 to a function that will find the next index, looking backwards in the
171 file.
173 The function should leave point at the place to be connected to the
174 index and it should return nil when it doesn't find another index.")
175 (make-variable-buffer-local 'imenu-prev-index-position-function)
177 (defvar imenu-extract-index-name-function nil
178 "Function for extracting the index name.
180 This function is called after the function pointed out by
181 `imenu-prev-index-position-function'.")
182 (make-variable-buffer-local 'imenu-extract-index-name-function)
185 ;;; Macro to display a progress message.
186 ;;; RELPOS is the relative position to display.
187 ;;; If RELPOS is nil, then the relative position in the buffer
188 ;;; is calculated.
189 ;;; PREVPOS is the variable in which we store the last position displayed.
190 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
191 (` (and
192 imenu-scanning-message
193 (let ((pos (, (if relpos
194 relpos
195 (` (imenu--relative-position (, reverse)))))))
196 (if (, (if relpos t
197 (` (> pos (+ 5 (, prevpos))))))
198 (progn
199 (message imenu-scanning-message pos)
200 (setq (, prevpos) pos)))))))
203 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
204 ;;;;
205 ;;;; Some examples of functions utilizing the framework of this
206 ;;;; package.
207 ;;;;
208 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
210 ;; Return the current/previous sexp and the location of the sexp (it's
211 ;; beginning) without moving the point.
212 (defun imenu-example--name-and-position ()
213 (save-excursion
214 (forward-sexp -1)
215 (let ((beg (point))
216 (end (progn (forward-sexp) (point)))
217 (marker (make-marker)))
218 (set-marker marker beg)
219 (cons (buffer-substring beg end)
220 marker))))
223 ;;; Lisp
224 ;;;
226 (defun imenu-example--lisp-extract-index-name ()
227 ;; Example of a candidate for `imenu-extract-index-name-function'.
228 ;; This will generate a flat index of definitions in a lisp file.
229 (save-match-data
230 (and (looking-at "(def")
231 (condition-case nil
232 (progn
233 (down-list 1)
234 (forward-sexp 2)
235 (let ((beg (point))
236 (end (progn (forward-sexp -1) (point))))
237 (buffer-substring beg end)))
238 (error nil)))))
240 (defun imenu-example--create-lisp-index ()
241 ;; Example of a candidate for `imenu-create-index-function'.
242 ;; It will generate a nested index of definitions.
243 (let ((index-alist '())
244 (index-var-alist '())
245 (index-type-alist '())
246 (index-unknown-alist '())
247 prev-pos)
248 (goto-char (point-max))
249 (imenu-progress-message prev-pos 0)
250 ;; Search for the function
251 (while (beginning-of-defun)
252 (imenu-progress-message prev-pos nil t)
253 (save-match-data
254 (and (looking-at "(def")
255 (save-excursion
256 (down-list 1)
257 (cond
258 ((looking-at "def\\(var\\|const\\)")
259 (forward-sexp 2)
260 (push (imenu-example--name-and-position)
261 index-var-alist))
262 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
263 (forward-sexp 2)
264 (push (imenu-example--name-and-position)
265 index-alist))
266 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
267 (forward-sexp 2)
268 (if (= (char-after (1- (point))) ?\))
269 (progn
270 (forward-sexp -1)
271 (down-list 1)
272 (forward-sexp 1)))
273 (push (imenu-example--name-and-position)
274 index-type-alist))
276 (forward-sexp 2)
277 (push (imenu-example--name-and-position)
278 index-unknown-alist)))))))
279 (imenu-progress-message prev-pos 100)
280 (and index-var-alist
281 (push (cons (imenu-create-submenu-name "Variables") index-var-alist)
282 index-alist))
283 (and index-type-alist
284 (push (cons (imenu-create-submenu-name "Types") index-type-alist)
285 index-alist))
286 (and index-unknown-alist
287 (push (cons (imenu-create-submenu-name "Syntax-unknown") index-unknown-alist)
288 index-alist))
289 index-alist))
291 (defvar imenu-generic-lisp-expression
293 (nil
294 "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\s-+\\([-A-Za-z0-9+]+\\)" 2)
295 ("Variables"
296 "^\\s-*(def\\(var\\|const\\)\\s-+\\([-A-Za-z0-9+]+\\)" 2)
297 ("Types"
298 "^\\s-*(def\\(type\\|struct\\|class\\|ine-condition\\)\\s-+\\([-A-Za-z0-9+]+\\)"
301 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
304 ;;; C++
306 ;; Example of an imenu-generic-expression
308 (defvar imenu-generic-c++-expression
310 ((nil
312 (concat
313 "^" ; beginning of line is required
314 "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
315 "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; type specs; there can be no
316 "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; more than 3 tokens, right?
318 "\\(" ; last type spec including */&
319 "[a-zA-Z0-9_:]+"
320 "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)" ; either pointer/ref sign or whitespace
321 "\\)?" ; if there is a last type spec
322 "\\(" ; name; take that into the imenu entry
323 "[a-zA-Z0-9_:~]+" ; member function, ctor or dtor...
324 ; (may not contain * because then
325 ; "a::operator char*" would become "char*"!)
326 "\\|"
327 "\\([a-zA-Z0-9_:~]*::\\)?operator"
328 "[^a-zA-Z1-9_][^(]*" ; ...or operator
329 " \\)"
330 "[ \t]*([^)]*)[ \t\n]*[^ ;]" ; require something other than a ; after
331 ; the (...) to avoid prototypes. Can't
332 ; catch cases with () inside the parentheses
333 ; surrounding the parameters
334 ; (like "int foo(int a=bar()) {...}"
336 )) 6)
337 ("Class"
338 (, (concat
339 "^" ; beginning of line is required
340 "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
341 "class[ \t]+"
342 "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
343 "[ \t]*[:{]"
344 )) 2)
345 ;; Example of generic expression for finding prototypes, structs, unions, enums.
346 ;; Uncomment if You want to find these too. It will be at bit slower gathering
347 ;; the indexes.
348 ; ("Prototypes"
349 ; (,
350 ; (concat
351 ; "^" ; beginning of line is required
352 ; "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
353 ; "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; type specs; there can be no
354 ; "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; more than 3 tokens, right?
356 ; "\\(" ; last type spec including */&
357 ; "[a-zA-Z0-9_:]+"
358 ; "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)" ; either pointer/ref sign or whitespace
359 ; "\\)?" ; if there is a last type spec
360 ; "\\(" ; name; take that into the imenu entry
361 ; "[a-zA-Z0-9_:~]+" ; member function, ctor or dtor...
362 ; ; (may not contain * because then
363 ; ; "a::operator char*" would become "char*"!)
364 ; "\\|"
365 ; "\\([a-zA-Z0-9_:~]*::\\)?operator"
366 ; "[^a-zA-Z1-9_][^(]*" ; ...or operator
367 ; " \\)"
368 ; "[ \t]*([^)]*)[ \t\n]*;" ; require ';' after
369 ; ; the (...) Can't
370 ; ; catch cases with () inside the parentheses
371 ; ; surrounding the parameters
372 ; ; (like "int foo(int a=bar());"
373 ; )) 6)
374 ; ("Struct"
375 ; (, (concat
376 ; "^" ; beginning of line is required
377 ; "\\(static[ \t]+\\)?" ; there may be static or const.
378 ; "\\(const[ \t]+\\)?"
379 ; "struct[ \t]+"
380 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
381 ; "[ \t]*[{]"
382 ; )) 3)
383 ; ("Enum"
384 ; (, (concat
385 ; "^" ; beginning of line is required
386 ; "\\(static[ \t]+\\)?" ; there may be static or const.
387 ; "\\(const[ \t]+\\)?"
388 ; "enum[ \t]+"
389 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
390 ; "[ \t]*[{]"
391 ; )) 3)
392 ; ("Union"
393 ; (, (concat
394 ; "^" ; beginning of line is required
395 ; "\\(static[ \t]+\\)?" ; there may be static or const.
396 ; "\\(const[ \t]+\\)?"
397 ; "union[ \t]+"
398 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
399 ; "[ \t]*[{]"
400 ; )) 3)
402 "Imenu generic expression for C++ mode. See `imenu-generic-expression'.")
405 ;;; C
408 (defvar imenu-generic-c-expression
409 ;; Use the C++ expression above.
410 imenu-generic-c++-expression
411 "Imenu generic expression for C mode. See `imenu-generic-expression'.")
413 ;; Regular expression to find C functions
414 (defvar imenu-example--function-name-regexp-c
415 (concat
416 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
417 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
418 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
419 "\\([*&]+[ \t]*\\)?" ; pointer
420 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
423 (defun imenu-example--create-c-index (&optional regexp)
424 (let ((index-alist '())
425 prev-pos char)
426 (goto-char (point-min))
427 (imenu-progress-message prev-pos 0)
428 ;; Search for the function
429 (save-match-data
430 (while (re-search-forward
431 (or regexp imenu-example--function-name-regexp-c)
432 nil t)
433 (imenu-progress-message prev-pos)
434 (backward-up-list 1)
435 (save-excursion
436 (goto-char (scan-sexps (point) 1))
437 (setq char (following-char)))
438 ;; Skip this function name if it is a prototype declaration.
439 (if (not (eq char ?\;))
440 (push (imenu-example--name-and-position) index-alist))))
441 (imenu-progress-message prev-pos 100)
442 (nreverse index-alist)))
446 ;; Ada
448 ;; Written by Christian Egli <Christian.Egli@hcsd.hac.com>
450 (defvar imenu-generic-ada-expression
451 '((nil "^\\s-*\\(procedure\\|function\\)\\s-+\\([A-Za-z0-9_]+\\)" 2)
452 ("Type Defs" "^\\s-*\\(sub\\)?type\\s-+\\([A-Za-z0-9_]+\\)" 2))
454 "Imenu generic expression for Ada mode. See `imenu-generic-expression'.")
456 ;;;
457 ;;; TexInfo
458 ;;;
459 ;; Written by Wolfgang Bangerth <zcg51122@rpool1.rus.uni-stuttgart.de>
462 (defvar imenu-generic-texinfo-expression
463 '((nil "^@node[ \t]+\\([^,\n]*\\)" 1)
464 ("Chapters" "^@chapter[ \t]+\\(.*\\)$" 1))
466 "Imenu generic expression for TexInfo mode. See `imenu-generic-expression'.
468 To overide this example, Either set 'imenu-generic-expression
469 or 'imenu-create-index-function")
471 ;;;
472 ;;; LaTex
473 ;;;
474 ;; Written by Wolfgang Bangerth <zcg51122@rpool1.rus.uni-stuttgart.de>
477 (defvar imenu-generic-latex-expression
479 ("Part" "\\\\part{\\([^}]*\\)}" 1)
480 ("Chapter" "\\\\chapter{\\([^}]*\\)}" 1)
481 ("Section" "\\\\[a-zA-Z]*section{\\([^}]*\\)}" 1)
482 ;; i put numbers like 3.15 before my
483 ;; \begin{equation}'s which tell me
484 ;; the number the equation will get when
485 ;; being printed.
486 ("Equations" "%[ \t]*\\([0-9]+\\.[0-9]+\\)[,;]?[ \t]?" 1))
488 "Imenu generic expression for LaTex mode. See `imenu-generic-expression'.")
490 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
492 ;;; Internal variables
494 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
496 ;; The item to use in the index for rescanning the buffer.
497 (defconst imenu--rescan-item '("*Rescan*" . -99))
499 ;; The latest buffer index.
500 ;; Buffer local.
501 (defvar imenu--index-alist nil)
502 (make-variable-buffer-local 'imenu--index-alist)
504 ;; History list for 'jump-to-function-in-buffer'.
505 ;; Making this buffer local caused it not to work!
506 (defvar imenu--history-list nil)
508 (defvar imenu--scanning-method-alist
509 '((emacs-lisp-mode imenu-generic-lisp-expression)
510 (lisp-mode imenu-example--create-lisp-index)
511 (c++-mode imenu-generic-c++-expression)
512 (c-mode imenu-generic-c-expression)
513 (latex-mode imenu-generic-latex-expression)
514 (texinfo-mode imenu-generic-texinfo-expression)
515 (ada-mode imenu-generic-ada-expression))
517 "Alist of major mode and imenu scanning methods.
519 Each item should be a list of the form (MAJOR-MODE
520 IMENU-SCANNING-METHOD), where both MAJOR-MODE and IMENU-SCANNING-METHOD
521 are symbols. If IMENU-SCANNING-METHOD is a function then it is called
522 to create an index. If it is a \"pattern\" (see `imenu-generic-expression')
523 it is passed to `imenu--generic-function' to create an index.")
525 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
527 ;;; Internal support functions
529 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
532 ;;; Sort function
533 ;;; Sorts the items depending on their index name.
534 ;;; An item look like (NAME . POSITION).
536 (defun imenu--sort-by-name (item1 item2)
537 (string-lessp (car item1) (car item2)))
539 (defun imenu--relative-position (&optional reverse)
540 ;; Support function to calculate relative position in buffer
541 ;; Beginning of buffer is 0 and end of buffer is 100
542 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
543 (let ((pos (point))
544 (total (buffer-size)))
545 (and reverse (setq pos (- total pos)))
546 (if (> total 50000)
547 ;; Avoid overflow from multiplying by 100!
548 (/ (1- pos) (max (/ total 100) 1))
549 (/ (* 100 (1- pos)) (max total 1)))))
552 ;;; Function for suporting general looking submenu names.
553 ;;; Uses `imenu-submenu-name-format' for creating the name.
554 ;;; NAME is the base of the new submenu name.
556 (defun imenu-create-submenu-name (name)
557 (format imenu-submenu-name-format name))
559 ;; Split LIST into sublists of max length N.
560 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
561 (defun imenu--split (list n)
562 (let ((remain list)
563 (result '())
564 (sublist '())
565 (i 0))
566 (while remain
567 (push (pop remain) sublist)
568 (incf i)
569 (and (= i n)
570 ;; We have finished a sublist
571 (progn (push (nreverse sublist) result)
572 (setq i 0)
573 (setq sublist '()))))
574 ;; There might be a sublist (if the length of LIST mod n is != 0)
575 ;; that has to be added to the result list.
576 (and sublist
577 (push (nreverse sublist) result))
578 (nreverse result)))
581 ;;; Split a menu in to several menus.
583 (defun imenu--split-menu (menulist title)
584 (cons "Index menu"
585 (mapcar
586 (function
587 (lambda (menu)
588 (cons (format "(%s)" title) menu)))
589 (imenu--split menulist imenu-max-items))))
592 ;;; Find all items in this buffer that should be in the index.
593 ;;; Returns an alist on the form
594 ;;; ((NAME . POSITION) (NAME . POSITION) ...)
597 (defun imenu--make-index-alist ()
598 ;; Create a list for this buffer only when needed.
599 (or (and imenu--index-alist
600 (or (not imenu-auto-rescan)
601 (and imenu-auto-rescan
602 (> (buffer-size) imenu-auto-rescan-maxout))))
603 ;; Get the index
604 (setq imenu--index-alist
605 (save-excursion
606 (funcall imenu-create-index-function))))
607 (or imenu--index-alist
608 (error "No items suitable for an index found in this buffer"))
609 ;; Add a rescan option to the index.
610 (cons imenu--rescan-item imenu--index-alist))
612 ;;; Find all markers in alist and makes
613 ;;; them point nowhere.
615 (defun imenu--cleanup (&optional alist)
616 ;; Sets the markers in imenu--index-alist
617 ;; point nowhere.
618 ;; if alist is provided use that list.
619 (or alist
620 (setq alist imenu--index-alist))
621 (and alist
622 (mapcar
623 (function
624 (lambda (item)
625 (cond
626 ((markerp (cdr item))
627 (set-marker (cdr item) nil))
628 ((consp (cdr item))
629 (imenu--cleanup (cdr item))))))
630 alist)
633 (defun imenu--create-keymap-2 (alist counter)
634 (let ((map nil))
635 (mapcar
636 (function
637 (lambda (item)
638 (cond
639 ((listp (cdr item))
640 (append (list (incf counter) (car item) 'keymap (car item))
641 (imenu--create-keymap-2 (cdr item) (+ counter 10))))
643 (let ((end (cons '(nil) t)))
644 (cons (car item)
645 (cons (car item) end))))
647 alist)))
649 (defun imenu--create-keymap-1 (title alist)
650 (append (list 'keymap title) (imenu--create-keymap-2 alist 0)))
653 (defun imenu--in-alist (str alist)
654 "Check whether the string STR is contained in multi-level ALIST."
655 (let (elt head tail res)
656 (setq res nil)
657 (while alist
658 (setq elt (car alist)
659 tail (cdr elt)
660 alist (cdr alist)
661 head (car elt))
662 (if (string= str head)
663 (setq alist nil res elt)
664 (if (and (listp tail)
665 (setq res (imenu--in-alist str tail)))
666 (setq alist nil))))
667 res))
669 (defun imenu-default-create-index-function ()
670 "*Wrapper for index searching functions.
672 Moves point to end of buffer and then repeatedly calls
673 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
674 Their results are gathered into an index alist."
675 ;; These should really be done by setting imenu-create-index-function
676 ;; in these major modes. But save that change for later.
677 (cond ((and (fboundp imenu-prev-index-position-function)
678 (fboundp imenu-extract-index-name-function))
679 (let ((index-alist '())
680 prev-pos name)
681 (goto-char (point-max))
682 (imenu-progress-message prev-pos 0 t)
683 ;; Search for the function
684 (while (funcall imenu-prev-index-position-function)
685 (imenu-progress-message prev-pos nil t)
686 (save-excursion
687 (setq name (funcall imenu-extract-index-name-function)))
688 (and (stringp name)
689 (push (cons name (point)) index-alist)))
690 (imenu-progress-message prev-pos 100 t)
691 index-alist))
692 ;; Use generic expression if possible.
693 ((and imenu-generic-expression)
694 (imenu--generic-function imenu-generic-expression))
695 ;; Use supplied example functions or expressions
696 ((assq major-mode imenu--scanning-method-alist)
697 (let ((method (cadr (assq major-mode imenu--scanning-method-alist))))
698 ;; is it a function?
699 (if (fboundp method)
700 ;; ... then call it
701 (funcall method)
702 ;; ...otherwise pass the pattern to imenu--generic-function
703 (imenu--generic-function (eval method)))))
705 (error "The mode \"%s\" does not take full advantage of imenu.el yet."
706 mode-name))))
708 (defun imenu--replace-spaces (name replacement)
709 ;; Replace all spaces in NAME with REPLACEMENT.
710 ;; That second argument should be a string.
711 (mapconcat
712 (function
713 (lambda (ch)
714 (if (char-equal ch ?\ )
715 replacement
716 (char-to-string ch))))
717 name
718 ""))
720 (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
721 ;; Takes a nested INDEX-ALIST and returns a flat index alist.
722 ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
723 ;; name and a space concatenated to the names of the children.
724 ;; Third argument PREFIX is for internal use only.
725 (mapcan
726 (function
727 (lambda (item)
728 (let* ((name (car item))
729 (pos (cdr item))
730 (new-prefix (and concat-names
731 (if prefix
732 (concat prefix imenu-level-separator name)
733 name))))
734 (cond
735 ((or (markerp pos) (numberp pos))
736 (list (cons new-prefix pos)))
738 (imenu--flatten-index-alist pos new-prefix))))))
739 index-alist))
742 ;;; Generic index gathering function.
745 (defun imenu--generic-function (patterns)
746 ;; Built on some ideas that Erik Naggum <erik@naggum.no> once posted
747 ;; to comp.emacs
748 "Return an index of the current buffer as an alist.
750 PATTERN is an alist with elements that look like this: (MENU-TITLE
751 REGEXP INDEX).
753 MENU-TITLE is a string used as the title for the submenu or nil if the
754 entries are not nested.
756 REGEXP is a regexp that should match a construct in the buffer that is
757 to be displayed in the menu; i.e., function or variable definitions,
758 etc. It contains a substring which is the name to appear in the
759 menu. See the info section on Regexps for more information.
761 INDEX points to the substring in REGEXP that contains the name (of the
762 function, variable or type) that is to appear in the menu.
764 For emacs-lisp-mode for example PATTERN would look like:
766 '((nil \"^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\s-+\\([-A-Za-z0-9]+\\)\" 2)
767 (\"*Vars*\" \"^\\s-*(def\\(var\\|const\\)\\s-+\\([-A-Za-z0-9]+\\)\" 2)
768 (\"*Types*\" \"^\\s-*(def\\(type\\|struct\\|class\\|ine-condition\\)\\s-+\\([-A-Za-z0-9]+\\)\" 2))'
770 Returns an index of the current buffer as an alist. The elements in
771 the alist look like: (INDEX-NAME . INDEX-POSITION). They may also be
772 nested index lists like (INDEX-NAME . INDEX-ALIST) depending on
773 pattern.
775 \(imenu--generic-function PATTERN\)."
777 (let ((index-alist (list 'dummy))
778 (found nil)
779 (global-regexp
780 (concat "\\("
781 (mapconcat
782 (function (lambda (pattern) (identity (cadr pattern))))
783 patterns "\\)\\|\\(")
784 "\\)"))
785 prev-pos)
787 (goto-char (point-max))
788 (imenu-progress-message prev-pos 0 t)
789 (save-match-data
790 (while (re-search-backward global-regexp nil t)
791 (imenu-progress-message prev-pos nil t)
792 (setq found nil)
793 (save-excursion
794 (goto-char (match-beginning 0))
795 (mapcar
796 (function
797 (lambda (pat)
798 (let ((menu-title (car pat))
799 (regexp (cadr pat))
800 (index (caddr pat)))
801 (if (and (not found) ; Only allow one entry;
802 (looking-at regexp))
803 (let ((beg (match-beginning index))
804 (end (match-end index)))
805 (setq found t)
806 (push
807 (cons (buffer-substring beg end) beg)
808 (cdr
809 (or (if (not (stringp menu-title)) index-alist)
810 (assoc
811 (imenu-create-submenu-name menu-title)
812 index-alist)
813 (car (push
814 (cons
815 (imenu-create-submenu-name menu-title)
816 '())
817 index-alist))))))))))
818 patterns))))
819 (imenu-progress-message prev-pos 100 t)
820 (delete 'dummy index-alist)))
822 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
824 ;;; The main functions for this package!
826 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
828 (defun imenu--completion-buffer (index-alist &optional prompt)
829 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
831 Returns t for rescan and otherwise a position number."
832 ;; Create a list for this buffer only when needed.
833 (let (name choice
834 (prepared-index-alist
835 (mapcar
836 (function
837 (lambda (item)
838 (cons (imenu--replace-spaces (car item) imenu-space-replacement)
839 (cdr item))))
840 index-alist)))
841 (if (eq imenu-always-use-completion-buffer-p 'never)
842 (setq name (completing-read (or prompt "Index item: ")
843 prepared-index-alist
844 nil t nil 'imenu--history-list))
845 (save-window-excursion
846 ;; Display the completion buffer
847 (with-output-to-temp-buffer "*Completions*"
848 (display-completion-list
849 (all-completions "" prepared-index-alist )))
850 (let ((minibuffer-setup-hook
851 (function (lambda ()
852 (let ((buffer (current-buffer)))
853 (save-excursion
854 (set-buffer "*Completions*")
855 (setq completion-reference-buffer buffer)))))))
856 ;; Make a completion question
857 (setq name (completing-read (or prompt "Index item: ")
858 prepared-index-alist
859 nil t nil 'imenu--history-list)))))
860 (cond ((not (stringp name))
861 nil)
862 ((string= name (car imenu--rescan-item))
865 (setq choice (assoc name prepared-index-alist))
866 (if (listp (cdr choice))
867 (imenu--completion-buffer (cdr choice) prompt)
868 choice)))))
870 (defun imenu--mouse-menu (index-alist event &optional title)
871 "Let the user select from a buffer index from a mouse menu.
873 INDEX-ALIST is the buffer index and EVENT is a mouse event.
875 Returns t for rescan and otherwise a position number."
876 (let* ((menu (imenu--split-menu
877 (if imenu-sort-function
878 (sort
879 (let ((res nil)
880 (oldlist index-alist))
881 ;; Copy list method from the cl package `copy-list'
882 (while (consp oldlist) (push (pop oldlist) res))
883 (prog1 (nreverse res) (setcdr res oldlist)))
884 imenu-sort-function)
885 index-alist)
886 (or title (buffer-name))))
887 position)
888 (and imenu-use-keymap-menu
889 (setq menu (imenu--create-keymap-1 (car menu)
890 (if (< 1 (length (cdr menu)))
891 (cdr menu)
892 (cdr (cadr menu))))))
893 (setq position (x-popup-menu event menu))
894 (if imenu-use-keymap-menu
895 (progn
896 (cond
897 ((and (listp position)
898 (numberp (car position))
899 (stringp (nth (1- (length position)) position)))
900 (setq position (nth (1- (length position)) position)))
901 ((and (stringp (car position))
902 (null (cdr position)))
903 (setq position (car position))))))
904 (cond
905 ((eq position nil)
906 position)
907 ((listp position)
908 (imenu--mouse-menu position event
909 (if title
910 (concat title imenu-level-separator
911 (car (rassq position index-alist)))
912 (car (rassq position index-alist)))))
913 ((stringp position)
914 (or (string= position (car imenu--rescan-item))
915 (imenu--in-alist position index-alist)))
916 ((or (= position (cdr imenu--rescan-item))
917 (and (stringp position)
918 (string= position (car imenu--rescan-item))))
921 (rassq position index-alist)))))
923 (defun imenu-choose-buffer-index (&optional prompt alist)
924 "Let the user select from a buffer index and return the chosen index.
926 If the user originally activated this function with the mouse, a mouse
927 menu is used. Otherwise a completion buffer is used and the user is
928 prompted with PROMPT.
930 If you call this function with index alist ALIST, then it lets the user
931 select from ALIST.
933 With no index alist ALIST, it calls `imenu--make-index-alist' to
934 create the index alist.
936 If `imenu-always-use-completion-buffer-p' is non-nil, then the
937 completion buffer is always used, no matter if the mouse was used or
938 not.
940 The returned value is on the form (INDEX-NAME . INDEX-POSITION)."
941 (let (index-alist
942 (mouse-triggered (listp last-nonmenu-event))
943 (result t) )
944 ;; If selected by mouse, see to that the window where the mouse is
945 ;; really is selected.
946 (and mouse-triggered
947 (not (equal last-nonmenu-event '(menu-bar)))
948 (let ((window (posn-window (event-start last-nonmenu-event))))
949 (or (framep window) (null window) (select-window window))))
950 ;; Create a list for this buffer only when needed.
951 (while (eq result t)
952 (setq index-alist (if alist alist (imenu--make-index-alist)))
953 (setq result
954 (if (and mouse-triggered
955 (not imenu-always-use-completion-buffer-p))
956 (imenu--mouse-menu index-alist last-nonmenu-event)
957 (imenu--completion-buffer index-alist prompt)))
958 (and (eq result t)
959 (imenu--cleanup)
960 (setq imenu--index-alist nil)))
961 result))
963 ;;;###autoload
964 (defun imenu-add-to-menubar (name)
965 "Adds an \"imenu\" entry to the menubar for the current local keymap.
966 NAME is the string naming the menu to be added.
967 See 'imenu' for more information."
968 (interactive "sMenu name: ")
969 (and window-system
970 (define-key (current-local-map) [menu-bar index]
971 (cons name 'imenu))))
973 ;;;###autoload
974 (defun imenu (index-item)
975 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
976 See `imenu-choose-buffer-index' for more information."
977 (interactive
978 (list (save-restriction
979 (widen)
980 (imenu-choose-buffer-index))))
981 (and index-item
982 (progn
983 (push-mark)
984 (cond
985 ((markerp (cdr index-item))
986 (if (or ( > (marker-position (cdr index-item)) (point-min))
987 ( < (marker-position (cdr index-item)) (point-max)))
988 ;; widen if outside narrowing
989 (widen))
990 (goto-char (marker-position (cdr index-item))))
992 (if (or ( > (cdr index-item) (point-min))
993 ( < (cdr index-item) (point-max)))
994 ;; widen if outside narrowing
995 (widen))
996 (goto-char (cdr index-item)))))))
998 (provide 'imenu)
1000 ;;; imenu.el ends here