imenu.el 34.5 KB
Newer Older
1
;;; imenu.el --- framework for mode-specific buffer indexes  -*- lexical-binding: t -*-
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1994-1998, 2001-2019 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4 5 6

;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
;;         Lars Lindberg <lli@sypro.cap.se>
7
;; Maintainer: emacs-devel@gnu.org
Richard M. Stallman's avatar
Richard M. Stallman committed
8
;; Created: 8 Feb 1994
Dan Nicolaescu's avatar
Dan Nicolaescu committed
9
;; Keywords: tools convenience
Erik Naggum's avatar
Erik Naggum committed
10 11 12

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Erik Naggum's avatar
Erik Naggum committed
17 18

;; GNU Emacs is distributed in the hope that it will be useful,
Richard M. Stallman's avatar
Richard M. Stallman committed
19 20 21
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
Erik Naggum's avatar
Erik Naggum committed
22

Richard M. Stallman's avatar
Richard M. Stallman committed
23
;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
25 26

;;; Commentary:
Erik Naggum's avatar
Erik Naggum committed
27

Richard M. Stallman's avatar
Richard M. Stallman committed
28 29 30 31 32
;; Purpose of this package:
;;   To present a framework for mode-specific buffer indexes.
;;   A buffer index is an alist of names and buffer positions.
;;   For instance all functions in a C-file and their positions.
;;
33 34
;;   It is documented in the Emacs Lisp manual.
;;
Richard M. Stallman's avatar
Richard M. Stallman committed
35 36 37 38 39 40 41 42
;; How it works:

;;   A mode-specific function is called to generate the index.  It is
;;   then presented to the user, who can choose from this index.
;;
;;   The package comes with a set of example functions for how to
;;   utilize this package.

43 44 45 46
;;   There are *examples* for index gathering functions/regular
;;   expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
;;   customize for other modes.  A function for jumping to the chosen
;;   index position is also supplied.
Richard M. Stallman's avatar
Richard M. Stallman committed
47

