Use new form of calendar-read-date.
[emacs.git] / lisp / imenu.el
blob80b31229ee434db614ec2ec4c43b2965da15a101
1 ;;; imenu.el --- Framework for mode-specific buffer indexes.
3 ;; Copyright (C) 1994 Free Software Foundation, Inc.
5 ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
6 ;; Lars Lindberg <lli@sypro.cap.se>
7 ;; Created: 8 Feb 1994
8 ;; Version: 1.12
9 ;; Keywords: tools
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program; if not, write to the Free Software
23 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 ;;; Commentary:
27 ;; Purpose of this package:
28 ;; To present a framework for mode-specific buffer indexes.
29 ;; A buffer index is an alist of names and buffer positions.
30 ;; For instance all functions in a C-file and their positions.
32 ;; How it works:
34 ;; A mode-specific function is called to generate the index. It is
35 ;; then presented to the user, who can choose from this index.
37 ;; The package comes with a set of example functions for how to
38 ;; utilize this package.
40 ;; There are *examples* for index gathering functions for C/C++ and
41 ;; Lisp/Emacs Lisp but it is easy to customize for other modes. A
42 ;; function for jumping to the chosen index position is also
43 ;; supplied.
45 ;;; Thanks goes to
46 ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
47 ;; [dean] - Dean Andrews ada@unison.com
48 ;; [alon] - Alon Albert al@mercury.co.il
49 ;; [greg] - Greg Thompson gregt@porsche.visix.COM
51 ;;; Code
52 (eval-when-compile (require 'cl))
54 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
55 ;;;
56 ;;; Customizable variables
57 ;;;
58 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
60 (defvar imenu-always-use-completion-buffer-p nil
61 "*Set this to non-nil for displaying the index in a completion buffer.
63 Non-nil means always display the index in a completion buffer.
64 Nil means display the index as a mouse menu when the mouse was
65 used to invoke `imenu'.")
67 (defvar imenu-sort-function nil
68 "*The function to use for sorting the index mouse-menu.
70 Affects only the mouse index menu.
72 Set this to nil if you don't want any sorting (faster).
73 The items in the menu are then presented in the order they were found
74 in the buffer.
76 Set it to `imenu--sort-by-name' if you want alphabetic sorting.
78 The function should take two arguments and return T if the first
79 element should come before the second. The arguments are cons cells;
80 \(NAME . POSITION). Look at `imenu--sort-by-name' for an example.")
82 (defvar imenu-max-items 25
83 "*Maximum number of elements in an index mouse-menu.")
85 (defvar imenu-scanning-message "Scanning buffer for index. (%3d%%)"
86 "*Progress message during the index scanning of the buffer.
87 If non-nil, user gets a message during the scanning of the buffer
89 Relevant only if the mode-specific function that creates the buffer
90 index use `imenu-progress-message'.")
92 (defvar imenu-space-replacement "^"
93 "*The replacement string for spaces in index names.
94 Used when presenting the index in a completion-buffer to make the
95 names work as tokens.")
97 (defvar imenu-level-separator ":"
98 "*The separator between index names of different levels.
99 Used for making mouse-menu titles and for flattening nested indexes
100 with name concatenation.")
102 (defvar imenu-submenu-name-format "%s..."
103 "*The format for making a submenu name.")
105 ;;;; Hooks
107 (defvar imenu-create-index-function 'imenu-default-create-index-function
108 "The function to use for creating a buffer index.
110 It should be a function that takes no arguments and returns an index
111 of the current buffer as an alist. The elements in the alist look
112 like: (INDEX-NAME . INDEX-POSITION). You may also nest index list like
113 \(INDEX-NAME . INDEX-ALIST).
115 This function is called within a `save-excursion'.
117 The variable is buffer-local.")
118 (make-variable-buffer-local 'imenu-create-index-function)
120 (defvar imenu-prev-index-position-function 'beginning-of-defun
121 "Function for finding the next index position.
123 If `imenu-create-index-function' is set to
124 `imenu-default-create-index-function', then you must set this variable
125 to a function that will find the next index, looking backwards in the
126 file.
128 The function should leave point at the place to be connected to the
129 index and it should return nil when it doesn't find another index. ")
130 (make-variable-buffer-local 'imenu-prev-index-position-function)
132 (defvar imenu-extract-index-name-function nil
133 "Function for extracting the index name.
135 This function is called after the function pointed out by
136 `imenu-prev-index-position-function'.")
137 (make-variable-buffer-local 'imenu-extract-index-name-function)
139 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
141 ;;; Internal variables
143 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
145 ;; The item to use in the index for rescanning the buffer.
146 (defconst imenu--rescan-item '("*Rescan*" . -99))
148 ;; The latest buffer index.
149 ;; Buffer local.
150 (defvar imenu--index-alist nil)
151 (make-variable-buffer-local 'imenu--index-alist)
153 ;; History list for 'jump-to-function-in-buffer'.
154 ;; Buffer local.
155 (defvar imenu--history-list nil)
156 (make-variable-buffer-local 'imenu--history-list)
158 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
160 ;;; Internal support functions
162 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
165 ;;; Sort function
166 ;;; Sorts the items depending on their index name.
167 ;;; An item look like (NAME . POSITION).
169 (defun imenu--sort-by-name (item1 item2)
170 (string-lessp (car item1) (car item2)))
172 (defun imenu--relative-position (&optional reverse)
173 ;; Support function to calculate relative position in buffer
174 ;; Beginning of buffer is 0 and end of buffer is 100
175 ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
176 (let ((pos (point))
177 (total (buffer-size)))
178 (and reverse (setq pos (- total pos)))
179 (if (> total 50000)
180 ;; Avoid overflow from multiplying by 100!
181 (/ (1- pos) (max (/ total 100) 1))
182 (/ (* 100 (1- pos)) (max total 1)))))
185 ;;; Macro to display a progress message.
186 ;;; RELPOS is the relative position to display.
187 ;;; If RELPOS is nil, then the relative position in the buffer
188 ;;; is calculated.
189 ;;; PREVPOS is the variable in which we store the last position displayed.
190 (defmacro imenu-progress-message (prevpos &optional relpos reverse)
191 (` (and
192 imenu-scanning-message
193 (let ((pos (, (if relpos
194 relpos
195 (` (imenu--relative-position (, reverse)))))))
196 (if (, (if relpos t
197 (` (> pos (+ 5 (, prevpos))))))
198 (progn
199 (message imenu-scanning-message pos)
200 (setq (, prevpos) pos)))))))
203 ;;; Function for suporting general looking submenu names.
204 ;;; Uses `imenu-submenu-name-format' for creating the name.
205 ;;; NAME is the base of the new submenu name.
207 (defun imenu-create-submenu-name (name)
208 (format imenu-submenu-name-format name))
210 ;; Split LIST into sublists of max length N.
211 ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
212 (defun imenu--split (list n)
213 (let ((remain list)
214 (result '())
215 (sublist '())
216 (i 0))
217 (while remain
218 (push (pop remain) sublist)
219 (incf i)
220 (and (= i n)
221 ;; We have finished a sublist
222 (progn (push (nreverse sublist) result)
223 (setq i 0)
224 (setq sublist '()))))
225 ;; There might be a sublist (if the length of LIST mod n is != 0)
226 ;; that has to be added to the result list.
227 (and sublist
228 (push (nreverse sublist) result))
229 (nreverse result)))
232 ;;; Split a menu in to several menus.
234 (defun imenu--split-menu (menulist title)
235 (cons "Function menus"
236 (mapcar
237 (function
238 (lambda (menu)
239 (cons (format "(%s)" title) menu)))
240 (imenu--split menulist imenu-max-items))))
243 ;;; Find all items in this buffer that should be in the index.
244 ;;; Returns an alist on the form
245 ;;; ((NAME . POSITION) (NAME . POSITION) ...)
248 (defun imenu--make-index-alist ()
249 ;; Create a list for this buffer only when needed.
250 (or imenu--index-alist
251 ;; Get the index
252 (setq imenu--index-alist
253 (save-excursion
254 (funcall imenu-create-index-function))))
255 (or imenu--index-alist
256 (error "No items suitable for an index found in this buffer."))
257 ;; Add a rescan option to the index.
258 (cons imenu--rescan-item imenu--index-alist))
260 ;;; Find all markers in alist and makes
261 ;;; them point nowhere.
263 (defun imenu--cleanup (&optional alist)
264 ;; Sets the markers in imenu--index-alist
265 ;; point nowhere.
266 ;; if alist is provided use that list.
267 (and imenu--index-alist
268 (mapcar
269 (function
270 (lambda (item)
271 (cond
272 ((markerp (cdr item))
273 (set-marker (cdr item) nil))
274 ((listp (cdr item))
275 (imenu--cleanup (cdr item))))))
276 (if alist alist imenu--index-alist))
278 (defun imenu-default-create-index-function ()
279 "*Wrapper for index searching functions.
281 Moves point to end of buffer and then repeatedly calls
282 `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
283 Their results are gathered into an index alist."
284 ;; These should really be done by setting imenu-create-index-function
285 ;; in these major modes. But save that change for later.
286 (cond ((eq major-mode 'emacs-lisp-mode)
287 (imenu-example--create-lisp-index))
288 ((eq major-mode 'lisp-mode)
289 (imenu-example--create-lisp-index))
290 ((eq major-mode 'c++-mode)
291 (imenu-example--create-c++-index))
292 ((eq major-mode 'c-mode)
293 (imenu-example--create-c-index))
295 (or (and (fboundp imenu-prev-index-position-function)
296 (fboundp imenu-extract-index-name-function))
297 (error "The mode \"%s\" does not take full advantage of imenu.el yet."
298 mode-name))
299 (let ((index-alist '())
300 name prev-pos)
301 (goto-char (point-max))
302 (imenu-progress-message prev-pos 0 t)
303 ;; Search for the function
304 (while (funcall imenu-prev-index-position-function)
305 (imenu-progress-message prev-pos nil t)
306 (save-excursion
307 (setq name (funcall imenu-extract-index-name-function)))
308 (and (stringp name)
309 (push (cons name (point)) index-alist)))
310 (imenu-progress-message prev-pos 100 t)
311 index-alist))))
313 (defun imenu--replace-spaces (name replacement)
314 ;; Replace all spaces in NAME with REPLACEMENT.
315 ;; That second argument should be a string.
316 (mapconcat
317 (function
318 (lambda (ch)
319 (if (char-equal ch ?\ )
320 replacement
321 (char-to-string ch))))
322 name
323 ""))
325 (defun imenu--flatten-index-alist (index-alist &optional concat-names prefix)
326 ;; Takes a nested INDEX-ALIST and returns a flat index alist.
327 ;; If optional CONCAT-NAMES is non-nil, then a nested index has its
328 ;; name and a space concatenated to the names of the children.
329 ;; Third argument PREFIX is for internal use only.
330 (mapcan
331 (function
332 (lambda (item)
333 (let* ((name (car item))
334 (pos (cdr item))
335 (new-prefix (and concat-names
336 (if prefix
337 (concat prefix imenu-level-separator name)
338 name))))
339 (cond
340 ((or (markerp pos) (numberp pos))
341 (list (cons new-prefix pos)))
343 (imenu--flatten-index-alist pos new-prefix))))))
344 index-alist))
346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
348 ;;; The main functions for this package!
350 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
352 (defun imenu--completion-buffer (index-alist &optional prompt)
353 "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
355 Returns t for rescan and otherwise a position number."
356 ;; Create a list for this buffer only when needed.
357 (let (name choice
358 (prepared-index-alist
359 (mapcar
360 (function
361 (lambda (item)
362 (cons (imenu--replace-spaces (car item) imenu-space-replacement)
363 (cdr item))))
364 index-alist)))
365 (save-window-excursion
366 ;; Display the completion buffer
367 (with-output-to-temp-buffer "*Completions*"
368 (display-completion-list
369 (all-completions "" prepared-index-alist )))
370 (let ((minibuffer-setup-hook
371 (function (lambda ()
372 (let ((buffer (current-buffer)))
373 (save-excursion
374 (set-buffer "*Completions*")
375 (setq completion-reference-buffer buffer)))))))
376 ;; Make a completion question
377 (setq name (completing-read (or prompt "Index item: ")
378 prepared-index-alist
379 nil t nil 'imenu--history-list))))
380 (cond ((not (stringp name))
381 nil)
382 ((string= name (car imenu--rescan-item))
385 (setq choice (assoc name prepared-index-alist))
386 (if (listp (cdr choice))
387 (imenu--completion-buffer (cdr choice) prompt)
388 choice)))))
390 (defun imenu--mouse-menu (index-alist event &optional title)
391 "Let the user select from a buffer index from a mouse menu.
393 INDEX-ALIST is the buffer index and EVENT is a mouse event.
395 Returns t for rescan and otherwise a position number."
396 (let* ((menu (imenu--split-menu
397 (if imenu-sort-function
398 (sort
399 (let ((res nil)
400 (oldlist index-alist))
401 ;; Copy list method from the cl package `copy-list'
402 (while (consp oldlist) (push (pop oldlist) res))
403 (prog1 (nreverse res) (setcdr res oldlist)))
404 imenu-sort-function)
405 index-alist)
406 (or title (buffer-name))))
407 position)
408 (setq position (x-popup-menu event menu))
409 (cond
410 ((eq position nil)
411 position)
412 ((listp position)
413 (imenu--mouse-menu position event
414 (if title
415 (concat title imenu-level-separator
416 (car (rassq position index-alist)))
417 (car (rassq position index-alist)))))
418 ((= position (cdr imenu--rescan-item))
421 (rassq position index-alist)))))
423 (defun imenu-choose-buffer-index (&optional prompt alist)
424 "Let the user select from a buffer index and return the chosen index.
426 If the user originally activated this function with the mouse, a mouse
427 menu is used. Otherwise a completion buffer is used and the user is
428 prompted with PROMPT.
430 If you call this function with index alist ALIST, then it lets the user
431 select from ALIST.
433 With no index alist ALIST, it calls `imenu--make-index-alist' to
434 create the index alist.
436 If `imenu-always-use-completion-buffer-p' is non-nil, then the
437 completion buffer is always used, no matter if the mouse was used or
438 not.
440 The returned value is on the form (INDEX-NAME . INDEX-POSITION)."
441 (let (index-alist
442 (mouse-triggered (listp last-nonmenu-event))
443 (result t) )
444 ;; If selected by mouse, see to that the window where the mouse is
445 ;; really is selected.
446 (and mouse-triggered
447 (let ((window (posn-window (event-start last-nonmenu-event))))
448 (or (framep window) (select-window window))))
449 ;; Create a list for this buffer only when needed.
450 (while (eq result t)
451 (setq index-alist (if alist alist (imenu--make-index-alist)))
452 (setq result
453 (if (and mouse-triggered
454 (not imenu-always-use-completion-buffer-p))
455 (imenu--mouse-menu index-alist last-nonmenu-event)
456 (imenu--completion-buffer index-alist prompt)))
457 (and (eq result t)
458 (imenu--cleanup)
459 (setq imenu--index-alist nil)))
460 result))
462 (defun imenu-add-to-menubar (name)
463 "Adds an \"imenu\" entry to the menubar for the
464 current local keymap.
465 NAME is the string naming the menu to be added.
466 See 'imenu' for more information."
467 (interactive "sMenu name: ")
468 (and window-system
469 (define-key (current-local-map) [menu-bar index]
470 (cons name 'imenu))))
472 ;;;###autoload
473 (defun imenu ()
474 "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
475 See `imenu-choose-buffer-index' for more information."
476 (interactive)
477 (let ((index-item (imenu-choose-buffer-index)))
478 (and index-item
479 (progn
480 (push-mark)
481 (cond
482 ((markerp (cdr index-item))
483 (goto-char (marker-position (cdr index-item))))
485 (goto-char (cdr index-item))))))))
488 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
489 ;;;;
490 ;;;; Some examples of functions utilizing the framework of this
491 ;;;; package.
492 ;;;;
493 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
495 ;; Return the current/previous sexp and the location of the sexp (its
496 ;; beginning) without moving the point.
497 (defun imenu-example--name-and-position ()
498 (save-excursion
499 (forward-sexp -1)
500 (let ((beg (point))
501 (end (progn (forward-sexp) (point)))
502 (marker (make-marker)))
503 (set-marker marker beg)
504 (cons (buffer-substring beg end)
505 marker))))
508 ;;; Lisp
509 ;;;
511 (defun imenu-example--lisp-extract-index-name ()
512 ;; Example of a candidate for `imenu-extract-index-name-function'.
513 ;; This will generate a flat index of definitions in a lisp file.
514 (save-match-data
515 (and (looking-at "(def")
516 (condition-case nil
517 (progn
518 (down-list 1)
519 (forward-sexp 2)
520 (let ((beg (point))
521 (end (progn (forward-sexp -1) (point))))
522 (buffer-substring beg end)))
523 (error nil)))))
525 (defun imenu-example--create-lisp-index ()
526 ;; Example of a candidate for `imenu-create-index-function'.
527 ;; It will generate a nested index of definitions.
528 (let ((index-alist '())
529 (index-var-alist '())
530 (index-type-alist '())
531 (index-unknown-alist '())
532 prev-pos)
533 (goto-char (point-max))
534 (imenu-progress-message prev-pos 0)
535 ;; Search for the function
536 (while (beginning-of-defun)
537 (imenu-progress-message prev-pos nil t)
538 (save-match-data
539 (and (looking-at "(def")
540 (save-excursion
541 (down-list 1)
542 (cond
543 ((looking-at "def\\(var\\|const\\)")
544 (forward-sexp 2)
545 (push (imenu-example--name-and-position)
546 index-var-alist))
547 ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
548 (forward-sexp 2)
549 (push (imenu-example--name-and-position)
550 index-alist))
551 ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
552 (forward-sexp 2)
553 (if (= (char-after (1- (point))) ?\))
554 (progn
555 (forward-sexp -1)
556 (down-list 1)
557 (forward-sexp 1)))
558 (push (imenu-example--name-and-position)
559 index-type-alist))
561 (forward-sexp 2)
562 (push (imenu-example--name-and-position)
563 index-unknown-alist)))))))
564 (imenu-progress-message prev-pos 100)
565 (and index-var-alist
566 (push (cons (imenu-create-submenu-name "Variables") index-var-alist)
567 index-alist))
568 (and index-type-alist
569 (push (cons (imenu-create-submenu-name "Types") index-type-alist)
570 index-alist))
571 (and index-unknown-alist
572 (push (cons (imenu-create-submenu-name "Syntax-unknown") index-unknown-alist)
573 index-alist))
574 index-alist))
578 ;;; C
580 ;; Regular expression to find C functions
581 (defvar imenu-example--function-name-regexp-c
582 (concat
583 "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
584 "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
585 "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
586 "\\([*&]+[ \t]*\\)?" ; pointer
587 "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
590 (defun imenu-example--create-c-index (&optional regexp)
591 (let ((index-alist '())
592 prev-pos char)
593 (goto-char (point-min))
594 (imenu-progress-message prev-pos 0)
595 ;; Search for the function
596 (save-match-data
597 (while (re-search-forward
598 (or regexp imenu-example--function-name-regexp-c)
599 nil t)
600 (imenu-progress-message prev-pos)
601 (backward-up-list 1)
602 (save-excursion
603 (goto-char (scan-sexps (point) 1))
604 (setq char (following-char)))
605 ;; Skip this function name if it is a prototype declaration.
606 (if (not (eq char ?\;))
607 (push (imenu-example--name-and-position) index-alist))))
608 (imenu-progress-message prev-pos 100)
609 (nreverse index-alist)))
611 ;;;
612 ;;; C++
613 ;;;
614 ;; Regular expression to find C++ functions
615 (defvar imenu-example--function-name-regexp-c++
616 (concat
617 "^[a-zA-Z0-9:]+[ \t]?" ; type specs; there can be no
618 "\\([a-zA-Z0-9_:~*]+[ \t]+\\)?" ; more than 3 tokens, right?
619 "\\([a-zA-Z0-9_:~*]+[ \t]+\\)?"
620 "\\([*&]+[ \t]*\\)?" ; pointer
621 "\\([a-zA-Z0-9_:*]+\\)[ \t]*(" ; name
623 (defun imenu-example--create-c++-index ()
624 (imenu-example--create-c-index imenu-example--function-name-regexp-c++))
626 (provide 'imenu)
628 ;;; imenu.el ends here