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