(imenu--generic-function): Create a special entry
[bpt/emacs.git] / lisp / imenu.el
CommitLineData
0a688fd0
RS
1;;; imenu.el --- Framework for mode-specific buffer indexes.
2
f5632218 3;; Copyright (C) 1994, 1995, 1996 Free Software Foundation, Inc.
0a688fd0
RS
4
5;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
6;; Lars Lindberg <lli@sypro.cap.se>
7;; Created: 8 Feb 1994
0a688fd0 8;; Keywords: tools
b578f267
EN
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
0a688fd0
RS
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.
b578f267
EN
16
17;; GNU Emacs is distributed in the hope that it will be useful,
0a688fd0
RS
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.
b578f267 21
0a688fd0 22;; You should have received a copy of the GNU General Public License
b578f267
EN
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.
0a688fd0
RS
26
27;;; Commentary:
b578f267 28
0a688fd0
RS
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
2d24227e
RS
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.
0a688fd0 46
26d6bb60
RS
47;;; Thanks goes to
48;; [simon] - Simon Leinen simon@lia.di.epfl.ch
49;; [dean] - Dean Andrews ada@unison.com
5d3b0f18 50;; [alon] - Alon Albert al@mercury.co.il
7804cd27 51;; [greg] - Greg Thompson gregt@porsche.visix.COM
615b306c 52;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
056ab244 53;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
af447694 54;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
2d24227e
RS
55;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
56;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
57
0a688fd0 58;;; Code
b578f267 59
0ee4f8ad 60(eval-when-compile (require 'cl))
0a688fd0
RS
61
62;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
63;;;
64;;; Customizable variables
65;;;
66;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2d24227e
RS
67
68(defvar imenu-auto-rescan nil
6c1bf12b 69 "*Non-nil means Imenu should always rescan the buffers.")
2d24227e
RS
70
71(defvar imenu-auto-rescan-maxout 60000
72 "* auto-rescan is disabled in buffers larger than this.
6c1bf12b 73This variable is buffer-local.")
0a688fd0
RS
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
78Non-nil means always display the index in a completion buffer.
79Nil means display the index as a mouse menu when the mouse was
af447694
RS
80used to invoke `imenu'.
81`never' means never automatically display a listing of any kind.")
0a688fd0
RS
82
83(defvar imenu-sort-function nil
84 "*The function to use for sorting the index mouse-menu.
85
86Affects only the mouse index menu.
87
88Set this to nil if you don't want any sorting (faster).
89The items in the menu are then presented in the order they were found
90in the buffer.
91
0ee4f8ad 92Set it to `imenu--sort-by-name' if you want alphabetic sorting.
0a688fd0
RS
93
94The function should take two arguments and return T if the first
95element should come before the second. The arguments are cons cells;
a4e104bf 96\(NAME . POSITION). Look at `imenu--sort-by-name' for an example.")
0a688fd0
RS
97
98(defvar imenu-max-items 25
0c20ee61 99 "*Maximum number of elements in an mouse menu for Imenu.")
0a688fd0 100
6c1bf12b 101(defvar imenu-scanning-message "Scanning buffer for index (%3d%%)"
0a688fd0 102 "*Progress message during the index scanning of the buffer.
7dea4e70 103If non-nil, user gets a message during the scanning of the buffer
0a688fd0
RS
104
105Relevant only if the mode-specific function that creates the buffer
0ee4f8ad 106index use `imenu-progress-message'.")
0a688fd0
RS
107
108(defvar imenu-space-replacement "^"
109 "*The replacement string for spaces in index names.
110Used when presenting the index in a completion-buffer to make the
111names work as tokens.")
112
113(defvar imenu-level-separator ":"
114 "*The separator between index names of different levels.
115Used for making mouse-menu titles and for flattening nested indexes
116with name concatenation.")
117
2d24227e 118;;;###autoload
615b306c 119(defvar imenu-generic-expression nil
2d24227e
RS
120 "The regex pattern to use for creating a buffer index.
121
122If non-nil this pattern is passed to `imenu-create-index-with-pattern'
123to create a buffer index.
124
215b077e
RS
125The value should be an alist with elements that look like this:
126 (MENU-TITLE REGEXP INDEX)
127or like this:
128 (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
129with zero or more ARGUMENTS. The former format creates a simple element in
130the index alist when it matches; the latter creates a special element
131of the form (NAME FUNCTION NAME POSITION-MARKER ARGUMENTS...)
132with FUNCTION and ARGUMENTS beiong copied from `imenu-generic-expression'.
2d24227e
RS
133
134MENU-TITLE is a string used as the title for the submenu or nil if the
135entries are not nested.
136
137REGEXP is a regexp that should match a construct in the buffer that is
6c1bf12b
RS
138to be displayed in the menu; i.e., function or variable definitions,
139etc. It contains a substring which is the name to appear in the
140menu. See the info section on Regexps for more information.
2d24227e
RS
141
142INDEX points to the substring in REGEXP that contains the name (of the
143function, variable or type) that is to appear in the menu.
615b306c 144
2d24227e
RS
145For emacs-lisp-mode for example PATTERN would look like:
146
c30c8a0c
RS
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))
2d24227e
RS
150
151The variable is buffer-local.")
152
af5eb153 153;;;###autoload
6c1bf12b 154(make-variable-buffer-local 'imenu-generic-expression)
615b306c 155
0a688fd0
RS
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
161It should be a function that takes no arguments and returns an index
215b077e
RS
162of the current buffer as an alist.
163
164Simple elements in the alist look like (INDEX-NAME . INDEX-POSITION).
165Special elements look like (INDEX-NAME FUNCTION ARGUMENTS...).
166A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
167The function `imenu--subalist-p' tests an element and returns t
168 if it is a sub-alist.
0a688fd0 169
0ee4f8ad 170This function is called within a `save-excursion'.
0a688fd0
RS
171
172The variable is buffer-local.")
173(make-variable-buffer-local 'imenu-create-index-function)
174
68e01f5a 175(defvar imenu-prev-index-position-function 'beginning-of-defun
0a688fd0
RS
176 "Function for finding the next index position.
177
0ee4f8ad
RS
178If `imenu-create-index-function' is set to
179`imenu-default-create-index-function', then you must set this variable
0a688fd0
RS
180to a function that will find the next index, looking backwards in the
181file.
182
183The function should leave point at the place to be connected to the
6c1bf12b 184index and it should return nil when it doesn't find another index.")
68e01f5a 185(make-variable-buffer-local 'imenu-prev-index-position-function)
0a688fd0 186
68e01f5a 187(defvar imenu-extract-index-name-function nil
0a688fd0
RS
188 "Function for extracting the index name.
189
0a688fd0 190This function is called after the function pointed out by
68e01f5a
RS
191`imenu-prev-index-position-function'.")
192(make-variable-buffer-local 'imenu-extract-index-name-function)
0a688fd0 193
215b077e
RS
194(defun imenu--subalist-p (item)
195 (and (consp (cdr item)) (listp (cadr item))
196 (not (eq (caadr item) 'lambda))))
197
615b306c
KH
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
e064a4f9 224;; Return the current/previous sexp and the location of the sexp (its
615b306c
KH
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
0c20ee61 295 (push (cons "Variables" index-var-alist)
615b306c
KH
296 index-alist))
297 (and index-type-alist
0c20ee61 298 (push (cons "Types" index-type-alist)
615b306c
KH
299 index-alist))
300 (and index-unknown-alist
0c20ee61 301 (push (cons "Syntax-unknown" index-unknown-alist)
615b306c
KH
302 index-alist))
303 index-alist))
304
615b306c
KH
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
2d24227e 336
0a688fd0
RS
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
0a8e8bc6
KH
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
0a688fd0 355;; History list for 'jump-to-function-in-buffer'.
6c1bf12b 356;; Making this buffer local caused it not to work!
0a688fd0 357(defvar imenu--history-list nil)
0a688fd0
RS
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
0a688fd0
RS
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
0c20ee61
RS
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.
0a688fd0 408(defun imenu--split-menu (menulist title)
32c1a22e
RS
409 (if imenu-sort-function
410 (setq menulist
411 (sort
412 (let ((res nil)
413 (oldlist menulist))
414 ;; Copy list method from the cl package `copy-list'
415 (while (consp oldlist) (push (pop oldlist) res))
416 (prog1 (nreverse res) (setcdr res oldlist)))
417 imenu-sort-function)))
0c20ee61
RS
418 (if (> (length menulist) imenu-max-items)
419 (let ((count 0))
420 (cons title
421 (mapcar
422 (function
423 (lambda (menu)
424 (cons (format "(%s-%d)" title (setq count (1+ count)))
425 menu)))
426 (imenu--split menulist imenu-max-items))))
427 (cons title menulist)))
428
429;;; Split up each long alist that are nested within ALIST
430;;; into nested alists.
431(defun imenu--split-submenus (alist)
432 (mapcar (function (lambda (elt)
433 (if (and (consp elt)
434 (stringp (car elt))
435 (listp (cdr elt)))
436 (imenu--split-menu (cdr elt) (car elt))
437 elt)))
438 alist))
0a688fd0
RS
439
440;;;
441;;; Find all items in this buffer that should be in the index.
442;;; Returns an alist on the form
443;;; ((NAME . POSITION) (NAME . POSITION) ...)
444;;;
445
0a8e8bc6 446(defun imenu--make-index-alist (&optional noerror)
0a688fd0 447 ;; Create a list for this buffer only when needed.
2d24227e
RS
448 (or (and imenu--index-alist
449 (or (not imenu-auto-rescan)
450 (and imenu-auto-rescan
451 (> (buffer-size) imenu-auto-rescan-maxout))))
0a688fd0
RS
452 ;; Get the index
453 (setq imenu--index-alist
454 (save-excursion
455 (funcall imenu-create-index-function))))
0a8e8bc6 456 (or imenu--index-alist noerror
6c1bf12b 457 (error "No items suitable for an index found in this buffer"))
0a8e8bc6
KH
458 (or imenu--index-alist
459 (setq imenu--index-alist (list nil)))
0a688fd0
RS
460 ;; Add a rescan option to the index.
461 (cons imenu--rescan-item imenu--index-alist))
5d3b0f18
RS
462;;;
463;;; Find all markers in alist and makes
464;;; them point nowhere.
465;;;
466(defun imenu--cleanup (&optional alist)
467 ;; Sets the markers in imenu--index-alist
468 ;; point nowhere.
469 ;; if alist is provided use that list.
4818d210
RS
470 (or alist
471 (setq alist imenu--index-alist))
472 (and alist
7804cd27 473 (mapcar
5d3b0f18
RS
474 (function
475 (lambda (item)
476 (cond
477 ((markerp (cdr item))
478 (set-marker (cdr item) nil))
215b077e 479 ((imenu--subalist-p item)
5d3b0f18 480 (imenu--cleanup (cdr item))))))
4818d210 481 alist)
615b306c
KH
482 t))
483
0a8e8bc6 484(defun imenu--create-keymap-2 (alist counter &optional commands)
2d24227e
RS
485 (let ((map nil))
486 (mapcar
487 (function
488 (lambda (item)
489 (cond
215b077e 490 ((imenu--subalist-p item)
fc0ac20d
KH
491 (append (list (setq counter (1+ counter))
492 (car item) 'keymap (car item))
0a8e8bc6 493 (imenu--create-keymap-2 (cdr item) (+ counter 10) commands)))
2d24227e 494 (t
fc0ac20d
KH
495 (let ((end (if commands `(lambda () (interactive)
496 (imenu--menubar-select ',item))
32c1a22e 497 (cons '(nil) item))))
2d24227e
RS
498 (cons (car item)
499 (cons (car item) end))))
500 )))
501 alist)))
502
0a8e8bc6
KH
503;; If COMMANDS is non-nil, make a real keymap
504;; with a real command used as the definition.
505;; If it is nil, make something suitable for x-popup-menu.
506(defun imenu--create-keymap-1 (title alist &optional commands)
507 (append (list 'keymap title) (imenu--create-keymap-2 alist 0 commands)))
2d24227e
RS
508
509
510(defun imenu--in-alist (str alist)
511 "Check whether the string STR is contained in multi-level ALIST."
512 (let (elt head tail res)
513 (setq res nil)
514 (while alist
515 (setq elt (car alist)
516 tail (cdr elt)
517 alist (cdr alist)
518 head (car elt))
8396299d
RS
519 ;; A nested ALIST element looks like
520 ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
521 ;; while a bottom-level element looks like
522 ;; (INDEX-NAME . INDEX-POSITION)
523 ;; We are only interested in the bottom-level elements, so we need to
524 ;; recurse if TAIL is a list.
525 (cond ((listp tail)
526 (if (setq res (imenu--in-alist str tail))
527 (setq alist nil)))
528 ((string= str head)
529 (setq alist nil res elt))))
2d24227e
RS
530 res))
531
0a688fd0
RS
532(defun imenu-default-create-index-function ()
533 "*Wrapper for index searching functions.
534
535Moves point to end of buffer and then repeatedly calls
68e01f5a 536`imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
0a688fd0 537Their results are gathered into an index alist."
3e062f78
RS
538 ;; These should really be done by setting imenu-create-index-function
539 ;; in these major modes. But save that change for later.
615b306c
KH
540 (cond ((and (fboundp imenu-prev-index-position-function)
541 (fboundp imenu-extract-index-name-function))
3e062f78 542 (let ((index-alist '())
615b306c 543 prev-pos name)
3e062f78 544 (goto-char (point-max))
7dea4e70 545 (imenu-progress-message prev-pos 0 t)
3e062f78
RS
546 ;; Search for the function
547 (while (funcall imenu-prev-index-position-function)
7dea4e70 548 (imenu-progress-message prev-pos nil t)
3e062f78
RS
549 (save-excursion
550 (setq name (funcall imenu-extract-index-name-function)))
551 (and (stringp name)
552 (push (cons name (point)) index-alist)))
7dea4e70 553 (imenu-progress-message prev-pos 100 t)
615b306c
KH
554 index-alist))
555 ;; Use generic expression if possible.
556 ((and imenu-generic-expression)
e064a4f9 557 (imenu--generic-function imenu-generic-expression))
615b306c
KH
558 (t
559 (error "The mode \"%s\" does not take full advantage of imenu.el yet."
560 mode-name))))
0a688fd0
RS
561
562(defun imenu--replace-spaces (name replacement)
563 ;; Replace all spaces in NAME with REPLACEMENT.
564 ;; That second argument should be a string.
565 (mapconcat
566 (function
567 (lambda (ch)
568 (if (char-equal ch ?\ )
569 replacement
570 (char-to-string ch))))
571 name
572 ""))
573
574(defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
575 ;; Takes a nested INDEX-ALIST and returns a flat index alist.
576 ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
577 ;; name and a space concatenated to the names of the children.
578 ;; Third argument PREFIX is for internal use only.
579 (mapcan
580 (function
581 (lambda (item)
582 (let* ((name (car item))
583 (pos (cdr item))
584 (new-prefix (and concat-names
585 (if prefix
586 (concat prefix imenu-level-separator name)
587 name))))
588 (cond
5d3b0f18 589 ((or (markerp pos) (numberp pos))
0a688fd0
RS
590 (list (cons new-prefix pos)))
591 (t
592 (imenu--flatten-index-alist pos new-prefix))))))
593 index-alist))
594
615b306c
KH
595;;;
596;;; Generic index gathering function.
597;;;
2d24227e
RS
598
599(defun imenu--generic-function (patterns)
600;; Built on some ideas that Erik Naggum <erik@naggum.no> once posted
601;; to comp.emacs
602 "Return an index of the current buffer as an alist.
603
604PATTERN is an alist with elements that look like this: (MENU-TITLE
6c1bf12b 605REGEXP INDEX).
2d24227e
RS
606
607MENU-TITLE is a string used as the title for the submenu or nil if the
608entries are not nested.
609
610REGEXP is a regexp that should match a construct in the buffer that is
6c1bf12b
RS
611to be displayed in the menu; i.e., function or variable definitions,
612etc. It contains a substring which is the name to appear in the
613menu. See the info section on Regexps for more information.
2d24227e
RS
614
615INDEX points to the substring in REGEXP that contains the name (of the
616function, variable or type) that is to appear in the menu.
617
618For emacs-lisp-mode for example PATTERN would look like:
619
c30c8a0c
RS
620'((nil \"^\\\\s-*(def\\\\(un\\\\|subst\\\\|macro\\\\|advice\\\\)\\\\s-+\\\\([-A-Za-z0-9]+\\\\)\" 2)
621 (\"*Vars*\" \"^\\\\s-*(def\\\\(var\\\\|const\\\\)\\\\s-+\\\\([-A-Za-z0-9]+\\\\)\" 2)
622 (\"*Types*\" \"^\\\\s-*(def\\\\(type\\\\|struct\\\\|class\\\\|ine-condition\\\\)\\\\s-+\\\\([-A-Za-z0-9]+\\\\)\" 2))'
2d24227e 623
6c1bf12b
RS
624Returns an index of the current buffer as an alist. The elements in
625the alist look like: (INDEX-NAME . INDEX-POSITION). They may also be
2d24227e
RS
626nested index lists like (INDEX-NAME . INDEX-ALIST) depending on
627pattern.
628
629\(imenu--generic-function PATTERN\)."
630
631 (let ((index-alist (list 'dummy))
632 (found nil)
633 (global-regexp
634 (concat "\\("
635 (mapconcat
636 (function (lambda (pattern) (identity (cadr pattern))))
637 patterns "\\)\\|\\(")
638 "\\)"))
639 prev-pos)
640
615b306c
KH
641 (goto-char (point-max))
642 (imenu-progress-message prev-pos 0 t)
2d24227e
RS
643 (save-match-data
644 (while (re-search-backward global-regexp nil t)
645 (imenu-progress-message prev-pos nil t)
646 (setq found nil)
647 (save-excursion
648 (goto-char (match-beginning 0))
649 (mapcar
650 (function
651 (lambda (pat)
652 (let ((menu-title (car pat))
653 (regexp (cadr pat))
215b077e
RS
654 (index (caddr pat))
655 (function (cadddr pat))
656 (rest (cddddr pat)))
657 (if (and (not found) ; Only allow one entry;
658 (looking-at regexp))
659 (let ((beg (make-marker))
660 (end (match-end index)))
661 (set-marker beg (match-beginning index))
662 (setq found t)
663 (push
664 (let ((name
665 (buffer-substring-no-properties beg end)))
666 (if function
667 (nconc (list name function name beg)
668 rest)
669 (cons name beg)))
670 (cdr
671 (or (assoc menu-title index-alist)
672 (car (push
673 (cons menu-title '())
674 index-alist))))))))))
0c20ee61
RS
675 patterns))))
676 (imenu-progress-message prev-pos 100 t)
677 (let ((main-element (assq nil index-alist)))
678 (nconc (delq main-element (delq 'dummy index-alist)) main-element))))
615b306c 679
0a688fd0
RS
680;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
681;;;
682;;; The main functions for this package!
683;;;
684;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685
686(defun imenu--completion-buffer (index-alist &optional prompt)
687 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
688
689Returns t for rescan and otherwise a position number."
690 ;; Create a list for this buffer only when needed.
691 (let (name choice
615b306c
KH
692 (prepared-index-alist
693 (mapcar
694 (function
695 (lambda (item)
696 (cons (imenu--replace-spaces (car item) imenu-space-replacement)
697 (cdr item))))
698 index-alist)))
af447694
RS
699 (if (eq imenu-always-use-completion-buffer-p 'never)
700 (setq name (completing-read (or prompt "Index item: ")
701 prepared-index-alist
702 nil t nil 'imenu--history-list))
703 (save-window-excursion
704 ;; Display the completion buffer
705 (with-output-to-temp-buffer "*Completions*"
706 (display-completion-list
707 (all-completions "" prepared-index-alist )))
708 (let ((minibuffer-setup-hook
709 (function (lambda ()
710 (let ((buffer (current-buffer)))
711 (save-excursion
712 (set-buffer "*Completions*")
713 (setq completion-reference-buffer buffer)))))))
714 ;; Make a completion question
715 (setq name (completing-read (or prompt "Index item: ")
716 prepared-index-alist
717 nil t nil 'imenu--history-list)))))
3e062f78
RS
718 (cond ((not (stringp name))
719 nil)
720 ((string= name (car imenu--rescan-item))
721 t)
722 (t
723 (setq choice (assoc name prepared-index-alist))
215b077e 724 (if (imenu--subalist-p choice)
3e062f78
RS
725 (imenu--completion-buffer (cdr choice) prompt)
726 choice)))))
68e01f5a 727
0a688fd0
RS
728(defun imenu--mouse-menu (index-alist event &optional title)
729 "Let the user select from a buffer index from a mouse menu.
730
731INDEX-ALIST is the buffer index and EVENT is a mouse event.
732
32c1a22e 733Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
0c20ee61 734 (setq index-alist (imenu--split-submenus index-alist))
32c1a22e 735 (let* ((menu (imenu--split-menu index-alist
0a688fd0
RS
736 (or title (buffer-name))))
737 position)
fdbf0fc7
RS
738 (setq menu (imenu--create-keymap-1 (car menu)
739 (if (< 1 (length (cdr menu)))
740 (cdr menu)
32c1a22e 741 (cdr (car (cdr menu))))))
0a688fd0 742 (setq position (x-popup-menu event menu))
32c1a22e
RS
743 (cond ((eq position nil)
744 position)
745 ;; If one call to x-popup-menu handled the nested menus,
746 ;; find the result by looking down the menus here.
747 ((and (listp position)
27f94c9b
RS
748 (numberp (car position))
749 (stringp (nth (1- (length position)) position)))
32c1a22e
RS
750 (let ((final menu))
751 (while position
752 (setq final (assoc (car position) final))
753 (setq position (cdr position)))
b8c44b29
RS
754 (or (string= (car final) (car imenu--rescan-item))
755 (cdr (cdr (cdr final))))))
32c1a22e
RS
756 ;; If x-popup-menu went just one level and found a leaf item,
757 ;; return the INDEX-ALIST element for that.
758 ((and (consp position)
759 (stringp (car position))
27f94c9b 760 (null (cdr position)))
32c1a22e
RS
761 (or (string= (car position) (car imenu--rescan-item))
762 (assq (car position) index-alist)))
763 ;; If x-popup-menu went just one level
764 ;; and found a non-leaf item (a submenu),
765 ;; recurse to handle the rest.
27f94c9b
RS
766 ((listp position)
767 (imenu--mouse-menu position event
768 (if title
769 (concat title imenu-level-separator
770 (car (rassq position index-alist)))
32c1a22e 771 (car (rassq position index-alist))))))))
0a688fd0 772
26d6bb60 773(defun imenu-choose-buffer-index (&optional prompt alist)
0a688fd0
RS
774 "Let the user select from a buffer index and return the chosen index.
775
776If the user originally activated this function with the mouse, a mouse
0a688fd0
RS
777menu is used. Otherwise a completion buffer is used and the user is
778prompted with PROMPT.
779
26d6bb60
RS
780If you call this function with index alist ALIST, then it lets the user
781select from ALIST.
782
0ee4f8ad 783With no index alist ALIST, it calls `imenu--make-index-alist' to
26d6bb60
RS
784create the index alist.
785
0ee4f8ad 786If `imenu-always-use-completion-buffer-p' is non-nil, then the
0a688fd0
RS
787completion buffer is always used, no matter if the mouse was used or
788not.
789
790The returned value is on the form (INDEX-NAME . INDEX-POSITION)."
791 (let (index-alist
7dea4e70 792 (mouse-triggered (listp last-nonmenu-event))
0a688fd0
RS
793 (result t) )
794 ;; If selected by mouse, see to that the window where the mouse is
795 ;; really is selected.
796 (and mouse-triggered
4cde72b4 797 (not (equal last-nonmenu-event '(menu-bar)))
7dea4e70 798 (let ((window (posn-window (event-start last-nonmenu-event))))
4a840d8b 799 (or (framep window) (null window) (select-window window))))
0a688fd0
RS
800 ;; Create a list for this buffer only when needed.
801 (while (eq result t)
26d6bb60 802 (setq index-alist (if alist alist (imenu--make-index-alist)))
0a688fd0
RS
803 (setq result
804 (if (and mouse-triggered
805 (not imenu-always-use-completion-buffer-p))
7dea4e70 806 (imenu--mouse-menu index-alist last-nonmenu-event)
0a688fd0
RS
807 (imenu--completion-buffer index-alist prompt)))
808 (and (eq result t)
5d3b0f18 809 (imenu--cleanup)
0a688fd0
RS
810 (setq imenu--index-alist nil)))
811 result))
812
2d24227e 813;;;###autoload
5d3b0f18 814(defun imenu-add-to-menubar (name)
d1757026 815 "Adds an `imenu' entry to the menu bar for the current buffer.
0a8e8bc6 816NAME is a string used to name the menu bar item.
d1757026 817See the command `imenu' for more information."
0a8e8bc6 818 (interactive "sImenu menu item name: ")
d1757026
RS
819 (let ((newmap (make-sparse-keymap))
820 (menu-bar (lookup-key (current-local-map) [menu-bar])))
821 (define-key newmap [menu-bar]
822 (append (make-sparse-keymap) menu-bar))
823 (define-key newmap [menu-bar index]
824 (cons name (nconc (make-sparse-keymap "Imenu")
825 (make-sparse-keymap))))
826 (use-local-map (append newmap (current-local-map))))
0a8e8bc6
KH
827 (add-hook 'menu-bar-update-hook 'imenu-update-menubar))
828
6d7a4832
KH
829(defvar imenu-buffer-menubar nil)
830
0a8e8bc6
KH
831(defun imenu-update-menubar ()
832 (and (current-local-map)
833 (keymapp (lookup-key (current-local-map) [menu-bar index]))
834 (let ((index-alist (imenu--make-index-alist t)))
835 ;; Don't bother updating if the index-alist has not changed
836 ;; since the last time we did it.
837 (or (equal index-alist imenu--last-menubar-index-alist)
838 (let (menu menu1 old)
839 (setq imenu--last-menubar-index-alist index-alist)
0c20ee61 840 (setq index-alist (imenu--split-submenus index-alist))
32c1a22e 841 (setq menu (imenu--split-menu index-alist
0a8e8bc6
KH
842 (buffer-name)))
843 (setq menu1 (imenu--create-keymap-1 (car menu)
844 (if (< 1 (length (cdr menu)))
845 (cdr menu)
846 (cdr (car (cdr menu))))
847 t))
848 (setq old (lookup-key (current-local-map) [menu-bar index]))
5d43dca8 849 (setcdr old (cdr menu1)))))))
0a8e8bc6
KH
850
851(defun imenu--menubar-select (item)
852 "Use Imenu to select the function or variable named in this menu item."
e63679b8
RS
853 (if (equal item '("*Rescan*" . -99))
854 (progn
855 (imenu--cleanup)
856 (setq imenu--index-alist nil)
857 (imenu-update-menubar))
858 (imenu item)))
5d3b0f18 859
68e01f5a 860;;;###autoload
6c1bf12b 861(defun imenu (index-item)
68e01f5a 862 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
0ee4f8ad 863See `imenu-choose-buffer-index' for more information."
6c1bf12b
RS
864 (interactive
865 (list (save-restriction
866 (widen)
880169e2 867 (imenu-choose-buffer-index))))
0a8e8bc6
KH
868 ;; Convert a string to an alist element.
869 (if (stringp index-item)
870 (setq index-item (assoc index-item (imenu--make-index-alist))))
6c1bf12b
RS
871 (and index-item
872 (progn
873 (push-mark)
874 (cond
875 ((markerp (cdr index-item))
32c1a22e
RS
876 (if (or (< (marker-position (cdr index-item)) (point-min))
877 (> (marker-position (cdr index-item)) (point-max)))
6c1bf12b
RS
878 ;; widen if outside narrowing
879 (widen))
880 (goto-char (marker-position (cdr index-item))))
215b077e 881 ((imenu--subalist-p index-item)
32c1a22e
RS
882 (if (or (< (cdr index-item) (point-min))
883 (> (cdr index-item) (point-max)))
6c1bf12b
RS
884 ;; widen if outside narrowing
885 (widen))
215b077e
RS
886 (goto-char (cdr index-item)))
887 (t
888 ;; A special item with a function.
889 (let ((function (cadr index-item))
890 (rest (cddr index-item)))
891 (apply function (car index-item) rest)))))))
5d3b0f18 892
0a688fd0
RS
893(provide 'imenu)
894
895;;; imenu.el ends here