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