(msb--few-menus, msb--very-many-menus): Use current Gnus
[bpt/emacs.git] / lisp / msb.el
1 ;;; msb.el --- Customizable buffer-selection with multiple menus.
2
3 ;; Copyright (C) 1993, 94, 95, 97, 98, 99, 2000 Free Software Foundation, Inc.
4
5 ;; Author: Lars Lindberg <Lars.G.Lindberg@capgemini.se>
6 ;; Maintainer: FSF
7 ;; Created: 8 Oct 1993
8 ;; Lindberg's last update version: 3.34
9 ;; Keywords: mouse buffer menu
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; Purpose of this package:
31 ;; 1. Offer a function for letting the user choose buffer,
32 ;; not necessarily for switching to it.
33 ;; 2. Make a better mouse-buffer-menu. This is done as a global
34 ;; minor mode, msb-mode.
35 ;;
36 ;; Customization:
37 ;; Look at the variable `msb-menu-cond' for deciding what menus you
38 ;; want. It's not that hard to customize, despite my not-so-good
39 ;; doc-string. Feel free to send me a better doc-string.
40 ;; There are some constants for you to try here:
41 ;; msb--few-menus
42 ;; msb--very-many-menus (default)
43 ;;
44 ;; Look at the variable `msb-item-handling-function' for customization
45 ;; of the appearance of every menu item. Try for instance setting
46 ;; it to `msb-alon-item-handler'.
47 ;;
48 ;; Look at the variable `msb-item-sort-function' for customization
49 ;; of sorting the menus. Set it to t for instance, which means no
50 ;; sorting - you will get latest used buffer first.
51 ;;
52 ;; Also check out the variable `msb-display-invisible-buffers-p'.
53
54 ;; Known bugs:
55 ;; - Files-by-directory
56 ;; + No possibility to show client/changed buffers separately.
57 ;; + All file buffers only appear in a file sub-menu, they will
58 ;; for instance not appear in the Mail sub-menu.
59
60 ;; Future enhancements:
61
62 ;;; Thanks goes to
63 ;; Mark Brader <msb@sq.com>
64 ;; Jim Berry <m1jhb00@FRB.GOV>
65 ;; Hans Chalupsky <hans@cs.Buffalo.EDU>
66 ;; Larry Rosenberg <ljr@ictv.com>
67 ;; Will Henney <will@astroscu.unam.mx>
68 ;; Jari Aalto <jaalto@tre.tele.nokia.fi>
69 ;; Michael Kifer <kifer@sbkifer.cs.sunysb.edu>
70 ;; Gael Marziou <gael@gnlab030.grenoble.hp.com>
71 ;; Dave Gillespie <daveg@thymus.synaptics.com>
72 ;; Alon Albert <alon@milcse.rtsg.mot.com>
73 ;; Kevin Broadey, <KevinB@bartley.demon.co.uk>
74 ;; Ake Stenhof <ake@cadpoint.se>
75 ;; Richard Stallman <rms@gnu.org>
76 ;; Steve Fisk <fisk@medved.bowdoin.edu>
77
78 ;; This version turned into a global minor mode and subsequently
79 ;; hacked on by Dave Love.
80 ;;; Code:
81
82 (eval-when-compile (require 'cl))
83
84 ;;;
85 ;;; Some example constants to be used for `msb-menu-cond'. See that
86 ;;; variable for more information. Please note that if the condition
87 ;;; returns `multi', then the buffer can appear in several menus.
88 ;;;
89 (defconst msb--few-menus
90 '(((and (boundp 'server-buffer-clients)
91 server-buffer-clients
92 'multi)
93 3030
94 "Clients (%d)")
95 ((and msb-display-invisible-buffers-p
96 (msb-invisible-buffer-p)
97 'multi)
98 3090
99 "Invisible buffers (%d)")
100 ((eq major-mode 'dired-mode)
101 2010
102 "Dired (%d)"
103 msb-dired-item-handler
104 msb-sort-by-directory)
105 ((eq major-mode 'Man-mode)
106 4090
107 "Manuals (%d)")
108 ((eq major-mode 'w3-mode)
109 4020
110 "WWW (%d)")
111 ((or (memq major-mode
112 '(rmail-mode rmail-edit-mode vm-summary-mode vm-mode mail-mode))
113 (memq major-mode '(mh-letter-mode mh-show-mode mh-folder-mode))
114 (memq major-mode
115 '(gnus-summary-mode message-mode gnus-group-mode
116 gnus-article-mode score-mode gnus-browse-killed-mode)))
117 4010
118 "Mail (%d)")
119 ((not buffer-file-name)
120 4099
121 "Buffers (%d)")
122 ('no-multi
123 1099
124 "Files (%d)")))
125
126 (defconst msb--very-many-menus
127 '(((and (boundp 'server-buffer-clients)
128 server-buffer-clients
129 'multi)
130 1010
131 "Clients (%d)")
132 ((and (boundp 'vc-mode) vc-mode 'multi)
133 1020
134 "Version Control (%d)")
135 ((and buffer-file-name
136 (buffer-modified-p)
137 'multi)
138 1030
139 "Changed files (%d)")
140 ((and (get-buffer-process (current-buffer))
141 'multi)
142 1040
143 "Processes (%d)")
144 ((and msb-display-invisible-buffers-p
145 (msb-invisible-buffer-p)
146 'multi)
147 1090
148 "Invisible buffers (%d)")
149 ((eq major-mode 'dired-mode)
150 2010
151 "Dired (%d)"
152 ;; Note this different menu-handler
153 msb-dired-item-handler
154 ;; Also note this item-sorter
155 msb-sort-by-directory)
156 ((eq major-mode 'Man-mode)
157 5030
158 "Manuals (%d)")
159 ((eq major-mode 'w3-mode)
160 5020
161 "WWW (%d)")
162 ((or (memq major-mode
163 '(rmail-mode rmail-edit-mode vm-summary-mode vm-mode mail-mode))
164 (memq major-mode '(mh-letter-mode mh-show-mode mh-folder-mode))
165 (memq major-mode '(gnus-summary-mode message-mode gnus-group-mode
166 gnus-article-mode score-mode
167 gnus-browse-killed-mode)))
168 5010
169 "Mail (%d)")
170 ;; Catchup for all non-file buffers
171 ((and (not buffer-file-name)
172 'no-multi)
173 5099
174 "Other non-file buffers (%d)")
175 ((and (string-match "/\\.[^/]*$" buffer-file-name)
176 'multi)
177 3090
178 "Hidden Files (%d)")
179 ((memq major-mode '(c-mode c++-mode))
180 3010
181 "C/C++ Files (%d)")
182 ((eq major-mode 'emacs-lisp-mode)
183 3020
184 "Elisp Files (%d)")
185 ((eq major-mode 'latex-mode)
186 3030
187 "LaTex Files (%d)")
188 ('no-multi
189 3099
190 "Other files (%d)")))
191
192 ;; msb--many-menus is obsolete
193 (defvar msb--many-menus msb--very-many-menus)
194
195 ;;;
196 ;;; Customizable variables
197 ;;;
198
199 (defgroup msb nil
200 "Customizable buffer-selection with multiple menus."
201 :prefix "msb-"
202 :group 'mouse)
203
204 ;;;###autoload
205 (defcustom msb-mode nil
206 "Toggle msb-mode.
207 Setting this variable directly does not take effect;
208 use either \\[customize] or the function `msb-mode'."
209 :set (lambda (symbol value)
210 (msb-mode (or value 0)))
211 :initialize 'custom-initialize-default
212 :version "20.4"
213 :type 'boolean
214 :group 'msb
215 :require 'msb)
216
217 (defun msb-custom-set (symbol value)
218 "Set the value of custom variables for msb."
219 (set symbol value)
220 (if (and (featurep 'msb) msb-mode)
221 ;; wait until package has been loaded before bothering to update
222 ;; the buffer lists.
223 (msb-menu-bar-update-buffers t)))
224
225 (defcustom msb-menu-cond msb--very-many-menus
226 "*List of criteria for splitting the mouse buffer menu.
227 The elements in the list should be of this type:
228 (CONDITION MENU-SORT-KEY MENU-TITLE ITEM-HANDLING-FN ITEM-SORT-FN).
229
230 When making the split, the buffers are tested one by one against the
231 CONDITION, just like a Lisp cond: When hitting a true condition, the
232 other criteria are *not* tested and the buffer name will appear in the
233 menu with the menu-title corresponding to the true condition.
234
235 If the condition returns the symbol `multi', then the buffer will be
236 added to this menu *and* tested for other menus too. If it returns
237 `no-multi', then the buffer will only be added if it hasn't been added
238 to any other menu.
239
240 During this test, the buffer in question is the current buffer, and
241 the test is surrounded by calls to `save-excursion' and
242 `save-match-data'.
243
244 The categories are sorted by MENU-SORT-KEY. Smaller keys are on top.
245 nil means don't display this menu.
246
247 MENU-TITLE is really a format. If you add %d in it, the %d is
248 replaced with the number of items in that menu.
249
250 ITEM-HANDLING-FN, is optional. If it is supplied and is a function,
251 than it is used for displaying the items in that particular buffer
252 menu, otherwise the function pointed out by
253 `msb-item-handling-function' is used.
254
255 ITEM-SORT-FN, is also optional.
256 If it is not supplied, the function pointed out by
257 `msb-item-sort-function' is used.
258 If it is nil, then no sort takes place and the buffers are presented
259 in least-recently-used order.
260 If it is t, then no sort takes place and the buffers are presented in
261 most-recently-used order.
262 If it is supplied and non-nil and not t than it is used for sorting
263 the items in that particular buffer menu.
264
265 Note1: There should always be a `catch-all' as last element, in this
266 list. That is an element like (t TITLE ITEM-HANDLING-FUNCTION).
267 Note2: A buffer menu appears only if it has at least one buffer in it.
268 Note3: If you have a CONDITION that can't be evaluated you will get an
269 error every time you do \\[msb]."
270 :type `(choice (const :tag "long" :value ,msb--very-many-menus)
271 (const :tag "short" :value ,msb--few-menus)
272 (sexp :tag "user"))
273 :set 'msb-custom-set
274 :group 'msb)
275
276 (defcustom msb-modes-key 4000
277 "The sort key for files sorted by mode."
278 :type 'integer
279 :set 'msb-custom-set
280 :group 'msb
281 :version "20.3")
282
283 (defcustom msb-separator-diff 100
284 "*Non-nil means use separators.
285 The separators will appear between all menus that have a sorting key
286 that differs by this value or more."
287 :type '(choice integer (const nil))
288 :set 'msb-custom-set
289 :group 'msb)
290
291 (defvar msb-files-by-directory-sort-key 0
292 "*The sort key for files sorted by directory.")
293
294 (defcustom msb-max-menu-items 15
295 "*The maximum number of items in a menu.
296 If this variable is set to 15 for instance, then the submenu will be
297 split up in minor parts, 15 items each. Nil means no limit."
298 :type '(choice integer (const nil))
299 :set 'msb-custom-set
300 :group 'msb)
301
302 (defcustom msb-max-file-menu-items 10
303 "*The maximum number of items from different directories.
304
305 When the menu is of type `file by directory', this is the maximum
306 number of buffers that are clumped together from different
307 directories.
308
309 Set this to 1 if you want one menu per directory instead of clumping
310 them together.
311
312 If the value is not a number, then the value 10 is used."
313 :type 'integer
314 :set 'msb-custom-set
315 :group 'msb)
316
317 (defcustom msb-most-recently-used-sort-key -1010
318 "*Where should the menu with the most recently used buffers be placed?"
319 :type 'integer
320 :set 'msb-custom-set
321 :group 'msb)
322
323 (defcustom msb-display-most-recently-used 15
324 "*How many buffers should be in the most-recently-used menu.
325 No buffers at all if less than 1 or nil (or any non-number)."
326 :type 'integer
327 :set 'msb-custom-set
328 :group 'msb)
329
330 (defcustom msb-most-recently-used-title "Most recently used (%d)"
331 "*The title for the most-recently-used menu."
332 :type 'string
333 :set 'msb-custom-set
334 :group 'msb)
335
336 (defvar msb-horizontal-shift-function '(lambda () 0)
337 "*Function that specifies how many pixels to shift the top menu leftwards.")
338
339 (defcustom msb-display-invisible-buffers-p nil
340 "*Show invisible buffers or not.
341 Non-nil means that the buffer menu should include buffers that have
342 names that starts with a space character."
343 :type 'boolean
344 :set 'msb-custom-set
345 :group 'msb)
346
347 (defvar msb-item-handling-function 'msb-item-handler
348 "*The appearance of a buffer menu.
349
350 The default function to call for handling the appearance of a menu
351 item. It should take to arguments, BUFFER and MAX-BUFFER-NAME-LENGTH,
352 where the latter is the max length of all buffer names.
353
354 The function should return the string to use in the menu.
355
356 When the function is called, BUFFER is the current buffer. This
357 function is called for items in the variable `msb-menu-cond' that have
358 nil as ITEM-HANDLING-FUNCTION. See `msb-menu-cond' for more
359 information.")
360
361 (defcustom msb-item-sort-function 'msb-sort-by-name
362 "*The order of items in a buffer menu.
363
364 The default function to call for handling the order of items in a menu
365 item. This function is called like a sort function. The items look
366 like (ITEM-NAME . BUFFER).
367
368 ITEM-NAME is the name of the item that will appear in the menu.
369 BUFFER is the buffer, this is not necessarily the current buffer.
370
371 Set this to nil or t if you don't want any sorting (faster)."
372 :type '(choice (const msb-sort-by-name)
373 (const :tag "Newest first" t)
374 (const :tag "Oldest first" nil))
375 :set 'msb-custom-set
376 :group 'msb)
377
378 (defcustom msb-files-by-directory nil
379 "*Non-nil means that files should be sorted by directory.
380 This is instead of the groups in `msb-menu-cond'."
381 :type 'boolean
382 :set 'msb-custom-set
383 :group 'msb)
384
385 (defcustom msb-after-load-hooks nil
386 "Hooks to be run after the msb package has been loaded."
387 :type 'hook
388 :set 'msb-custom-set
389 :group 'msb)
390
391 ;;;
392 ;;; Internal variables
393 ;;;
394
395 ;; The last calculated menu.
396 (defvar msb--last-buffer-menu nil)
397
398 ;; If this is non-nil, then it is a string that describes the error.
399 (defvar msb--error nil)
400
401 ;;;
402 ;;; Some example function to be used for `msb-item-handling-function'.
403 ;;;
404 (defun msb-item-handler (buffer &optional maxbuf)
405 "Create one string item, concerning BUFFER, for the buffer menu.
406 The item looks like:
407 *% <buffer-name>
408 The `*' appears only if the buffer is marked as modified.
409 The `%' appears only if the buffer is read-only.
410 Optional second argument MAXBUF is completely ignored."
411 (let ((name (buffer-name))
412 (modified (if (buffer-modified-p) "*" " "))
413 (read-only (if buffer-read-only "%" " ")))
414 (format "%s%s %s" modified read-only name)))
415
416
417 (eval-when-compile (require 'dired))
418
419 ;; `dired' can be called with a list of the form (directory file1 file2 ...)
420 ;; which causes `dired-directory' to be in the same form.
421 (defun msb--dired-directory ()
422 (cond ((stringp dired-directory)
423 (abbreviate-file-name (expand-file-name dired-directory)))
424 ((consp dired-directory)
425 (abbreviate-file-name (expand-file-name (car dired-directory))))
426 (t
427 (error "Unknown type of `dired-directory' in buffer %s"
428 (buffer-name)))))
429
430 (defun msb-dired-item-handler (buffer &optional maxbuf)
431 "Create one string item, concerning a dired BUFFER, for the buffer menu.
432 The item looks like:
433 *% <buffer-name>
434 The `*' appears only if the buffer is marked as modified.
435 The `%' appears only if the buffer is read-only.
436 Optional second argument MAXBUF is completely ignored."
437 (let ((name (msb--dired-directory))
438 (modified (if (buffer-modified-p) "*" " "))
439 (read-only (if buffer-read-only "%" " ")))
440 (format "%s%s %s" modified read-only name)))
441
442 (defun msb-alon-item-handler (buffer maxbuf)
443 "Create one string item for the buffer menu.
444 The item looks like:
445 <buffer-name> *%# <file-name>
446 The `*' appears only if the buffer is marked as modified.
447 The `%' appears only if the buffer is read-only.
448 The `#' appears only version control file (SCCS/RCS)."
449 (format (format "%%%ds %%s%%s%%s %%s" maxbuf)
450 (buffer-name buffer)
451 (if (buffer-modified-p) "*" " ")
452 (if buffer-read-only "%" " ")
453 (if (and (boundp 'vc-mode) vc-mode) "#" " ")
454 (or buffer-file-name "")))
455
456 ;;;
457 ;;; Some example function to be used for `msb-item-sort-function'.
458 ;;;
459 (defun msb-sort-by-name (item1 item2)
460 "Sort the items ITEM1 and ITEM2 by their `buffer-name'.
461 An item looks like (NAME . BUFFER)."
462 (string-lessp (buffer-name (cdr item1))
463 (buffer-name (cdr item2))))
464
465
466 (defun msb-sort-by-directory (item1 item2)
467 "Sort the items ITEM1 and ITEM2 by directory name. Made for dired.
468 An item look like (NAME . BUFFER)."
469 (string-lessp (save-excursion (set-buffer (cdr item1))
470 (msb--dired-directory))
471 (save-excursion (set-buffer (cdr item2))
472 (msb--dired-directory))))
473
474 ;;;
475 ;;; msb
476 ;;;
477 ;;; This function can be used instead of (mouse-buffer-menu EVENT)
478 ;;; function in "mouse.el".
479 ;;;
480 (defun msb (event)
481 "Pop up several menus of buffers for selection with the mouse.
482 This command switches buffers in the window that you clicked on, and
483 selects that window.
484
485 See the function `mouse-select-buffer' and the variable
486 `msb-menu-cond' for more information about how the menus are split."
487 (interactive "e")
488 (let ((old-window (selected-window))
489 (window (posn-window (event-start event))))
490 (unless (framep window) (select-window window))
491 (let ((buffer (mouse-select-buffer event)))
492 (if buffer
493 (switch-to-buffer buffer)
494 (select-window old-window))))
495 nil)
496
497 ;;;
498 ;;; Some supportive functions
499 ;;;
500 (defun msb-invisible-buffer-p (&optional buffer)
501 "Return t if optional BUFFER is an \"invisible\" buffer.
502 If the argument is left out or nil, then the current buffer is considered."
503 (and (> (length (buffer-name buffer)) 0)
504 (eq ?\ (aref (buffer-name buffer) 0))))
505
506 (defun msb--strip-dir (dir)
507 "Strip one hierarchy level from the end of DIR."
508 (file-name-directory (directory-file-name dir)))
509
510 ;; Create an alist with all buffers from LIST that lies under the same
511 ;; directory will be in the same item as the directory string.
512 ;; ((PATH1 . (BUFFER-1 BUFFER-2 ...)) (PATH2 . (BUFFER-K BUFFER-K+1...)) ...)
513 (defun msb--init-file-alist (list)
514 (let ((buffer-alist
515 ;; Make alist that looks like
516 ;; ((PATH-1 BUFFER-1) (PATH-2 BUFFER-2) ...)
517 ;; sorted on PATH-x
518 (sort
519 (apply #'nconc
520 (mapcar
521 (lambda (buffer)
522 (let ((file-name (expand-file-name
523 (buffer-file-name buffer))))
524 (when file-name
525 (list (cons (msb--strip-dir file-name) buffer)))))
526 list))
527 (lambda (item1 item2)
528 (string< (car item1) (car item2))))))
529 ;; Now clump buffers together that have the same path
530 ;; Make alist that looks like
531 ;; ((PATH1 . (BUFFER-1 BUFFER-2 ...)) (PATH2 . (BUFFER-K)) ...)
532 (let ((path nil)
533 (buffers nil))
534 (nconc
535 (apply
536 #'nconc
537 (mapcar (lambda (item)
538 (cond
539 ((equal path (car item))
540 ;; The same path as earlier: Add to current list of
541 ;; buffers.
542 (push (cdr item) buffers)
543 ;; This item should not be added to list
544 nil)
545 (t
546 ;; New path
547 (let ((result (and path (cons path buffers))))
548 (setq path (car item))
549 (setq buffers (list (cdr item)))
550 ;; Add the last result the list.
551 (and result (list result))))))
552 buffer-alist))
553 ;; Add the last result to the list
554 (list (cons path buffers))))))
555
556 (defun msb--format-title (top-found-p path number-of-items)
557 "Format a suitable title for the menu item."
558 (format (if top-found-p "%s... (%d)" "%s (%d)")
559 (abbreviate-file-name path) number-of-items))
560
561 ;; Variables for debugging.
562 (defvar msb--choose-file-menu-list)
563 (defvar msb--choose-file-menu-arg-list)
564
565 (defun msb--choose-file-menu (list)
566 "Choose file-menu with respect to directory for every buffer in LIST."
567 (setq msb--choose-file-menu-arg-list list)
568 (let ((buffer-alist (msb--init-file-alist list))
569 (final-list nil)
570 (max-clumped-together (if (numberp msb-max-file-menu-items)
571 msb-max-file-menu-items
572 10))
573 (top-found-p nil)
574 (last-path nil)
575 first rest path buffers old-path)
576 ;; Prepare for looping over all items in buffer-alist
577 (setq first (car buffer-alist)
578 rest (cdr buffer-alist)
579 path (car first)
580 buffers (cdr first))
581 (setq msb--choose-file-menu-list (copy-sequence rest))
582 ;; This big loop tries to clump buffers together that have a
583 ;; similar name. Remember that buffer-alist is sorted based on the
584 ;; path for the buffers.
585 (while rest
586 (let ((found-p nil)
587 (tmp-rest rest)
588 result
589 new-path item)
590 (setq item (car tmp-rest))
591 ;; Clump together the "rest"-buffers that have a path that is
592 ;; a subpath of the current one.
593 (while (and tmp-rest
594 (<= (length buffers) max-clumped-together)
595 (>= (length (car item)) (length path))
596 ;; `completion-ignore-case' seems to default to t
597 ;; on the systems with case-insensitive file names.
598 (eq t (compare-strings path 0 nil
599 (car item) 0 (length path)
600 completion-ignore-case)))
601 (setq found-p t)
602 (setq buffers (append buffers (cdr item))) ;nconc is faster than append
603 (setq tmp-rest (cdr tmp-rest)
604 item (car tmp-rest)))
605 (cond
606 ((> (length buffers) max-clumped-together)
607 ;; Oh, we failed. Too many buffers clumped together.
608 ;; Just use the original ones for the result.
609 (setq last-path (car first))
610 (push (cons (msb--format-title top-found-p
611 (car first)
612 (length (cdr first)))
613 (cdr first))
614 final-list)
615 (setq top-found-p nil)
616 (setq first (car rest)
617 rest (cdr rest)
618 path (car first)
619 buffers (cdr first)))
620 (t
621 ;; The first pass of clumping together worked out, go ahead
622 ;; with this result.
623 (when found-p
624 (setq top-found-p t)
625 (setq first (cons path buffers)
626 rest tmp-rest))
627 ;; Now see if we can clump more buffers together if we go up
628 ;; one step in the file hierarchy.
629 ;; If path isn't changed by msb--strip-dir, we are looking
630 ;; at the machine name component of an ange-ftp filename.
631 (setq old-path path)
632 (setq path (msb--strip-dir path)
633 buffers (cdr first))
634 (if (equal old-path path)
635 (setq last-path path))
636 (when (and last-path
637 (or (and (>= (length path) (length last-path))
638 (eq t (compare-strings
639 last-path 0 nil path 0
640 (length last-path)
641 completion-ignore-case)))
642 (and (< (length path) (length last-path))
643 (eq t (compare-strings
644 path 0 nil last-path 0 (length path)
645 completion-ignore-case)))))
646 ;; We have reached the same place in the file hierarchy as
647 ;; the last result, so we should quit at this point and
648 ;; take what we have as result.
649 (push (cons (msb--format-title top-found-p
650 (car first)
651 (length (cdr first)))
652 (cdr first))
653 final-list)
654 (setq top-found-p nil)
655 (setq first (car rest)
656 rest (cdr rest)
657 path (car first)
658 buffers (cdr first)))))))
659 ;; Now take care of the last item.
660 (when first
661 (push (cons (msb--format-title top-found-p
662 (car first)
663 (length (cdr first)))
664 (cdr first))
665 final-list))
666 (setq top-found-p nil)
667 (nreverse final-list)))
668
669 (defun msb--create-function-info (menu-cond-elt)
670 "Create a vector from an element MENU-COND-ELT of `msb-menu-cond'.
671 This takes the form:
672 \]BUFFER-LIST-VARIABLE CONDITION MENU-SORT-KEY MENU-TITLE ITEM-HANDLER SORTER)
673 See `msb-menu-cond' for a description of its elements."
674 (let* ((list-symbol (make-symbol "-msb-buffer-list"))
675 (tmp-ih (and (> (length menu-cond-elt) 3)
676 (nth 3 menu-cond-elt)))
677 (item-handler (if (and tmp-ih (fboundp tmp-ih))
678 tmp-ih
679 msb-item-handling-function))
680 (tmp-s (if (> (length menu-cond-elt) 4)
681 (nth 4 menu-cond-elt)
682 msb-item-sort-function))
683 (sorter (if (or (fboundp tmp-s)
684 (null tmp-s)
685 (eq tmp-s t))
686 tmp-s
687 msb-item-sort-function)))
688 (when (< (length menu-cond-elt) 3)
689 (error "Wrong format of msb-menu-cond"))
690 (when (and (> (length menu-cond-elt) 3)
691 (not (fboundp tmp-ih)))
692 (signal 'invalid-function (list tmp-ih)))
693 (when (and (> (length menu-cond-elt) 4)
694 tmp-s
695 (not (fboundp tmp-s))
696 (not (eq tmp-s t)))
697 (signal 'invalid-function (list tmp-s)))
698 (set list-symbol ())
699 (vector list-symbol ;BUFFER-LIST-VARIABLE
700 (nth 0 menu-cond-elt) ;CONDITION
701 (nth 1 menu-cond-elt) ;SORT-KEY
702 (nth 2 menu-cond-elt) ;MENU-TITLE
703 item-handler ;ITEM-HANDLER
704 sorter) ;SORTER
705 ))
706
707 ;; This defsubst is only used in `msb--choose-menu' below. It was
708 ;; pulled out merely to make the code somewhat clearer. The indentation
709 ;; level was too big.
710 (defsubst msb--collect (function-info-vector)
711 (let ((result nil)
712 (multi-flag nil)
713 function-info-list)
714 (setq function-info-list
715 (loop for fi
716 across function-info-vector
717 if (and (setq result
718 (eval (aref fi 1))) ;Test CONDITION
719 (not (and (eq result 'no-multi)
720 multi-flag))
721 (progn (when (eq result 'multi)
722 (setq multi-flag t))
723 t))
724 collect fi
725 until (and result
726 (not (eq result 'multi)))))
727 (when (and (not function-info-list)
728 (not result))
729 (error "No catch-all in msb-menu-cond!"))
730 function-info-list))
731
732 (defun msb--add-to-menu (buffer function-info max-buffer-name-length)
733 "Add BUFFER to the menu depicted by FUNCTION-INFO.
734 All side-effects. Adds an element of form (BUFFER-TITLE . BUFFER)
735 to the buffer-list variable in function-info."
736 (let ((list-symbol (aref function-info 0))) ;BUFFER-LIST-VARIABLE
737 ;; Here comes the hairy side-effect!
738 (set list-symbol
739 (cons (cons (funcall (aref function-info 4) ;ITEM-HANDLER
740 buffer
741 max-buffer-name-length)
742 buffer)
743 (eval list-symbol)))))
744
745 (defsubst msb--choose-menu (buffer function-info-vector max-buffer-name-length)
746 "Select the appropriate menu for BUFFER."
747 ;; This is all side-effects, folks!
748 ;; This should be optimized.
749 (unless (and (not msb-display-invisible-buffers-p)
750 (msb-invisible-buffer-p buffer))
751 (condition-case nil
752 (save-excursion
753 (set-buffer buffer)
754 ;; Menu found. Add to this menu
755 (dolist (info (msb--collect function-info-vector))
756 (msb--add-to-menu buffer info max-buffer-name-length)))
757 (error (unless msb--error
758 (setq msb--error
759 (format
760 "In msb-menu-cond, error for buffer `%s'."
761 (buffer-name buffer)))
762 (error "%s" msb--error))))))
763
764 (defun msb--create-sort-item (function-info)
765 "Return (SORT-KEY TITLE . BUFFER-LIST) or nil if the buffer-list is empty."
766 (let ((buffer-list (eval (aref function-info 0))))
767 (when buffer-list
768 (let ((sorter (aref function-info 5)) ;SORTER
769 (sort-key (aref function-info 2))) ;MENU-SORT-KEY
770 (when sort-key
771 (cons sort-key
772 (cons (format (aref function-info 3) ;MENU-TITLE
773 (length buffer-list))
774 (cond
775 ((null sorter)
776 buffer-list)
777 ((eq sorter t)
778 (nreverse buffer-list))
779 (t
780 (sort buffer-list sorter))))))))))
781
782 (defun msb--aggregate-alist (alist same-predicate sort-predicate)
783 "Return ALIST as a sorted, aggregated alist.
784
785 In the result all items with the same car element (according to
786 SAME-PREDICATE) are aggregated together. The alist is first sorted by
787 SORT-PREDICATE.
788
789 Example:
790 \(msb--aggregate-alist
791 '((a . a1) (a . a2) (b . b1) (c . c3) (a . a4) (a . a3) (b . b3) (b . b2))
792 (function string=)
793 (lambda (item1 item2)
794 (string< (symbol-name item1) (symbol-name item2))))
795 results in
796 \((a a1 a2 a4 a3) (b b1 b3 b2) (c c3))"
797 (when (not (null alist))
798 (let (result
799 same
800 tmp-old-car
801 tmp-same
802 (first-time-p t)
803 old-car)
804 (nconc
805 (apply #'nconc
806 (mapcar
807 (lambda (item)
808 (cond
809 (first-time-p
810 (push (cdr item) same)
811 (setq first-time-p nil)
812 (setq old-car (car item))
813 nil)
814 ((funcall same-predicate (car item) old-car)
815 (push (cdr item) same)
816 nil)
817 (t
818 (setq tmp-same same
819 tmp-old-car old-car)
820 (setq same (list (cdr item))
821 old-car (car item))
822 (list (cons tmp-old-car (nreverse tmp-same))))))
823 (sort alist (lambda (item1 item2)
824 (funcall sort-predicate (car item1) (car item2))))))
825 (list (cons old-car (nreverse same)))))))
826
827
828 (defun msb--mode-menu-cond ()
829 (let ((key msb-modes-key))
830 (mapcar (lambda (item)
831 (incf key)
832 (list `( eq major-mode (quote ,(car item)))
833 key
834 (concat (cdr item) " (%d)")))
835 (sort
836 (let ((mode-list nil))
837 (dolist (buffer (cdr (buffer-list)))
838 (save-excursion
839 (set-buffer buffer)
840 (when (and (not (msb-invisible-buffer-p))
841 (not (assq major-mode mode-list)))
842 (push (cons major-mode mode-name)
843 mode-list))))
844 mode-list)
845 (lambda (item1 item2)
846 (string< (cdr item1) (cdr item2)))))))
847
848 (defun msb--most-recently-used-menu (max-buffer-name-length)
849 "Return a list for the most recently used buffers.
850 It takes the form ((TITLE . BUFFER-LIST)...)."
851 (when (and (numberp msb-display-most-recently-used)
852 (> msb-display-most-recently-used 0))
853 (let* ((buffers (cdr (buffer-list)))
854 (most-recently-used
855 (loop with n = 0
856 for buffer in buffers
857 if (save-excursion
858 (set-buffer buffer)
859 (and (not (msb-invisible-buffer-p))
860 (not (eq major-mode 'dired-mode))))
861 collect (save-excursion
862 (set-buffer buffer)
863 (cons (funcall msb-item-handling-function
864 buffer
865 max-buffer-name-length)
866 buffer))
867 and do (incf n)
868 until (>= n msb-display-most-recently-used))))
869 (cons (if (stringp msb-most-recently-used-title)
870 (format msb-most-recently-used-title
871 (length most-recently-used))
872 (signal 'wrong-type-argument (list msb-most-recently-used-title)))
873 most-recently-used))))
874
875 (defun msb--create-buffer-menu-2 ()
876 (let ((max-buffer-name-length 0)
877 file-buffers
878 function-info-vector)
879 ;; Calculate the longest buffer name.
880 (dolist (buffer (buffer-list))
881 (when (or msb-display-invisible-buffers-p
882 (not (msb-invisible-buffer-p)))
883 (setq max-buffer-name-length
884 (max max-buffer-name-length (length (buffer-name buffer))))))
885 ;; Make a list with elements of type
886 ;; (BUFFER-LIST-VARIABLE
887 ;; CONDITION
888 ;; MENU-SORT-KEY
889 ;; MENU-TITLE
890 ;; ITEM-HANDLER
891 ;; SORTER)
892 ;; Uses "function-global" variables:
893 ;; function-info-vector
894 (setq function-info-vector
895 (apply (function vector)
896 (mapcar (function msb--create-function-info)
897 (append msb-menu-cond (msb--mode-menu-cond)))))
898 ;; Split the buffer-list into several lists; one list for each
899 ;; criteria. This is the most critical part with respect to time.
900 (dolist (buffer (buffer-list))
901 (cond ((and msb-files-by-directory
902 (buffer-file-name buffer)
903 ;; exclude ange-ftp buffers
904 ;;(not (string-match "\\/[^/:]+:"
905 ;; (buffer-file-name buffer)))
906 )
907 (push buffer file-buffers))
908 (t
909 (msb--choose-menu buffer
910 function-info-vector
911 max-buffer-name-length))))
912 (when file-buffers
913 (setq file-buffers
914 (mapcar (lambda (buffer-list)
915 (cons msb-files-by-directory-sort-key
916 (cons (car buffer-list)
917 (sort
918 (mapcar (function
919 (lambda (buffer)
920 (cons (save-excursion
921 (set-buffer buffer)
922 (funcall msb-item-handling-function
923 buffer
924 max-buffer-name-length))
925 buffer)))
926 (cdr buffer-list))
927 (function
928 (lambda (item1 item2)
929 (string< (car item1) (car item2))))))))
930 (msb--choose-file-menu file-buffers))))
931 ;; Now make the menu - a list of (TITLE . BUFFER-LIST)
932 (let* (menu
933 (most-recently-used
934 (msb--most-recently-used-menu max-buffer-name-length))
935 (others (nconc file-buffers
936 (loop for elt
937 across function-info-vector
938 for value = (msb--create-sort-item elt)
939 if value collect value))))
940 (setq menu
941 (mapcar 'cdr ;Remove the SORT-KEY
942 ;; Sort the menus - not the items.
943 (msb--add-separators
944 (sort
945 ;; Get a list of (SORT-KEY TITLE . BUFFER-LIST)
946 ;; Also sorts the items within the menus.
947 (if (cdr most-recently-used)
948 (cons
949 ;; Add most recent used buffers
950 (cons msb-most-recently-used-sort-key
951 most-recently-used)
952 others)
953 others)
954 (lambda (elt1 elt2)
955 (< (car elt1) (car elt2)))))))
956 ;; Now make it a keymap menu
957 (append
958 '(keymap "Select Buffer")
959 (msb--make-keymap-menu menu)
960 (when msb-separator-diff
961 (list (list 'separator "--")))
962 (list (cons 'toggle
963 (cons
964 (if msb-files-by-directory
965 "*Files by type*"
966 "*Files by directory*")
967 'msb--toggle-menu-type)))))))
968
969 (defun msb--create-buffer-menu ()
970 (save-match-data
971 (save-excursion
972 (msb--create-buffer-menu-2))))
973
974 (defun msb--toggle-menu-type ()
975 "Multi purpose function for selecting a buffer with the mouse."
976 (interactive)
977 (setq msb-files-by-directory (not msb-files-by-directory))
978 ;; This gets a warning, but it is correct,
979 ;; because this file redefines menu-bar-update-buffers.
980 (msb-menu-bar-update-buffers t))
981
982 (defun mouse-select-buffer (event)
983 "Pop up several menus of buffers, for selection with the mouse.
984 Returns the selected buffer or nil if no buffer is selected.
985
986 The way the buffers are split is conveniently handled with the
987 variable `msb-menu-cond'."
988 ;; Popup the menu and return the selected buffer.
989 (when (or msb--error
990 (not msb--last-buffer-menu)
991 (not (fboundp 'frame-or-buffer-changed-p))
992 (frame-or-buffer-changed-p))
993 (setq msb--error nil)
994 (setq msb--last-buffer-menu (msb--create-buffer-menu)))
995 (let ((position event)
996 choice)
997 (when (and (fboundp 'posn-x-y)
998 (fboundp 'posn-window))
999 (let ((posX (car (posn-x-y (event-start event))))
1000 (posY (cdr (posn-x-y (event-start event))))
1001 (posWind (posn-window (event-start event))))
1002 ;; adjust position
1003 (setq posX (- posX (funcall msb-horizontal-shift-function))
1004 position (list (list posX posY) posWind))))
1005 ;; This `sit-for' magically makes the menu stay up if the mouse
1006 ;; button is released within 0.1 second.
1007 (sit-for 0 100)
1008 ;; Popup the menu
1009 (setq choice (x-popup-menu position msb--last-buffer-menu))
1010 (cond
1011 ((eq (car choice) 'toggle)
1012 ;; Bring up the menu again with type toggled.
1013 (msb--toggle-menu-type)
1014 (mouse-select-buffer event))
1015 ((and (numberp (car choice))
1016 (null (cdr choice)))
1017 (let ((msb--last-buffer-menu (nthcdr 3 (assq (car choice)
1018 msb--last-buffer-menu))))
1019 (mouse-select-buffer event)))
1020 ((while (numberp (car choice))
1021 (setq choice (cdr choice))))
1022 ((and (stringp (car choice))
1023 (null (cdr choice)))
1024 (car choice))
1025 ((null choice)
1026 choice)
1027 (t
1028 (error "Unknown form for buffer: %s" choice)))))
1029
1030 ;; Add separators
1031 (defun msb--add-separators (sorted-list)
1032 (if (or (not msb-separator-diff)
1033 (not (numberp msb-separator-diff)))
1034 sorted-list
1035 (let ((last-key nil))
1036 (apply #'nconc
1037 (mapcar
1038 (lambda (item)
1039 (cond
1040 ((and msb-separator-diff
1041 last-key
1042 (> (- (car item) last-key)
1043 msb-separator-diff))
1044 (setq last-key (car item))
1045 (list (cons last-key 'separator)
1046 item))
1047 (t
1048 (setq last-key (car item))
1049 (list item))))
1050 sorted-list)))))
1051
1052 (defun msb--split-menus-2 (list mcount result)
1053 (cond
1054 ((> (length list) msb-max-menu-items)
1055 (let ((count 0)
1056 sub-name
1057 (tmp-list nil))
1058 (while (< count msb-max-menu-items)
1059 (push (pop list) tmp-list)
1060 (incf count))
1061 (setq tmp-list (nreverse tmp-list))
1062 (setq sub-name (concat (car (car tmp-list)) "..."))
1063 (push (nconc (list mcount sub-name
1064 'keymap sub-name)
1065 tmp-list)
1066 result))
1067 (msb--split-menus-2 list (1+ mcount) result))
1068 ((null result)
1069 list)
1070 (t
1071 (let (sub-name)
1072 (setq sub-name (concat (car (car list)) "..."))
1073 (push (nconc (list mcount sub-name 'keymap sub-name)
1074 list)
1075 result))
1076 (nreverse result))))
1077
1078 (defun msb--split-menus (list)
1079 (if (and (integerp msb-max-menu-items)
1080 (> msb-max-menu-items 0))
1081 (msb--split-menus-2 list 0 nil)
1082 list))
1083
1084 (defun msb--make-keymap-menu (raw-menu)
1085 (let ((end (cons '(nil) 'menu-bar-select-buffer))
1086 (mcount 0))
1087 (mapcar
1088 (lambda (sub-menu)
1089 (cond
1090 ((eq 'separator sub-menu)
1091 (list 'separator "--"))
1092 (t
1093 (let ((buffers (mapcar (lambda (item)
1094 (cons (buffer-name (cdr item))
1095 (cons (car item) end)))
1096 (cdr sub-menu))))
1097 (nconc (list (incf mcount) (car sub-menu)
1098 'keymap (car sub-menu))
1099 (msb--split-menus buffers))))))
1100 raw-menu)))
1101
1102 (defun msb-menu-bar-update-buffers (&optional arg)
1103 "A re-written version of `menu-bar-update-buffers'."
1104 ;; If user discards the Buffers item, play along.
1105 (when (and (lookup-key (current-global-map) [menu-bar buffer])
1106 (or (not (fboundp 'frame-or-buffer-changed-p))
1107 (frame-or-buffer-changed-p)
1108 arg))
1109 (let ((frames (frame-list))
1110 buffers-menu frames-menu)
1111 ;; Make the menu of buffers proper.
1112 (setq msb--last-buffer-menu (msb--create-buffer-menu))
1113 (setq buffers-menu msb--last-buffer-menu)
1114 ;; Make a Frames menu if we have more than one frame.
1115 (when (cdr frames)
1116 (let* ((frame-length (length frames))
1117 (f-title (format "Frames (%d)" frame-length)))
1118 ;; List only the N most recently selected frames
1119 (when (and (integerp msb-max-menu-items)
1120 (> msb-max-menu-items 1)
1121 (> frame-length msb-max-menu-items))
1122 (setcdr (nthcdr msb-max-menu-items frames) nil))
1123 (setq frames-menu
1124 (nconc
1125 (list 'frame f-title '(nil) 'keymap f-title)
1126 (mapcar
1127 (lambda (frame)
1128 (nconc
1129 (list frame
1130 (cdr (assq 'name
1131 (frame-parameters frame)))
1132 (cons nil nil))
1133 'menu-bar-select-frame))
1134 frames)))))
1135 (define-key (current-global-map) [menu-bar buffer]
1136 (cons "Buffers"
1137 (if (and buffers-menu frames-menu)
1138 ;; Combine Frame and Buffers menus with separator between
1139 (nconc (list 'keymap "Buffers and Frames" frames-menu
1140 (and msb-separator-diff '(separator "--")))
1141 (cddr buffers-menu))
1142 (or buffers-menu 'undefined)))))))
1143
1144 ;; Snarf current bindings of `mouse-buffer-menu' (normally
1145 ;; C-down-mouse-1).
1146 (defvar msb-mode-map
1147 (let ((map (make-sparse-keymap "Msb")))
1148 (mapcar (lambda (key)
1149 (define-key map key #'msb))
1150 (where-is-internal 'mouse-buffer-menu (make-sparse-keymap)))
1151 map))
1152
1153 ;;;###autoload
1154 (defun msb-mode (&optional arg)
1155 "Toggle Msb mode.
1156 With arg, turn Msb mode on if and only if arg is positive.
1157 This mode overrides the binding(s) of `mouse-buffer-menu' to provide a
1158 different buffer menu using the function `msb'."
1159 (interactive "P")
1160 (setq msb-mode (if arg
1161 (> (prefix-numeric-value arg) 0)
1162 (not msb-mode)))
1163 (if msb-mode
1164 (progn
1165 (add-hook 'menu-bar-update-hook 'msb-menu-bar-update-buffers)
1166 (remove-hook 'menu-bar-update-hook 'menu-bar-update-buffers))
1167 (remove-hook 'menu-bar-update-hook 'msb-menu-bar-update-buffers)
1168 (add-hook 'menu-bar-update-hook 'menu-bar-update-buffers))
1169 (run-hooks 'menu-bar-update-hook))
1170
1171 (defun msb-unload-hook ()
1172 (msb-mode 0))
1173
1174 (add-to-list 'minor-mode-map-alist (cons 'msb-mode msb-mode-map))
1175
1176 (provide 'msb)
1177 (eval-after-load 'msb (run-hooks 'msb-after-load-hooks))
1178
1179 ;;; msb.el ends here