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