imenu.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. ;;; imenu.el --- framework for mode-specific buffer indexes
  2. ;; Copyright (C) 1994-1998, 2001-2012 Free Software Foundation, Inc.
  3. ;; Author: Ake Stenhoff <etxaksf@aom.ericsson.se>
  4. ;; Lars Lindberg <lli@sypro.cap.se>
  5. ;; Maintainer: FSF
  6. ;; Created: 8 Feb 1994
  7. ;; Keywords: tools convenience
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; Purpose of this package:
  21. ;; To present a framework for mode-specific buffer indexes.
  22. ;; A buffer index is an alist of names and buffer positions.
  23. ;; For instance all functions in a C-file and their positions.
  24. ;;
  25. ;; It is documented in the Emacs Lisp manual.
  26. ;;
  27. ;; How it works:
  28. ;; A mode-specific function is called to generate the index. It is
  29. ;; then presented to the user, who can choose from this index.
  30. ;;
  31. ;; The package comes with a set of example functions for how to
  32. ;; utilize this package.
  33. ;; There are *examples* for index gathering functions/regular
  34. ;; expressions for C/C++ and Lisp/Emacs Lisp but it is easy to
  35. ;; customize for other modes. A function for jumping to the chosen
  36. ;; index position is also supplied.
  37. ;;; History:
  38. ;; Thanks go to
  39. ;; [simon] - Simon Leinen simon@lia.di.epfl.ch
  40. ;; [dean] - Dean Andrews ada@unison.com
  41. ;; [alon] - Alon Albert al@mercury.co.il
  42. ;; [greg] - Greg Thompson gregt@porsche.visix.COM
  43. ;; [wolfgang] - Wolfgang Bangerth zcg51122@rpool1.rus.uni-stuttgart.de
  44. ;; [kai] - Kai Grossjohann grossjoh@linus.informatik.uni-dortmund.de
  45. ;; [david] - David M. Smith dsmith@stats.adelaide.edu.au
  46. ;; [christian] - Christian Egli Christian.Egli@hcsd.hac.com
  47. ;; [karl] - Karl Fogel kfogel@floss.life.uiuc.edu
  48. ;;; Code:
  49. (eval-when-compile (require 'cl))
  50. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  51. ;;;
  52. ;;; Customizable variables
  53. ;;;
  54. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  55. (defgroup imenu nil
  56. "Mode-specific buffer indexes."
  57. :group 'matching
  58. :group 'frames
  59. :group 'convenience
  60. :link '(custom-manual "(elisp)Imenu"))
  61. (defcustom imenu-use-markers t
  62. "Non-nil means use markers instead of integers for Imenu buffer positions.
  63. Setting this to nil makes Imenu work a little faster but editing the
  64. buffer will make the generated index positions wrong.
  65. This might not yet be honored by all index-building functions."
  66. :type 'boolean
  67. :group 'imenu)
  68. (defcustom imenu-max-item-length 60
  69. "If a number, truncate Imenu entries to that length."
  70. :type '(choice integer
  71. (const :tag "Unlimited"))
  72. :group 'imenu)
  73. (defcustom imenu-auto-rescan nil
  74. "Non-nil means Imenu should always rescan the buffers."
  75. :type 'boolean
  76. :group 'imenu)
  77. (defcustom imenu-auto-rescan-maxout 60000
  78. "Imenu auto-rescan is disabled in buffers larger than this size (in bytes).
  79. This variable is buffer-local."
  80. :type 'integer
  81. :group 'imenu)
  82. (defvar imenu-always-use-completion-buffer-p nil)
  83. (make-obsolete-variable 'imenu-always-use-completion-buffer-p
  84. 'imenu-use-popup-menu "22.1")
  85. (defcustom imenu-use-popup-menu
  86. (if imenu-always-use-completion-buffer-p
  87. (not (eq imenu-always-use-completion-buffer-p 'never))
  88. 'on-mouse)
  89. "Use a popup menu rather than a minibuffer prompt.
  90. If nil, always use a minibuffer prompt.
  91. If t, always use a popup menu,
  92. If `on-mouse' use a popup menu when `imenu' was invoked with the mouse."
  93. :type '(choice (const :tag "On Mouse" on-mouse)
  94. (const :tag "Never" nil)
  95. (other :tag "Always" t))
  96. :group 'imenu)
  97. (defcustom imenu-eager-completion-buffer
  98. (not (eq imenu-always-use-completion-buffer-p 'never))
  99. "If non-nil, eagerly popup the completion buffer."
  100. :type 'boolean
  101. :group 'imenu
  102. :version "22.1")
  103. (defcustom imenu-after-jump-hook nil
  104. "Hooks called after jumping to a place in the buffer.
  105. Useful things to use here include `reposition-window', `recenter', and
  106. \(lambda () (recenter 0)) to show at top of screen."
  107. :type 'hook
  108. :group 'imenu)
  109. ;;;###autoload
  110. (defcustom imenu-sort-function nil
  111. "The function to use for sorting the index mouse-menu.
  112. Affects only the mouse index menu.
  113. Set this to nil if you don't want any sorting (faster).
  114. The items in the menu are then presented in the order they were found
  115. in the buffer.
  116. Set it to `imenu--sort-by-name' if you want alphabetic sorting.
  117. The function should take two arguments and return t if the first
  118. element should come before the second. The arguments are cons cells;
  119. \(NAME . POSITION). Look at `imenu--sort-by-name' for an example."
  120. :type '(choice (const :tag "No sorting" nil)
  121. (const :tag "Sort by name" imenu--sort-by-name)
  122. (function :tag "Another function"))
  123. :group 'imenu)
  124. (defcustom imenu-max-items 25
  125. "Maximum number of elements in a mouse menu for Imenu."
  126. :type 'integer
  127. :group 'imenu)
  128. ;; No longer used. KFS 2004-10-27
  129. ;; (defcustom imenu-scanning-message "Scanning buffer for index (%3d%%)"
  130. ;; "Progress message during the index scanning of the buffer.
  131. ;; If non-nil, user gets a message during the scanning of the buffer.
  132. ;;
  133. ;; Relevant only if the mode-specific function that creates the buffer
  134. ;; index use `imenu-progress-message', and not useful if that is fast, in
  135. ;; which case you might as well set this to nil."
  136. ;; :type '(choice string
  137. ;; (const :tag "None" nil))
  138. ;; :group 'imenu)
  139. (defcustom imenu-space-replacement "."
  140. "The replacement string for spaces in index names.
  141. Used when presenting the index in a completion buffer to make the
  142. names work as tokens."
  143. :type '(choice string (const nil))
  144. :group 'imenu)
  145. (defcustom imenu-level-separator ":"
  146. "The separator between index names of different levels.
  147. Used for making mouse-menu titles and for flattening nested indexes
  148. with name concatenation."
  149. :type 'string
  150. :group 'imenu)
  151. ;;;###autoload
  152. (defvar imenu-generic-expression nil
  153. "The regex pattern to use for creating a buffer index.
  154. If non-nil this pattern is passed to `imenu--generic-function' to
  155. create a buffer index. Look there for the documentation of this
  156. pattern's structure.
  157. For example, see the value of `fortran-imenu-generic-expression' used by
  158. `fortran-mode' with `imenu-syntax-alist' set locally to give the
  159. characters which normally have \"symbol\" syntax \"word\" syntax
  160. during matching.")
  161. ;;;###autoload(put 'imenu-generic-expression 'risky-local-variable t)
  162. ;;;###autoload
  163. (make-variable-buffer-local 'imenu-generic-expression)
  164. ;;;; Hooks
  165. ;;;###autoload
  166. (defvar imenu-create-index-function 'imenu-default-create-index-function
  167. "The function to use for creating an index alist of the current buffer.
  168. It should be a function that takes no arguments and returns
  169. an index alist of the current buffer. The function is
  170. called within a `save-excursion'.
  171. See `imenu--index-alist' for the format of the buffer index alist.")
  172. ;;;###autoload
  173. (make-variable-buffer-local 'imenu-create-index-function)
  174. ;;;###autoload
  175. (defvar imenu-prev-index-position-function 'beginning-of-defun
  176. "Function for finding the next index position.
  177. If `imenu-create-index-function' is set to
  178. `imenu-default-create-index-function', then you must set this variable
  179. to a function that will find the next index, looking backwards in the
  180. file.
  181. The function should leave point at the place to be connected to the
  182. index and it should return nil when it doesn't find another index.")
  183. ;;;###autoload
  184. (make-variable-buffer-local 'imenu-prev-index-position-function)
  185. ;;;###autoload
  186. (defvar imenu-extract-index-name-function nil
  187. "Function for extracting the index item name, given a position.
  188. This function is called after `imenu-prev-index-position-function'
  189. finds a position for an index item, with point at that position.
  190. It should return the name for that index item.")
  191. ;;;###autoload
  192. (make-variable-buffer-local 'imenu-extract-index-name-function)
  193. ;;;###autoload
  194. (defvar imenu-name-lookup-function nil
  195. "Function to compare string with index item.
  196. This function will be called with two strings, and should return
  197. non-nil if they match.
  198. If nil, comparison is done with `string='.
  199. Set this to some other function for more advanced comparisons,
  200. such as \"begins with\" or \"name matches and number of
  201. arguments match\".")
  202. ;;;###autoload
  203. (make-variable-buffer-local 'imenu-name-lookup-function)
  204. ;;;###autoload
  205. (defvar imenu-default-goto-function 'imenu-default-goto-function
  206. "The default function called when selecting an Imenu item.
  207. The function in this variable is called when selecting a normal index-item.")
  208. ;;;###autoload
  209. (make-variable-buffer-local 'imenu-default-goto-function)
  210. (defun imenu--subalist-p (item)
  211. (and (consp (cdr item)) (listp (cadr item))
  212. (not (eq (car (cadr item)) 'lambda))))
  213. ;; Macro to display a progress message.
  214. ;; RELPOS is the relative position to display.
  215. ;; If RELPOS is nil, then the relative position in the buffer
  216. ;; is calculated.
  217. ;; PREVPOS is the variable in which we store the last position displayed.
  218. (defmacro imenu-progress-message (prevpos &optional relpos reverse)
  219. ;; Made obsolete/empty, as computers are now faster than the eye, and
  220. ;; it had problems updating the messages correctly, and could shadow
  221. ;; more important messages/prompts in the minibuffer. KFS 2004-10-27.
  222. ;; `(and
  223. ;; imenu-scanning-message
  224. ;; (let ((pos ,(if relpos
  225. ;; relpos
  226. ;; `(imenu--relative-position ,reverse))))
  227. ;; (if ,(if relpos t
  228. ;; `(> pos (+ 5 ,prevpos)))
  229. ;; (progn
  230. ;; (message imenu-scanning-message pos)
  231. ;; (setq ,prevpos pos)))))
  232. )
  233. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  234. ;;;;
  235. ;;;; Some examples of functions utilizing the framework of this
  236. ;;;; package.
  237. ;;;;
  238. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  239. ;; FIXME: This was the only imenu-example-* definition actually used,
  240. ;; by cperl-mode.el. Now cperl-mode has its own copy, so these can
  241. ;; all be removed.
  242. (defun imenu-example--name-and-position ()
  243. "Return the current/previous sexp and its (beginning) location.
  244. Don't move point."
  245. (save-excursion
  246. (forward-sexp -1)
  247. ;; [ydi] modified for imenu-use-markers
  248. (let ((beg (if imenu-use-markers (point-marker) (point)))
  249. (end (progn (forward-sexp) (point))))
  250. (cons (buffer-substring beg end)
  251. beg))))
  252. (make-obsolete 'imenu-example--name-and-position
  253. "use your own function instead." "23.2")
  254. ;;;
  255. ;;; Lisp
  256. ;;;
  257. (defun imenu-example--lisp-extract-index-name ()
  258. ;; Example of a candidate for `imenu-extract-index-name-function'.
  259. ;; This will generate a flat index of definitions in a lisp file.
  260. (save-match-data
  261. (and (looking-at "(def")
  262. (condition-case nil
  263. (progn
  264. (down-list 1)
  265. (forward-sexp 2)
  266. (let ((beg (point))
  267. (end (progn (forward-sexp -1) (point))))
  268. (buffer-substring beg end)))
  269. (error nil)))))
  270. (make-obsolete 'imenu-example--lisp-extract-index-name "your own" "23.2")
  271. (defun imenu-example--create-lisp-index ()
  272. ;; Example of a candidate for `imenu-create-index-function'.
  273. ;; It will generate a nested index of definitions.
  274. (let ((index-alist '())
  275. (index-var-alist '())
  276. (index-type-alist '())
  277. (index-unknown-alist '())
  278. prev-pos)
  279. (goto-char (point-max))
  280. (imenu-progress-message prev-pos 0)
  281. ;; Search for the function
  282. (while (beginning-of-defun)
  283. (imenu-progress-message prev-pos nil t)
  284. (save-match-data
  285. (and (looking-at "(def")
  286. (save-excursion
  287. (down-list 1)
  288. (cond
  289. ((looking-at "def\\(var\\|const\\)")
  290. (forward-sexp 2)
  291. (push (imenu-example--name-and-position)
  292. index-var-alist))
  293. ((looking-at "def\\(un\\|subst\\|macro\\|advice\\)")
  294. (forward-sexp 2)
  295. (push (imenu-example--name-and-position)
  296. index-alist))
  297. ((looking-at "def\\(type\\|struct\\|class\\|ine-condition\\)")
  298. (forward-sexp 2)
  299. (if (= (char-after (1- (point))) ?\))
  300. (progn
  301. (forward-sexp -1)
  302. (down-list 1)
  303. (forward-sexp 1)))
  304. (push (imenu-example--name-and-position)
  305. index-type-alist))
  306. (t
  307. (forward-sexp 2)
  308. (push (imenu-example--name-and-position)
  309. index-unknown-alist)))))))
  310. (imenu-progress-message prev-pos 100)
  311. (and index-var-alist
  312. (push (cons "Variables" index-var-alist)
  313. index-alist))
  314. (and index-type-alist
  315. (push (cons "Types" index-type-alist)
  316. index-alist))
  317. (and index-unknown-alist
  318. (push (cons "Syntax-unknown" index-unknown-alist)
  319. index-alist))
  320. index-alist))
  321. (make-obsolete 'imenu-example--create-lisp-index "your own" "23.2")
  322. ;; Regular expression to find C functions
  323. (defvar imenu-example--function-name-regexp-c
  324. (concat
  325. "^[a-zA-Z0-9]+[ \t]?" ; type specs; there can be no
  326. "\\([a-zA-Z0-9_*]+[ \t]+\\)?" ; more than 3 tokens, right?
  327. "\\([a-zA-Z0-9_*]+[ \t]+\\)?"
  328. "\\([*&]+[ \t]*\\)?" ; pointer
  329. "\\([a-zA-Z0-9_*]+\\)[ \t]*(" ; name
  330. ))
  331. (defun imenu-example--create-c-index (&optional regexp)
  332. (let ((index-alist '())
  333. prev-pos char)
  334. (goto-char (point-min))
  335. (imenu-progress-message prev-pos 0)
  336. ;; Search for the function
  337. (save-match-data
  338. (while (re-search-forward
  339. (or regexp imenu-example--function-name-regexp-c)
  340. nil t)
  341. (imenu-progress-message prev-pos)
  342. (backward-up-list 1)
  343. (save-excursion
  344. (goto-char (scan-sexps (point) 1))
  345. (setq char (following-char)))
  346. ;; Skip this function name if it is a prototype declaration.
  347. (if (not (eq char ?\;))
  348. (push (imenu-example--name-and-position) index-alist))))
  349. (imenu-progress-message prev-pos 100)
  350. (nreverse index-alist)))
  351. (make-obsolete 'imenu-example--create-c-index "your own" "23.2")
  352. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  353. ;;;
  354. ;;; Internal variables
  355. ;;;
  356. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  357. ;; The item to use in the index for rescanning the buffer.
  358. (defconst imenu--rescan-item '("*Rescan*" . -99))
  359. ;; The latest buffer index.
  360. ;; Buffer local.
  361. (defvar imenu--index-alist nil
  362. "The buffer index alist computed for this buffer in Imenu.
  363. Simple elements in the alist look like (INDEX-NAME . POSITION).
  364. POSITION is the buffer position of the item; to go to the item
  365. is simply to move point to that position.
  366. Special elements look like (INDEX-NAME POSITION FUNCTION ARGUMENTS...).
  367. To \"go to\" a special element means applying FUNCTION
  368. to INDEX-NAME, POSITION, and the ARGUMENTS.
  369. A nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
  370. The function `imenu--subalist-p' tests an element and returns t
  371. if it is a sub-alist.
  372. There is one simple element with negative POSITION; selecting that
  373. element recalculates the buffer's index alist.")
  374. ;;;###autoload(put 'imenu--index-alist 'risky-local-variable t)
  375. (make-variable-buffer-local 'imenu--index-alist)
  376. (defvar imenu--last-menubar-index-alist nil
  377. "The latest buffer index alist used to update the menu bar menu.")
  378. (make-variable-buffer-local 'imenu--last-menubar-index-alist)
  379. ;; History list for 'jump-to-function-in-buffer'.
  380. ;; Making this buffer local caused it not to work!
  381. (defvar imenu--history-list nil)
  382. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  383. ;;;
  384. ;;; Internal support functions
  385. ;;;
  386. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  387. ;;;
  388. ;;; Sort function
  389. ;;; Sorts the items depending on their index name.
  390. ;;; An item looks like (NAME . POSITION).
  391. ;;;
  392. (defun imenu--sort-by-name (item1 item2)
  393. (string-lessp (car item1) (car item2)))
  394. (defun imenu--sort-by-position (item1 item2)
  395. (< (cdr item1) (cdr item2)))
  396. (defun imenu--relative-position (&optional reverse)
  397. ;; Support function to calculate relative position in buffer
  398. ;; Beginning of buffer is 0 and end of buffer is 100
  399. ;; If REVERSE is non-nil then the beginning is 100 and the end is 0.
  400. (let ((pos (point))
  401. (total (buffer-size)))
  402. (and reverse (setq pos (- total pos)))
  403. (if (> total 50000)
  404. ;; Avoid overflow from multiplying by 100!
  405. (/ (1- pos) (max (/ total 100) 1))
  406. (/ (* 100 (1- pos)) (max total 1)))))
  407. ;; Split LIST into sublists of max length N.
  408. ;; Example (imenu--split '(1 2 3 4 5 6 7 8) 3)-> '((1 2 3) (4 5 6) (7 8))
  409. ;;
  410. ;; The returned list DOES NOT share structure with LIST.
  411. (defun imenu--split (list n)
  412. (let ((remain list)
  413. (result '())
  414. (sublist '())
  415. (i 0))
  416. (while remain
  417. (push (pop remain) sublist)
  418. (incf i)
  419. (and (= i n)
  420. ;; We have finished a sublist
  421. (progn (push (nreverse sublist) result)
  422. (setq i 0)
  423. (setq sublist '()))))
  424. ;; There might be a sublist (if the length of LIST mod n is != 0)
  425. ;; that has to be added to the result list.
  426. (and sublist
  427. (push (nreverse sublist) result))
  428. (nreverse result)))
  429. ;;; Split the alist MENULIST into a nested alist, if it is long enough.
  430. ;;; In any case, add TITLE to the front of the alist.
  431. ;;; If IMENU--RESCAN-ITEM is present in MENULIST, it is moved to the
  432. ;;; beginning of the returned alist.
  433. ;;;
  434. ;;; The returned alist DOES NOT share structure with MENULIST.
  435. (defun imenu--split-menu (menulist title)
  436. (let ((menulist (copy-sequence menulist))
  437. keep-at-top tail)
  438. (if (memq imenu--rescan-item menulist)
  439. (setq keep-at-top (list imenu--rescan-item)
  440. menulist (delq imenu--rescan-item menulist)))
  441. (setq tail menulist)
  442. (dolist (item tail)
  443. (when (imenu--subalist-p item)
  444. (push item keep-at-top)
  445. (setq menulist (delq item menulist))))
  446. (if imenu-sort-function
  447. (setq menulist (sort menulist imenu-sort-function)))
  448. (if (> (length menulist) imenu-max-items)
  449. (setq menulist
  450. (mapcar
  451. (lambda (menu)
  452. (cons (format "From: %s" (caar menu)) menu))
  453. (imenu--split menulist imenu-max-items))))
  454. (cons title
  455. (nconc (nreverse keep-at-top) menulist))))
  456. ;;; Split up each long alist that are nested within ALIST
  457. ;;; into nested alists.
  458. ;;;
  459. ;;; Return a split and sorted copy of ALIST. The returned alist DOES
  460. ;;; NOT share structure with ALIST.
  461. (defun imenu--split-submenus (alist)
  462. (mapcar (function
  463. (lambda (elt)
  464. (if (and (consp elt)
  465. (stringp (car elt))
  466. (listp (cdr elt)))
  467. (imenu--split-menu (cdr elt) (car elt))
  468. elt)))
  469. alist))
  470. ;;; Truncate all strings in MENULIST to imenu-max-item-length
  471. (defun imenu--truncate-items (menulist)
  472. (mapcar (function
  473. (lambda (item)
  474. (cond
  475. ((consp (cdr item))
  476. (imenu--truncate-items (cdr item)))
  477. ;; truncate if necessary
  478. ((and (numberp imenu-max-item-length)
  479. (> (length (car item)) imenu-max-item-length))
  480. (setcar item (substring (car item) 0 imenu-max-item-length))))))
  481. menulist))
  482. (defun imenu--make-index-alist (&optional noerror)
  483. "Create an index alist for the definitions in the current buffer.
  484. This works by using the hook function `imenu-create-index-function'.
  485. Report an error if the list is empty unless NOERROR is supplied and
  486. non-nil.
  487. See `imenu--index-alist' for the format of the index alist."
  488. (or (and imenu--index-alist
  489. (or (not imenu-auto-rescan)
  490. (and imenu-auto-rescan
  491. (> (buffer-size) imenu-auto-rescan-maxout))))
  492. ;; Get the index; truncate if necessary
  493. (progn
  494. (setq imenu--index-alist
  495. (save-excursion
  496. (save-restriction
  497. (widen)
  498. (funcall imenu-create-index-function))))
  499. (imenu--truncate-items imenu--index-alist)))
  500. (or imenu--index-alist noerror
  501. (error "No items suitable for an index found in this buffer"))
  502. (or imenu--index-alist
  503. (setq imenu--index-alist (list nil)))
  504. ;; Add a rescan option to the index.
  505. (cons imenu--rescan-item imenu--index-alist))
  506. ;;; Find all markers in alist and makes
  507. ;;; them point nowhere.
  508. ;;; The top-level call uses nil as the argument;
  509. ;;; non-nil arguments are in recursive calls.
  510. (defvar imenu--cleanup-seen)
  511. (defun imenu--cleanup (&optional alist)
  512. ;; If alist is provided use that list.
  513. ;; If not, empty the table of lists already seen
  514. ;; and use imenu--index-alist.
  515. (if alist
  516. (setq imenu--cleanup-seen (cons alist imenu--cleanup-seen))
  517. (setq alist imenu--index-alist imenu--cleanup-seen (list alist)))
  518. (and alist
  519. (mapc
  520. (lambda (item)
  521. (cond
  522. ((markerp (cdr item))
  523. (set-marker (cdr item) nil))
  524. ;; Don't process one alist twice.
  525. ((memq (cdr item) imenu--cleanup-seen))
  526. ((imenu--subalist-p item)
  527. (imenu--cleanup (cdr item)))))
  528. alist)
  529. t))
  530. (defun imenu--create-keymap (title alist &optional cmd)
  531. (list* 'keymap title
  532. (mapcar
  533. (lambda (item)
  534. (list* (car item) (car item)
  535. (cond
  536. ((imenu--subalist-p item)
  537. (imenu--create-keymap (car item) (cdr item) cmd))
  538. (t
  539. `(lambda () (interactive)
  540. ,(if cmd `(,cmd ',item) (list 'quote item)))))))
  541. alist)))
  542. (defun imenu--in-alist (str alist)
  543. "Check whether the string STR is contained in multi-level ALIST."
  544. (let (elt head tail res)
  545. (setq res nil)
  546. (while alist
  547. (setq elt (car alist)
  548. tail (cdr elt)
  549. alist (cdr alist)
  550. head (car elt))
  551. ;; A nested ALIST element looks like
  552. ;; (INDEX-NAME (INDEX-NAME . INDEX-POSITION) ...)
  553. ;; while a bottom-level element looks like
  554. ;; (INDEX-NAME . INDEX-POSITION)
  555. ;; We are only interested in the bottom-level elements, so we need to
  556. ;; recurse if TAIL is a list.
  557. (cond ((listp tail)
  558. (if (setq res (imenu--in-alist str tail))
  559. (setq alist nil)))
  560. ((if imenu-name-lookup-function
  561. (funcall imenu-name-lookup-function str head)
  562. (string= str head))
  563. (setq alist nil res elt))))
  564. res))
  565. (defvar imenu-syntax-alist nil
  566. "Alist of syntax table modifiers to use while in `imenu--generic-function'.
  567. The car of the assocs may be either a character or a string and the
  568. cdr is a syntax description appropriate for `modify-syntax-entry'. For
  569. a string, all the characters in the string get the specified syntax.
  570. This is typically used to give word syntax to characters which
  571. normally have symbol syntax to simplify `imenu-expression'
  572. and speed-up matching.")
  573. ;;;###autoload
  574. (make-variable-buffer-local 'imenu-syntax-alist)
  575. (defun imenu-default-create-index-function ()
  576. "Default function to create an index alist of the current buffer.
  577. The most general method is to move point to end of buffer, then repeatedly call
  578. `imenu-prev-index-position-function' and `imenu-extract-index-name-function'.
  579. All the results returned by the latter are gathered into an index alist.
  580. This method is used if those two variables are non-nil.
  581. The alternate method, which is the one most often used, is to call
  582. `imenu--generic-function' with `imenu-generic-expression' as argument."
  583. ;; These should really be done by setting imenu-create-index-function
  584. ;; in these major modes. But save that change for later.
  585. (cond ((and imenu-prev-index-position-function
  586. imenu-extract-index-name-function)
  587. (let ((index-alist '()) (pos (point))
  588. prev-pos name)
  589. (goto-char (point-max))
  590. (imenu-progress-message prev-pos 0 t)
  591. ;; Search for the function
  592. (while (funcall imenu-prev-index-position-function)
  593. (when (= pos (point))
  594. (error "Infinite loop at %s:%d: imenu-prev-index-position-function does not move point" (buffer-name) pos))
  595. (setq pos (point))
  596. (imenu-progress-message prev-pos nil t)
  597. (save-excursion
  598. (setq name (funcall imenu-extract-index-name-function)))
  599. (and (stringp name)
  600. ;; [ydi] updated for imenu-use-markers
  601. (push (cons name (if imenu-use-markers (point-marker) (point)))
  602. index-alist)))
  603. (imenu-progress-message prev-pos 100 t)
  604. index-alist))
  605. ;; Use generic expression if possible.
  606. ((and imenu-generic-expression)
  607. (imenu--generic-function imenu-generic-expression))
  608. (t
  609. (error "This buffer cannot use `imenu-default-create-index-function'"))))
  610. ;;;
  611. ;;; Generic index gathering function.
  612. ;;;
  613. (defvar imenu-case-fold-search t
  614. "Defines whether `imenu--generic-function' should fold case when matching.
  615. This variable should be set (only) by initialization code
  616. for modes which use `imenu--generic-function'. If it is not set, but
  617. `font-lock-defaults' is set, then font-lock's setting is used.")
  618. ;;;###autoload
  619. (make-variable-buffer-local 'imenu-case-fold-search)
  620. ;; This function can be called with quitting disabled,
  621. ;; so it needs to be careful never to loop!
  622. (defun imenu--generic-function (patterns)
  623. "Return an index alist of the current buffer based on PATTERNS.
  624. PATTERNS is an alist with elements that look like this:
  625. (MENU-TITLE REGEXP INDEX)
  626. or like this:
  627. (MENU-TITLE REGEXP INDEX FUNCTION ARGUMENTS...)
  628. with zero or more ARGUMENTS. The former format creates a simple
  629. element in the index alist when it matches; the latter creates a
  630. special element of the form (INDEX-NAME POSITION-MARKER FUNCTION
  631. ARGUMENTS...) with FUNCTION and ARGUMENTS copied from PATTERNS.
  632. MENU-TITLE is a string used as the title for the submenu or nil
  633. if the entries are not nested.
  634. REGEXP is a regexp that should match a construct in the buffer
  635. that is to be displayed in the menu; i.e., function or variable
  636. definitions, etc. It contains a substring which is the name to
  637. appear in the menu. See the info section on Regexps for more
  638. information. REGEXP may also be a function, called without
  639. arguments. It is expected to search backwards. It shall return
  640. true and set `match-data' if it finds another element.
  641. INDEX points to the substring in REGEXP that contains the
  642. name (of the function, variable or type) that is to appear in the
  643. menu.
  644. The variable `imenu-case-fold-search' determines whether or not the
  645. regexp matches are case sensitive, and `imenu-syntax-alist' can be
  646. used to alter the syntax table for the search.
  647. See `lisp-imenu-generic-expression' for an example of PATTERNS.
  648. Returns an index of the current buffer as an alist. The elements in
  649. the alist look like:
  650. (INDEX-NAME . INDEX-POSITION)
  651. or like:
  652. (INDEX-NAME INDEX-POSITION FUNCTION ARGUMENTS...)
  653. They may also be nested index alists like:
  654. (INDEX-NAME . INDEX-ALIST)
  655. depending on PATTERNS."
  656. (let ((index-alist (list 'dummy))
  657. prev-pos
  658. (case-fold-search (if (or (local-variable-p 'imenu-case-fold-search)
  659. (not (local-variable-p 'font-lock-defaults)))
  660. imenu-case-fold-search
  661. (nth 2 font-lock-defaults)))
  662. (old-table (syntax-table))
  663. (table (copy-syntax-table (syntax-table)))
  664. (slist imenu-syntax-alist))
  665. ;; Modify the syntax table used while matching regexps.
  666. (dolist (syn slist)
  667. ;; The character(s) to modify may be a single char or a string.
  668. (if (numberp (car syn))
  669. (modify-syntax-entry (car syn) (cdr syn) table)
  670. (mapc (lambda (c)
  671. (modify-syntax-entry c (cdr syn) table))
  672. (car syn))))
  673. (goto-char (point-max))
  674. (imenu-progress-message prev-pos 0 t)
  675. (unwind-protect ; for syntax table
  676. (save-match-data
  677. (set-syntax-table table)
  678. ;; map over the elements of imenu-generic-expression
  679. ;; (typically functions, variables ...)
  680. (dolist (pat patterns)
  681. (let ((menu-title (car pat))
  682. (regexp (nth 1 pat))
  683. (index (nth 2 pat))
  684. (function (nth 3 pat))
  685. (rest (nthcdr 4 pat))
  686. start beg)
  687. ;; Go backwards for convenience of adding items in order.
  688. (goto-char (point-max))
  689. (while (and (if (functionp regexp)
  690. (funcall regexp)
  691. (re-search-backward regexp nil t))
  692. ;; Exit the loop if we get an empty match,
  693. ;; because it means a bad regexp was specified.
  694. (not (= (match-beginning 0) (match-end 0))))
  695. (setq start (point))
  696. ;; Record the start of the line in which the match starts.
  697. ;; That's the official position of this definition.
  698. (goto-char (match-beginning index))
  699. (beginning-of-line)
  700. (setq beg (point))
  701. (imenu-progress-message prev-pos nil t)
  702. ;; Add this sort of submenu only when we've found an
  703. ;; item for it, avoiding empty, duff menus.
  704. (unless (assoc menu-title index-alist)
  705. (push (list menu-title) index-alist))
  706. (if imenu-use-markers
  707. (setq beg (copy-marker beg)))
  708. (let ((item
  709. (if function
  710. (nconc (list (match-string-no-properties index)
  711. beg function)
  712. rest)
  713. (cons (match-string-no-properties index)
  714. beg)))
  715. ;; This is the desired submenu,
  716. ;; starting with its title (or nil).
  717. (menu (assoc menu-title index-alist)))
  718. ;; Insert the item unless it is already present.
  719. (unless (member item (cdr menu))
  720. (setcdr menu
  721. (cons item (cdr menu)))))
  722. ;; Go to the start of the match, to make sure we
  723. ;; keep making progress backwards.
  724. (goto-char start))))
  725. (set-syntax-table old-table)))
  726. (imenu-progress-message prev-pos 100 t)
  727. ;; Sort each submenu by position.
  728. ;; This is in case one submenu gets items from two different regexps.
  729. (dolist (item index-alist)
  730. (when (listp item)
  731. (setcdr item (sort (cdr item) 'imenu--sort-by-position))))
  732. (let ((main-element (assq nil index-alist)))
  733. (nconc (delq main-element (delq 'dummy index-alist))
  734. (cdr main-element)))))
  735. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  736. ;;;
  737. ;;; The main functions for this package!
  738. ;;;
  739. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  740. ;; See also info-lookup-find-item
  741. (defun imenu-find-default (guess completions)
  742. "Fuzzily find an item based on GUESS inside the alist COMPLETIONS."
  743. (catch 'found
  744. (let ((case-fold-search t))
  745. (if (assoc guess completions) guess
  746. (dolist (re (list (concat "\\`" (regexp-quote guess) "\\'")
  747. (concat "\\`" (regexp-quote guess))
  748. (concat (regexp-quote guess) "\\'")
  749. (regexp-quote guess)))
  750. (dolist (x completions)
  751. (if (string-match re (car x)) (throw 'found (car x)))))))))
  752. (defun imenu--completion-buffer (index-alist &optional prompt)
  753. "Let the user select from INDEX-ALIST in a completion buffer with PROMPT.
  754. Return one of the entries in index-alist or nil."
  755. ;; Create a list for this buffer only when needed.
  756. (let ((name (thing-at-point 'symbol))
  757. choice
  758. (prepared-index-alist
  759. (if (not imenu-space-replacement) index-alist
  760. (mapcar
  761. (lambda (item)
  762. (cons (subst-char-in-string ?\s (aref imenu-space-replacement 0)
  763. (car item))
  764. (cdr item)))
  765. index-alist))))
  766. (when (stringp name)
  767. (setq name (or (imenu-find-default name prepared-index-alist) name)))
  768. (cond (prompt)
  769. ((and name (imenu--in-alist name prepared-index-alist))
  770. (setq prompt (format "Index item (default %s): " name)))
  771. (t (setq prompt "Index item: ")))
  772. (let ((minibuffer-setup-hook minibuffer-setup-hook))
  773. ;; Display the completion buffer.
  774. (if (not imenu-eager-completion-buffer)
  775. (add-hook 'minibuffer-setup-hook 'minibuffer-completion-help))
  776. (setq name (completing-read prompt
  777. prepared-index-alist
  778. nil t nil 'imenu--history-list name)))
  779. (when (stringp name)
  780. (setq choice (assoc name prepared-index-alist))
  781. (if (imenu--subalist-p choice)
  782. (imenu--completion-buffer (cdr choice) prompt)
  783. choice))))
  784. (defun imenu--mouse-menu (index-alist event &optional title)
  785. "Let the user select from a buffer index from a mouse menu.
  786. INDEX-ALIST is the buffer index and EVENT is a mouse event.
  787. Returns t for rescan and otherwise an element or subelement of INDEX-ALIST."
  788. (setq index-alist (imenu--split-submenus index-alist))
  789. (let* ((menu (imenu--split-menu index-alist (or title (buffer-name))))
  790. (map (imenu--create-keymap (car menu)
  791. (cdr (if (< 1 (length (cdr menu)))
  792. menu
  793. (car (cdr menu)))))))
  794. (popup-menu map event)))
  795. (defun imenu-choose-buffer-index (&optional prompt alist)
  796. "Let the user select from a buffer index and return the chosen index.
  797. If the user originally activated this function with the mouse, a mouse
  798. menu is used. Otherwise a completion buffer is used and the user is
  799. prompted with PROMPT.
  800. If you call this function with index alist ALIST, then it lets the user
  801. select from ALIST.
  802. With no index alist ALIST, it calls `imenu--make-index-alist' to
  803. create the index alist.
  804. If `imenu-use-popup-menu' is nil, then the completion buffer
  805. is always used, no matter if the mouse was used or not.
  806. The returned value is of the form (INDEX-NAME . INDEX-POSITION)."
  807. (let (index-alist
  808. (mouse-triggered (listp last-nonmenu-event))
  809. (result t))
  810. ;; If selected by mouse, see to that the window where the mouse is
  811. ;; really is selected.
  812. (and mouse-triggered
  813. (not (equal last-nonmenu-event '(menu-bar)))
  814. (let ((window (posn-window (event-start last-nonmenu-event))))
  815. (or (framep window) (null window) (select-window window))))
  816. ;; Create a list for this buffer only when needed.
  817. (while (eq result t)
  818. (setq index-alist (if alist alist (imenu--make-index-alist)))
  819. (setq result
  820. (if (and imenu-use-popup-menu
  821. (or (eq imenu-use-popup-menu t) mouse-triggered))
  822. (imenu--mouse-menu index-alist last-nonmenu-event)
  823. (imenu--completion-buffer index-alist prompt)))
  824. (and (equal result imenu--rescan-item)
  825. (imenu--cleanup)
  826. (setq result t imenu--index-alist nil)))
  827. result))
  828. ;;;###autoload
  829. (defun imenu-add-to-menubar (name)
  830. "Add an `imenu' entry to the menu bar for the current buffer.
  831. NAME is a string used to name the menu bar item.
  832. See the command `imenu' for more information."
  833. (interactive "sImenu menu item name: ")
  834. (if (or (and imenu-prev-index-position-function
  835. imenu-extract-index-name-function)
  836. imenu-generic-expression
  837. (not (eq imenu-create-index-function
  838. 'imenu-default-create-index-function)))
  839. (unless (and (current-local-map)
  840. (keymapp (lookup-key (current-local-map) [menu-bar index])))
  841. (let ((newmap (make-sparse-keymap)))
  842. (set-keymap-parent newmap (current-local-map))
  843. (setq imenu--last-menubar-index-alist nil)
  844. (define-key newmap [menu-bar index]
  845. `(menu-item ,name ,(make-sparse-keymap "Imenu")))
  846. (use-local-map newmap)
  847. (add-hook 'menu-bar-update-hook 'imenu-update-menubar)))
  848. (error "The mode `%s' does not support Imenu"
  849. (format-mode-line mode-name))))
  850. ;;;###autoload
  851. (defun imenu-add-menubar-index ()
  852. "Add an Imenu \"Index\" entry on the menu bar for the current buffer.
  853. A trivial interface to `imenu-add-to-menubar' suitable for use in a hook."
  854. (interactive)
  855. (imenu-add-to-menubar "Index"))
  856. (defvar imenu-buffer-menubar nil)
  857. (defvar imenu-menubar-modified-tick 0
  858. "The value of (buffer-chars-modified-tick) as of the last call
  859. to `imenu-update-menubar'.")
  860. (make-variable-buffer-local 'imenu-menubar-modified-tick)
  861. (defun imenu-update-menubar ()
  862. (when (and (current-local-map)
  863. (keymapp (lookup-key (current-local-map) [menu-bar index]))
  864. (/= (buffer-chars-modified-tick) imenu-menubar-modified-tick))
  865. (setq imenu-menubar-modified-tick (buffer-chars-modified-tick))
  866. (let ((index-alist (imenu--make-index-alist t)))
  867. ;; Don't bother updating if the index-alist has not changed
  868. ;; since the last time we did it.
  869. (unless (equal index-alist imenu--last-menubar-index-alist)
  870. (let (menu menu1 old)
  871. (setq imenu--last-menubar-index-alist index-alist)
  872. (setq index-alist (imenu--split-submenus index-alist))
  873. (setq menu (imenu--split-menu index-alist
  874. (buffer-name)))
  875. (setq menu1 (imenu--create-keymap (car menu)
  876. (cdr (if (< 1 (length (cdr menu)))
  877. menu
  878. (car (cdr menu))))
  879. 'imenu--menubar-select))
  880. (setq old (lookup-key (current-local-map) [menu-bar index]))
  881. ;; This should never happen, but in some odd cases, potentially,
  882. ;; lookup-key may return a dynamically composed keymap.
  883. (if (keymapp (cadr old)) (setq old (cadr old)))
  884. (setcdr old (cdr menu1)))))))
  885. (defun imenu--menubar-select (item)
  886. "Use Imenu to select the function or variable named in this menu ITEM."
  887. (if (equal item imenu--rescan-item)
  888. (progn
  889. (imenu--cleanup)
  890. ;; Make sure imenu-update-menubar redoes everything.
  891. (setq imenu-menubar-modified-tick -1)
  892. (setq imenu--index-alist nil)
  893. (setq imenu--last-menubar-index-alist nil)
  894. (imenu-update-menubar)
  895. t)
  896. (imenu item)
  897. nil))
  898. (defun imenu-default-goto-function (name position &optional rest)
  899. "Move to the given position.
  900. NAME is ignored. POSITION is where to move. REST is also ignored.
  901. The ignored args just make this function have the same interface as a
  902. function placed in a special index-item."
  903. (if (or (< position (point-min))
  904. (> position (point-max)))
  905. ;; widen if outside narrowing
  906. (widen))
  907. (goto-char position))
  908. ;;;###autoload
  909. (defun imenu (index-item)
  910. "Jump to a place in the buffer chosen using a buffer menu or mouse menu.
  911. INDEX-ITEM specifies the position. See `imenu-choose-buffer-index'
  912. for more information."
  913. (interactive (list (imenu-choose-buffer-index)))
  914. ;; Convert a string to an alist element.
  915. (if (stringp index-item)
  916. (setq index-item (assoc index-item (imenu--make-index-alist))))
  917. (when index-item
  918. (push-mark)
  919. (let* ((is-special-item (listp (cdr index-item)))
  920. (function
  921. (if is-special-item
  922. (nth 2 index-item) imenu-default-goto-function))
  923. (position (if is-special-item
  924. (cadr index-item) (cdr index-item)))
  925. (rest (if is-special-item (cddr index-item))))
  926. (apply function (car index-item) position rest))
  927. (run-hooks 'imenu-after-jump-hook)))
  928. (dolist (mess
  929. '("^No items suitable for an index found in this buffer$"
  930. "^This buffer cannot use `imenu-default-create-index-function'$"
  931. "^The mode `.*' does not support Imenu$"))
  932. (add-to-list 'debug-ignored-errors mess))
  933. (provide 'imenu)
  934. ;;; imenu.el ends here