48 49
;;; History:
;;  Thanks go to
Richard M. Stallman's avatar
Richard M. Stallman committed
50 51
;;  [simon] - Simon Leinen simon@lia.di.epfl.ch
;;  [dean] - Dean Andrews ada@unison.com
52
;;  [alon] - Alon Albert al@mercury.co.il
53
;;  [greg] - Greg Thompson gregt@porsche.visix.COM
54
;;  [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
55
;;  [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
56
;;  [david] - David M. Smith dsmith@stats.adelaide.edu.au
57 58 59
;;  [christian] - Christian Egli Christian.Egli@hcsd.hac.com
;;  [karl] - Karl Fogel kfogel@floss.life.uiuc.edu

60
;;; Code:
Erik Naggum's avatar
Erik Naggum committed
61

62
(require 'cl-lib)
Richard M. Stallman's avatar
Richard M. Stallman committed
63 64 65 66 67 68

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Customizable variables
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
69

70 71 72
(defgroup imenu nil
  "Mode-specific buffer indexes."
  :group 'matching
73
  :group 'frames
Dan Nicolaescu's avatar
Dan Nicolaescu committed
74
  :group 'convenience
75
  :link '(custom-manual "(elisp)Imenu"))
76 77

(defcustom imenu-use-markers t
Lute Kamstra's avatar
Lute Kamstra committed
78
  "Non-nil means use markers instead of integers for Imenu buffer positions.
79 80 81

Setting this to nil makes Imenu work a little faster but editing the
buffer will make the generated index positions wrong.
82

83 84 85 86
This might not yet be honored by all index-building functions."
  :type 'boolean
  :group 'imenu)

87

88
(defcustom imenu-max-item-length 60
Lute Kamstra's avatar
Lute Kamstra committed
89
  "If a number, truncate Imenu entries to that length."
90 91
  :type '(choice integer
		 (const :tag "Unlimited"))
92
  :group 'imenu)
93

94
(defcustom imenu-auto-rescan nil
Lute Kamstra's avatar
Lute Kamstra committed
95
  "Non-nil means Imenu should always rescan the buffers."
96 97
  :type 'boolean
  :group 'imenu)
98

99 100
(defcustom imenu-auto-rescan-maxout 600000
  "Imenu auto-rescan is disabled in buffers larger than this size (in bytes)."
101
  :type 'integer
102 103
  :group 'imenu
  :version "26.2")
Richard M. Stallman's avatar
Richard M. Stallman committed
104

105
(defcustom imenu-use-popup-menu 'on-mouse
106 107 108 109 110 111
  "Use a popup menu rather than a minibuffer prompt.
If nil, always use a minibuffer prompt.
If t, always use a popup menu,
If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
  :type '(choice (const :tag "On Mouse" on-mouse)
		 (const :tag "Never" nil)
112 113
		 (other :tag "Always" t))
  :group 'imenu)
114

115
(defcustom imenu-eager-completion-buffer t
116
  "If non-nil, eagerly popup the completion buffer."
117 118
  :type 'boolean
  :group 'imenu
119
  :version "22.1")
Richard M. Stallman's avatar
Richard M. Stallman committed
120

121
(defcustom imenu-after-jump-hook nil
Lute Kamstra's avatar
Lute Kamstra committed
122
  "Hooks called after jumping to a place in the buffer.
123 124 125 126 127 128

Useful things to use here include `reposition-window', `recenter', and
\(lambda () (recenter 0)) to show at top of screen."
  :type 'hook
  :group 'imenu)

129
;;;###autoload
130
(defcustom imenu-sort-function nil
Lute Kamstra's avatar
Lute Kamstra committed
131
  "The function to use for sorting the index mouse-menu.
Richard M. Stallman's avatar
Richard M. Stallman committed
132 133 134 135 136 137 138

Affects only the mouse index menu.

Set this to nil if you don't want any sorting (faster).
The items in the menu are then presented in the order they were found
in the buffer.

139
Set it to `imenu--sort-by-name' if you want alphabetic sorting.
Richard M. Stallman's avatar
Richard M. Stallman committed
140

141
The function should take two arguments and return t if the first
Richard M. Stallman's avatar
Richard M. Stallman committed
142
element should come before the second.  The arguments are cons cells;
143
\(NAME . POSITION).  Look at `imenu--sort-by-name' for an example."
144
  :type '(choice (const :tag "No sorting" nil)
145
		 (const :tag "Sort by name" imenu--sort-by-name)
146
		 (function :tag "Another function"))
147
  :group 'imenu)
Richard M. Stallman's avatar
Richard M. Stallman committed
148

149
(defcustom imenu-max-items 25
Lute Kamstra's avatar
Lute Kamstra committed
150
  "Maximum number of elements in a mouse menu for Imenu."
151 152
  :type 'integer
  :group 'imenu)
Richard M. Stallman's avatar
Richard M. Stallman committed
153

154 155
;; No longer used.  KFS 2004-10-27
;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
Glenn Morris's avatar
Glenn Morris committed
156
;;   "Progress message during the index scanning of the buffer.
157 158 159 160 161 162 163 164
;; If non-nil, user gets a message during the scanning of the buffer.
;;
;; Relevant only if the mode-specific function that creates the buffer
;; index use `imenu-progress-message', and not useful if that is fast, in
;; which case you might as well set this to nil."
;;   :type '(choice string
;;  		 (const :tag "None" nil))
;;   :group 'imenu)
Richard M. Stallman's avatar
Richard M. Stallman committed
165

166
(defcustom imenu-space-replacement "."
Lute Kamstra's avatar
Lute Kamstra committed
167
  "The replacement string for spaces in index names.
168
Used when presenting the index in a completion buffer to make the
169
names work as tokens."
170
  :type '(choice string (const nil))
171
  :group 'imenu)
Richard M. Stallman's avatar
Richard M. Stallman committed
172

173
(defcustom imenu-level-separator ":"
Lute Kamstra's avatar
Lute Kamstra committed
174
  "The separator between index names of different levels.
Richard M. Stallman's avatar
Richard M. Stallman committed
175
Used for making mouse-menu titles and for flattening nested indexes
176 177 178
with name concatenation."
  :type 'string
  :group 'imenu)
Richard M. Stallman's avatar
Richard M. Stallman committed
179

180 181
(defcustom imenu-generic-skip-comments-and-strings t
  "When non-nil, ignore text inside comments and strings.
182 183 184
Only affects `imenu-default-create-index-function' (and any
alternative implementation of `imenu-create-index-function' that
uses `imenu--generic-function')."
185 186 187 188
  :type 'boolean
  :group 'imenu
  :version "24.4")

189
;;;###autoload
190
(defvar imenu-generic-expression nil
191 192 193 194 195 196 197 198 199 200 201
  "List of definition matchers for creating an Imenu index.
Each element of this list should have the form

  (MENU-TITLE REGEXP INDEX [FUNCTION] [ARGUMENTS...])

MENU-TITLE should be nil (in which case the matches for this
element are put in the top level of the buffer index) or a
string (which specifies the title of a submenu into which the
matches are put).
REGEXP is a regular expression matching a definition construct
which is to be displayed in the menu.  REGEXP may also be a
202 203 204
function of no arguments.  If REGEXP is a function, it is
expected to search backwards, return non-nil if it finds a
definition construct, and set `match-data' for that construct.
205 206 207 208 209 210 211 212 213 214 215
INDEX is an integer specifying which subexpression of REGEXP
matches the definition's name; this subexpression is displayed as
the menu item.
FUNCTION, if present, specifies a function to call when the index
item is selected by the user.  This function is called with
arguments consisting of the item name, the buffer position, and
the ARGUMENTS.

The variable `imenu-case-fold-search' determines whether or not
the regexp matches are case sensitive, and `imenu-syntax-alist'
can be used to alter the syntax table for the search.
216

217
If non-nil this pattern is passed to `imenu--generic-function' to
218
create a buffer index.
219

220
For example, see the value of `fortran-imenu-generic-expression'
221 222
used by `fortran-mode' with `imenu-syntax-alist' set locally so that
characters which normally have \"symbol\" syntax are considered to have
223
\"word\" syntax during matching.")
224
;;;###autoload(put 'imenu-generic-expression 'risky-local-variable t)
225

226
;;;###autoload
227
(make-variable-buffer-local 'imenu-generic-expression)
228

Richard M. Stallman's avatar
Richard M. Stallman committed
229 230
;;;; Hooks

231
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
232
(defvar imenu-create-index-function 'imenu-default-create-index-function
233
  "The function to use for creating an index alist of the current buffer.
Richard M. Stallman's avatar
Richard M. Stallman committed
234

235 236 237
It should be a function that takes no arguments and returns
an index alist of the current buffer.  The function is
called within a `save-excursion'.
238

239
See `imenu--index-alist' for the format of the buffer index alist.")
240
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
241 242
(make-variable-buffer-local 'imenu-create-index-function)

243
;;;###autoload
244
(defvar imenu-prev-index-position-function 'beginning-of-defun
Richard M. Stallman's avatar
Richard M. Stallman committed
245 246
  "Function for finding the next index position.

247 248
If `imenu-create-index-function' is set to
`imenu-default-create-index-function', then you must set this variable
Richard M. Stallman's avatar
Richard M. Stallman committed
249 250 251 252
to a function that will find the next index, looking backwards in the
file.

The function should leave point at the place to be connected to the
253
index and it should return nil when it doesn't find another index.")
254
;;;###autoload
255
(make-variable-buffer-local 'imenu-prev-index-position-function)
Richard M. Stallman's avatar
Richard M. Stallman committed
256

257
;;;###autoload
258
(defvar imenu-extract-index-name-function nil
259
  "Function for extracting the index item name, given a position.
260 261 262

This function is called after `imenu-prev-index-position-function'
finds a position for an index item, with point at that position.
263
It should return the name for that index item.")
264
;;;###autoload
265
(make-variable-buffer-local 'imenu-extract-index-name-function)
Richard M. Stallman's avatar
Richard M. Stallman committed
266

267 268 269 270 271 272 273 274 275 276
;;;###autoload
(defvar imenu-name-lookup-function nil
  "Function to compare string with index item.

This function will be called with two strings, and should return
non-nil if they match.

If nil, comparison is done with `string='.
Set this to some other function for more advanced comparisons,
such as \"begins with\" or \"name matches and number of
277
arguments match\".")
278 279 280
;;;###autoload
(make-variable-buffer-local 'imenu-name-lookup-function)

281
;;;###autoload
282 283 284
(defvar imenu-default-goto-function 'imenu-default-goto-function
  "The default function called when selecting an Imenu item.
The function in this variable is called when selecting a normal index-item.")
285
;;;###autoload
286 287 288
(make-variable-buffer-local 'imenu-default-goto-function)


289
(defun imenu--subalist-p (item)
290 291 292 293
  (and (consp item)
       (consp (cdr item))
       (listp (cadr item))
       (not (functionp (cadr item)))))
294

295 296 297 298 299 300
(defmacro imenu-progress-message (_prevpos &optional _relpos _reverse)
  "Macro to display a progress message.
RELPOS is the relative position to display.
If RELPOS is nil, then the relative position in the buffer
is calculated.
PREVPOS is the variable in which we store the last position displayed."
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

;; Made obsolete/empty, as computers are now faster than the eye, and
;; it had problems updating the messages correctly, and could shadow
;; more important messages/prompts in the minibuffer.  KFS 2004-10-27.

;;  `(and
;;    imenu-scanning-message
;;    (let ((pos ,(if relpos
;;		   relpos
;;		 `(imenu--relative-position ,reverse))))
;;	(if ,(if relpos t
;;	    `(> pos (+ 5 ,prevpos)))
;;	 (progn
;;	   (message imenu-scanning-message pos)
;;	   (setq ,prevpos pos)))))
)

318 319 320 321 322 323 324 325

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; Some examples of functions utilizing the framework of this
;;;; package.
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Glenn Morris's avatar
Glenn Morris committed
326 327 328
;; FIXME: This was the only imenu-example-* definition actually used,
;; by cperl-mode.el.  Now cperl-mode has its own copy, so these can
;; all be removed.
329
(defun imenu-example--name-and-position ()
330 331
  "Return the current/previous sexp and its (beginning) location.
Don't move point."
332
  (declare (obsolete "use your own function instead." "23.2"))
333 334
  (save-excursion
    (forward-sexp -1)
335 336 337
    ;; [ydi] modified for imenu-use-markers
    (let ((beg (if imenu-use-markers (point-marker) (point)))
	  (end (progn (forward-sexp) (point))))
338
      (cons (buffer-substring beg end)
339
	    beg))))
340 341 342

;;;
;;; Lisp
343
;;;
344

345 346 347 348 349 350
(define-error 'imenu-unavailable "imenu unavailable")

(defun imenu-unavailable-error (format &rest args)
  (signal 'imenu-unavailable
          (list (apply #'format-message format args))))

Richard M. Stallman's avatar
Richard M. Stallman committed
351 352 353 354 355 356 357 358 359 360
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Internal variables
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The item to use in the index for rescanning the buffer.
(defconst imenu--rescan-item '("*Rescan*" . -99))

;; The latest buffer index.
361
(defvar-local imenu--index-alist nil
362 363 364 365 366 367
  "The buffer index alist computed for this buffer in Imenu.

Simple elements in the alist look like (INDEX-NAME . POSITION).
POSITION is the buffer position of the item; to go to the item
is simply to move point to that position.

368 369 370 371 372 373 374 375
POSITION is passed to `imenu-default-goto-function', so it can be
a non-number if that variable has been changed (e.g. Semantic
uses overlays for POSITIONs).

Special elements look like
\(INDEX-NAME POSITION FUNCTION ARGUMENTS...).
To \"go to\" a special element means applying FUNCTION to
INDEX-NAME, POSITION, and the ARGUMENTS.
376

377
A nested sub-alist element looks like (INDEX-NAME . SUB-ALIST).
378 379 380 381
The function `imenu--subalist-p' tests an element and returns t
if it is a sub-alist.

There is one simple element with negative POSITION; selecting that
382
element recalculates the buffer's index alist.")
383
;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
384

385
(defvar-local imenu--last-menubar-index-alist nil
386
  "The latest buffer index alist used to update the menu bar menu.")
387

388 389
(defvar imenu--history-list nil
  ;; Making this buffer local caused it not to work!
390
  "History list for `jump-to-function-in-buffer'.")
Richard M. Stallman's avatar
Richard M. Stallman committed
391 392 393 394 395 396 397 398

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Internal support functions
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun imenu--sort-by-name (item1 item2)
399 400
  "Comparison function to sort items depending on their index name.
An item looks like (NAME . POSITION)."
Richard M. Stallman's avatar
Richard M. Stallman committed
401 402
  (string-lessp (car item1) (car item2)))

403
(defun imenu--sort-by-position (item1 item2)
404 405 406 407 408 409
  "Comparison function to sort items depending on their position.
Return non-nil if and only if ITEM1's position is lower than ITEM2's
position."
  (if (listp (cdr item1))
      (< (cadr item1) (cadr item2))
    (< (cdr item1) (cdr item2))))
410

Richard M. Stallman's avatar
Richard M. Stallman committed
411
(defun imenu--relative-position (&optional reverse)
412 413 414
  "Support function to calculate relative position in buffer.
Beginning of buffer is 0 and end of buffer is 100
If REVERSE is non-nil then the beginning is 100 and the end is 0."
Richard M. Stallman's avatar
Richard M. Stallman committed
415 416 417
  (let ((pos (point))
	(total (buffer-size)))
    (and reverse (setq pos (- total pos)))
418
    (floor (* 100.0 (1- pos)) (max total 1))))
Richard M. Stallman's avatar
Richard M. Stallman committed
419 420

(defun imenu--split (list n)
421
  "Split LIST into sublists of max length N.
422
Example (imenu--split \\='(1 2 3 4 5 6 7 8) 3) => ((1 2 3) (4 5 6) (7 8))
423
The returned list DOES NOT share structure with LIST."
Richard M. Stallman's avatar
Richard M. Stallman committed
424 425 426 427 428 429
  (let ((remain list)
	(result '())
	(sublist '())
	(i 0))
    (while remain
      (push (pop remain) sublist)
Stefan Monnier's avatar
Stefan Monnier committed
430
      (cl-incf i)
Richard M. Stallman's avatar
Richard M. Stallman committed
431 432 433 434 435 436 437 438 439 440 441 442
      (and (= i n)
	   ;; We have finished a sublist
	   (progn (push (nreverse sublist) result)
		  (setq i 0)
		  (setq sublist '()))))
    ;; There might be a sublist (if the length of LIST mod n is != 0)
    ;; that has to be added to the result list.
    (and sublist
	 (push (nreverse sublist) result))
    (nreverse result)))

(defun imenu--split-menu (menulist title)
443 444 445 446 447
  "Split the alist MENULIST into a nested alist, if it is long enough.
In any case, add TITLE to the front of the alist.
If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
beginning of the returned alist.
The returned alist DOES NOT share structure with MENULIST."
448
  (let ((menulist (copy-sequence menulist))
449
        keep-at-top)
450
    (if (memq imenu--rescan-item menulist)
451
	(setq keep-at-top (list imenu--rescan-item)
452
	      menulist (delq imenu--rescan-item menulist)))
453
    (dolist (item menulist)
454 455 456
      (when (imenu--subalist-p item)
	(push item keep-at-top)
	(setq menulist (delq item menulist))))
457
    (if imenu-sort-function
458
	(setq menulist (sort menulist imenu-sort-function)))
459
    (if (> (length menulist) imenu-max-items)
460 461 462 463 464
	(setq menulist
	      (mapcar
	       (lambda (menu)
		 (cons (format "From: %s" (caar menu)) menu))
	       (imenu--split menulist imenu-max-items))))
465 466
    (cons title
	  (nconc (nreverse keep-at-top) menulist))))
467 468

(defun imenu--split-submenus (alist)
469 470 471 472
  "Split up each long alist that are nested within ALIST into nested alists.
Return a split and sorted copy of ALIST.  The returned alist DOES
NOT share structure with ALIST."
  (mapcar (lambda (elt)
473
            (if (imenu--subalist-p elt)
474 475
                (imenu--split-menu (cdr elt) (car elt))
              elt))
476
	  alist))
Richard M. Stallman's avatar
Richard M. Stallman committed
477

478
(defun imenu--truncate-items (menulist)
479
  "Truncate all strings in MENULIST to `imenu-max-item-length'."
480
  (mapc (lambda (item)
481
	  ;; Truncate if necessary.
482 483 484 485 486 487
	  (when (and (numberp imenu-max-item-length)
		     (> (length (car item)) imenu-max-item-length))
	    (setcar item (substring (car item) 0 imenu-max-item-length)))
	  (when (imenu--subalist-p item)
	    (imenu--truncate-items (cdr item))))
	menulist))
488

489
(defun imenu--make-index-alist (&optional noerror)
490 491
  "Create an index alist for the definitions in the current buffer.
This works by using the hook function `imenu-create-index-function'.
492 493 494
Report an error if the list is empty unless NOERROR is supplied and
non-nil.

495
See `imenu--index-alist' for the format of the index alist."
496 497 498 499
  (or (and imenu--index-alist
	   (or (not imenu-auto-rescan)
	       (and imenu-auto-rescan
		    (> (buffer-size)  imenu-auto-rescan-maxout))))
500
      ;; Get the index; truncate if necessary.
501 502 503 504 505 506 507
      (progn
	(setq imenu--index-alist
	      (save-excursion
		(save-restriction
		  (widen)
		  (funcall imenu-create-index-function))))
	(imenu--truncate-items imenu--index-alist)))
508
  (or imenu--index-alist noerror
509 510
      (imenu-unavailable-error
       "No items suitable for an index found in this buffer"))
511 512
  (or imenu--index-alist
      (setq imenu--index-alist (list nil)))
513 514 515
  (unless imenu-auto-rescan
    ;; Add a rescan option to the index.
    (cons imenu--rescan-item imenu--index-alist)))
516

517
(defvar imenu--cleanup-seen nil)
518

519
(defun imenu--cleanup (&optional alist)
520 521 522
  "Find all markers in ALIST and make them point nowhere.
If ALIST is nil (the normal case), use `imenu--index-alist'.
Non-nil arguments are in recursive calls."
523
  ;; If alist is provided use that list.
524 525 526 527 528 529
  ;; If not, empty the table of lists already seen
  ;; and use imenu--index-alist.
  (if alist
      (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
    (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))

530 531 532 533 534 535 536 537
  (when alist
    (dolist (item alist)
      (cond
       ((markerp (cdr item)) (set-marker (cdr item) nil))
       ;; Don't process one alist twice.
       ((memq (cdr item) imenu--cleanup-seen))
       ((imenu--subalist-p item) (imenu--cleanup (cdr item)))))
    t))
538

539
(defun imenu--create-keymap (title alist &optional cmd)
Stefan Monnier's avatar
Stefan Monnier committed
540 541 542 543 544 545 546 547 548 549 550
  `(keymap ,title
           ,@(mapcar
              (lambda (item)
                `(,(car item) ,(car item)
                  ,@(cond
                     ((imenu--subalist-p item)
                      (imenu--create-keymap (car item) (cdr item) cmd))
                     (t
                      `(lambda () (interactive)
                         ,(if cmd `(,cmd ',item) (list 'quote item)))))))
              alist)))
551 552 553 554 555 556

(defun imenu--in-alist (str alist)
  "Check whether the string STR is contained in multi-level ALIST."
  (let (elt head tail res)
    (setq res nil)
    (while alist
557
      (setq elt (car alist)
558
	    tail (cdr elt)
559 560
	    alist (cdr alist)
	    head (car elt))
561 562 563 564
      ;; A nested ALIST element looks like
      ;;   (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
      ;; while a bottom-level element looks like
      ;;   (INDEX-NAME . INDEX-POSITION)
565 566
      ;; or
      ;;   (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
567
      ;; We are only interested in the bottom-level elements, so we need to
568 569
      ;; recurse if TAIL is a nested ALIST.
      (cond ((imenu--subalist-p elt)
570 571
	     (if (setq res (imenu--in-alist str tail))
		 (setq alist nil)))
572 573 574
	    ((if imenu-name-lookup-function
                 (funcall imenu-name-lookup-function str head)
               (string= str head))
575
	     (setq alist nil res elt))))
576 577
    res))

578
(defvar imenu-syntax-alist nil
579
  "Alist of syntax table modifiers to use while in `imenu--generic-function'.
580 581

The car of the assocs may be either a character or a string and the
Glenn Morris's avatar
Glenn Morris committed
582
cdr is a syntax description appropriate for `modify-syntax-entry'.  For
583 584 585
a string, all the characters in the string get the specified syntax.

This is typically used to give word syntax to characters which
Dave Love's avatar
Dave Love committed
586
normally have symbol syntax to simplify `imenu-expression'
587
and speed-up matching.")
588
;;;###autoload
589 590
(make-variable-buffer-local 'imenu-syntax-alist)

Richard M. Stallman's avatar
Richard M. Stallman committed
591
(defun imenu-default-create-index-function ()
Lute Kamstra's avatar
Lute Kamstra committed
592
  "Default function to create an index alist of the current buffer.
Richard M. Stallman's avatar
Richard M. Stallman committed
593

594
The most general method is to move point to end of buffer, then repeatedly call
595
`imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
596 597 598 599 600
All the results returned by the latter are gathered into an index alist.
This method is used if those two variables are non-nil.

The alternate method, which is the one most often used, is to call
`imenu--generic-function' with `imenu-generic-expression' as argument."
601 602
  ;; These should really be done by setting imenu-create-index-function
  ;; in these major modes.  But save that change for later.
603 604
  (cond ((and imenu-prev-index-position-function
	      imenu-extract-index-name-function)
605
	 (let ((index-alist '()) (pos (point-max))
606
	       name)
607
	   (goto-char pos)
608
	   ;; Search for the function
609
	   (while (funcall imenu-prev-index-position-function)
610
             (unless (< (point) pos)
611
               (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
612
             (setq pos (point))
613 614 615
	     (save-excursion
	       (setq name (funcall imenu-extract-index-name-function)))
	     (and (stringp name)
616 617 618
 		  ;; [ydi] Updated for imenu-use-markers.
		  (push (cons name
                              (if imenu-use-markers (point-marker) (point)))
619
			index-alist)))
620 621 622
	   index-alist))
	;; Use generic expression if possible.
	((and imenu-generic-expression)
623
	 (imenu--generic-function imenu-generic-expression))
624
	(t
625
         (imenu-unavailable-error "This buffer cannot use `imenu-default-create-index-function'"))))
Richard M. Stallman's avatar
Richard M. Stallman committed
626

627 628 629
;;;
;;; Generic index gathering function.
;;;
630

631 632 633
(defvar imenu-case-fold-search t
  "Defines whether `imenu--generic-function' should fold case when matching.

634
This variable should be set (only) by initialization code
635 636
for modes which use `imenu--generic-function'.  If it is not set, but
`font-lock-defaults' is set, then font-lock's setting is used.")
637
;;;###autoload
638 639
(make-variable-buffer-local 'imenu-case-fold-search)

640 641
;; This function can be called with quitting disabled,
;; so it needs to be careful never to loop!
642
(defun imenu--generic-function (patterns)
643
  "Return an index alist of the current buffer based on PATTERNS.
644
PATTERNS should be an alist of the same form as `imenu-generic-expression'.
645 646 647 648 649

If `imenu-generic-skip-comments-and-strings' is non-nil, this ignores
text inside comments and strings.

If `imenu-case-fold-search' is non-nil, this ignores case.
650

651
The return value is an alist of the form
652
 (INDEX-NAME . INDEX-POSITION)
653
or
654
 (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
655
The return value may also consist of nested index alists like:
656 657
 (INDEX-NAME . INDEX-ALIST)
depending on PATTERNS."
658
  (let ((index-alist (list 'dummy))
659 660 661 662
        (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
				  (not (local-variable-p 'font-lock-defaults)))
			      imenu-case-fold-search
			    (nth 2 font-lock-defaults)))
663 664 665 666
        (old-table (syntax-table))
        (table (copy-syntax-table (syntax-table)))
        (slist imenu-syntax-alist))
    ;; Modify the syntax table used while matching regexps.
667
    (dolist (syn slist)
668
      ;; The character(s) to modify may be a single char or a string.
669 670
      (if (numberp (car syn))
	  (modify-syntax-entry (car syn) (cdr syn) table)
671 672 673
        (mapc (lambda (c)
                (modify-syntax-entry c (cdr syn) table))
              (car syn))))
674
    (goto-char (point-max))
675
    (unwind-protect			; For syntax table.
676 677
	(save-match-data
	  (set-syntax-table table)
678

679 680
	  ;; Map over the elements of imenu-generic-expression
	  ;; (typically functions, variables ...).
681 682 683 684 685
	  (dolist (pat patterns)
	    (let ((menu-title (car pat))
		  (regexp (nth 1 pat))
		  (index (nth 2 pat))
		  (function (nth 3 pat))
686
		  (rest (nthcdr 4 pat))
687
		  start beg)
688 689
	      ;; Go backwards for convenience of adding items in order.
	      (goto-char (point-max))
690 691
	      (while (and (if (functionp regexp)
			      (funcall regexp)
692 693 694 695 696 697 698 699 700 701 702
			    (and
			     (re-search-backward regexp nil t)
			     ;; Do not count invisible definitions.
			     (let ((invis (invisible-p (point))))
			       (or (not invis)
				   (progn
				     (while (and invis
						 (not (bobp)))
				       (setq invis (not (re-search-backward
							 regexp nil 'move))))
				     (not invis))))))
703 704 705
			  ;; Exit the loop if we get an empty match,
			  ;; because it means a bad regexp was specified.
			  (not (= (match-beginning 0) (match-end 0))))
706
		(setq start (point))
707
		;; Record the start of the line in which the match starts.
708
		;; That's the official position of this definition.
709 710 711
		(goto-char (match-beginning index))
		(beginning-of-line)
		(setq beg (point))
712 713 714 715 716
		;; Add this sort of submenu only when we've found an
		;; item for it, avoiding empty, duff menus.
		(unless (assoc menu-title index-alist)
		  (push (list menu-title) index-alist))
		(if imenu-use-markers
717
		    (setq beg (copy-marker beg)))
718 719 720
		(let ((item
		       (if function
			   (nconc (list (match-string-no-properties index)
721
					beg function)
722 723
				  rest)
			 (cons (match-string-no-properties index)
724
			       beg)))
725 726 727 728
		      ;; This is the desired submenu,
		      ;; starting with its title (or nil).
		      (menu (assoc menu-title index-alist)))
		  ;; Insert the item unless it is already present.
729 730
		  (unless (or (member item (cdr menu))
                              (and imenu-generic-skip-comments-and-strings
731 732
                                   (save-excursion
                                     (goto-char start) (nth 8 (syntax-ppss)))))
733
		    (setcdr menu
734 735 736 737
			    (cons item (cdr menu)))))
		;; Go to the start of the match, to make sure we
		;; keep making progress backwards.
		(goto-char start))))
738
	  (set-syntax-table old-table)))
739 740
    ;; Sort each submenu by position.
    ;; This is in case one submenu gets items from two different regexps.
741 742 743
    (dolist (item index-alist)
      (when (listp item)
	(setcdr item (sort (cdr item) 'imenu--sort-by-position))))
744 745
    ;; Remove any empty menus.  That can happen because of skipping
    ;; things inside comments or strings.
746 747 748 749 750 751
    (setq index-alist (cl-delete-if
                       (lambda (it) (and (consp it) (null (cdr it))))
                       index-alist))
    (let ((main-element (assq nil index-alist)))
      (nconc (delq main-element (delq 'dummy index-alist))
             (cdr main-element)))))
752

Richard M. Stallman's avatar
Richard M. Stallman committed
753 754 755 756 757 758
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The main functions for this package!
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

759 760 761 762 763 764 765 766 767 768 769 770 771
;; See also info-lookup-find-item
(defun imenu-find-default (guess completions)
  "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
  (catch 'found
    (let ((case-fold-search t))
      (if (assoc guess completions) guess
	(dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
			  (concat "\\`" (regexp-quote guess))
			  (concat (regexp-quote guess) "\\'")
			  (regexp-quote guess)))
	  (dolist (x completions)
	    (if (string-match re (car x)) (throw 'found (car x)))))))))

Richard M. Stallman's avatar
Richard M. Stallman committed
772 773 774
(defun imenu--completion-buffer (index-alist &optional prompt)
  "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.

775
Return one of the entries in index-alist or nil."
Richard M. Stallman's avatar
Richard M. Stallman committed
776
  ;; Create a list for this buffer only when needed.
777 778 779
  (let ((name (thing-at-point 'symbol))
	choice
	(prepared-index-alist
780 781 782
	 (if (not imenu-space-replacement) index-alist
	   (mapcar
	    (lambda (item)
783
	      (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
784 785 786
					  (car item))
		    (cdr item)))
	    index-alist))))
787 788
    (when (stringp name)
      (setq name (or (imenu-find-default name prepared-index-alist) name)))
789 790 791 792
    (cond (prompt)
	  ((and name (imenu--in-alist name prepared-index-alist))
	   (setq prompt (format "Index item (default %s): " name)))
	  (t (setq prompt "Index item: ")))
793 794 795 796 797 798 799
    (let ((minibuffer-setup-hook minibuffer-setup-hook))
      ;; Display the completion buffer.
      (if (not imenu-eager-completion-buffer)
	  (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
      (setq name (completing-read prompt
				  prepared-index-alist
				  nil t nil 'imenu--history-list name)))
800

801 802 803 804 805
    (when (stringp name)
      (setq choice (assoc name prepared-index-alist))
      (if (imenu--subalist-p choice)
	  (imenu--completion-buffer (cdr choice) prompt)
	choice))))
806

Richard M. Stallman's avatar
Richard M. Stallman committed
807 808 809 810 811
(defun imenu--mouse-menu (index-alist event &optional title)
  "Let the user select from a buffer index from a mouse menu.

INDEX-ALIST is the buffer index and EVENT is a mouse event.

812
Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
813
  (setq index-alist (imenu--split-submenus index-alist))
814
  (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
815 816 817 818
	 (map (imenu--create-keymap (car menu)
				    (cdr (if (< 1 (length (cdr menu)))
					     menu
					   (car (cdr menu)))))))
819
    (popup-menu map event)))
Richard M. Stallman's avatar
Richard M. Stallman committed
820

Richard M. Stallman's avatar
Richard M. Stallman committed
821
(defun imenu-choose-buffer-index (&optional prompt alist)
Richard M. Stallman's avatar
Richard M. Stallman committed
822 823 824 825 826 827
  "Let the user select from a buffer index and return the chosen index.

If the user originally activated this function with the mouse, a mouse
menu is used.  Otherwise a completion buffer is used and the user is
prompted with PROMPT.

Richard M. Stallman's avatar
Richard M. Stallman committed
828 829 830
If you call this function with index alist ALIST, then it lets the user
select from ALIST.

831
With no index alist ALIST, it calls `imenu--make-index-alist' to
Richard M. Stallman's avatar
Richard M. Stallman committed
832 833
create the index alist.

834 835
If `imenu-use-popup-menu' is nil, then the completion buffer
is always used, no matter if the mouse was used or not.
Richard M. Stallman's avatar
Richard M. Stallman committed
836

837
The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
Richard M. Stallman's avatar
Richard M. Stallman committed
838
  (let (index-alist
839
	(mouse-triggered (listp last-nonmenu-event))
840
	(result t))
Richard M. Stallman's avatar
Richard M. Stallman committed
841 842 843
    ;; If selected by mouse, see to that the window where the mouse is
    ;; really is selected.
    (and mouse-triggered
844
	 (not (equal last-nonmenu-event '(menu-bar)))
845
	 (let ((window (posn-window (event-start last-nonmenu-event))))
846
	   (or (framep window) (null window) (select-window window))))
Richard M. Stallman's avatar
Richard M. Stallman committed
847 848
    ;; Create a list for this buffer only when needed.
    (while (eq result t)
Richard M. Stallman's avatar
Richard M. Stallman committed
849
      (setq index-alist (if alist alist (imenu--make-index-alist)))
Richard M. Stallman's avatar
Richard M. Stallman committed
850
      (setq result
851 852
	    (if (and imenu-use-popup-menu
		     (or (eq imenu-use-popup-menu t) mouse-triggered))
853
		(imenu--mouse-menu index-alist last-nonmenu-event)
Richard M. Stallman's avatar
Richard M. Stallman committed
854
	      (imenu--completion-buffer index-alist prompt)))
855
      (and (equal result imenu--rescan-item)
856
	   (imenu--cleanup)
857
	   (setq result t imenu--index-alist nil)))
Richard M. Stallman's avatar
Richard M. Stallman committed
858 859
    result))

860