bs.el 55.8 KB
Newer Older
1
;;; bs.el --- menu for selecting and displaying buffers -*- lexical-binding: t -*-
Gerd Moellmann's avatar
Gerd Moellmann committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1998-2019 Free Software Foundation, Inc.
Gerd Moellmann's avatar
Gerd Moellmann committed
4
;; Author: Olaf Sylvester <Olaf.Sylvester@netsurf.de>
5
;; Maintainer: emacs-devel@gnu.org
Gerd Moellmann's avatar
Gerd Moellmann committed
6 7 8 9
;; Keywords: convenience

;; This file is part of GNU Emacs.

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

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

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

;;; Commentary:

;; Version: 1.17
26
;; X-URL: http://www.geekware.de/software/emacs
Gerd Moellmann's avatar
Gerd Moellmann committed
27
;;
Juanma Barranquero's avatar
Juanma Barranquero committed
28
;; The bs-package contains a main function bs-show for popping up a
Gerd Moellmann's avatar
Gerd Moellmann committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42
;; buffer in a way similar to `list-buffers' and `electric-buffer-list':
;; The new buffer offers a Buffer Selection Menu for manipulating
;; the buffer list and buffers.
;;
;; -----------------------------------------------------------------------
;; | MR Buffer          Size  Mode          File                         |
;; | -- ------          ----  ----          ----                         |
;; |.   bs.el           14690  Emacs-Lisp    /home/sun/sylvester/el/bs.e$|
;; |  % executable.el    9429  Emacs-Lisp    /usr/share/emacs/19.34/lisp$|
;; |  % vc.el          104893  Emacs-Lisp    /usr/share/emacs/19.34/lisp$|
;; |  % test_vc.el        486  Emacs-Lisp    /home/sun/sylvester/el/test$|
;; |  % vc-hooks.el     43605  Emacs-Lisp    /usr/share/emacs/19.34/lisp$|
;; -----------------------------------------------------------------------

Juanma Barranquero's avatar
Juanma Barranquero committed
43
;;; Quick Installation and Customization:
Gerd Moellmann's avatar
Gerd Moellmann committed
44

45
;; To display the bs menu, do
Gerd Moellmann's avatar
Gerd Moellmann committed
46
;;   M-x bs-show
47 48
;; To customize its behavior, do
;;   M-x bs-customize
Gerd Moellmann's avatar
Gerd Moellmann committed
49 50 51 52 53 54 55 56 57 58 59 60 61

;;; More Commentary:

;; bs-show will generate a new buffer named *buffer-selection*, which shows
;; all buffers or a subset of them, and has possibilities for deleting,
;; saving and selecting buffers. For more details see docstring of
;; function `bs-mode'. A current configuration describes which buffers appear
;; in *buffer-selection*. See docstring of variable `bs-configurations' for
;; more details.
;;
;; The package bs combines the advantages of the Emacs functions
;; `list-buffers' and `electric-buffer-list'.
;;
62
;; Additional features for Buffer Selection Menu:
Gerd Moellmann's avatar
Gerd Moellmann committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
;;  - configurable list of buffers (show only files etc.).
;;  - comfortable way to change displayed subset of all buffers.
;;  - show sorted list of buffers.
;;  - cyclic navigation:
;;     - goes to top of buffer list if you are on last line and press down.
;;     - goes to end of buffer list if you are on first line and press up.
;;  - Offer an alternative buffer list by prefix key C-u.

;;; Cycling through buffers

;; This package offers two functions for buffer cycling. If you want to cycle
;; through buffer list you can use `bs-cycle-next' or `bs-cycle-previous'.
;; Bind these function to a key like
;;   (global-set-key [(f9)]   'bs-cycle-previous)
;;   (global-set-key [(f10)]  'bs-cycle-next)
;;
;; Both functions use a special subset of all buffers for cycling to avoid
;; to go through internal buffers like *Messages*.
;;
;; Cycling through buffers ignores sorting because sorting destroys
;; the logical buffer list. If buffer list is sorted by size you
;; won't be able to cycle to the smallest buffer.

;;; Customization:

;; There is a customization group called `bs' in group `convenience'.
;; Start customization by M-x bs-customize
;;
;; Buffer list
;; -----------
;; You can define your own configurations by extending variable
;; `bs-configurations' (see docstring for details).
;;
;; `bs-default-configuration' contains the name of default configuration.
;; The default value is "files" which means to show only files.
;;
;; If you always want to see all buffers, customize variable
;; `bs-default-configuration' in customization group `bs'.
;;
;; Configure sorting
;; -----------------
;; You can define functions for sorting the buffer list.
;; When selecting buffers, you can step through available sorting
;; methods with key 'S'.
;; To define a new way of sorting, customize variable `bs-sort-functions'.
;;
;; There are four basic functions for sorting:
;;   by buffer name, by mode, by size, or by filename
;;
;; Configure buffer cycling
;; ------------------------
;; When cycling through buffer list the functions for cycling will use
;; the current configuration of bs to calculate the buffer list.
;; If you want to use a different configuration for cycling you have to set
;; the variable `bs-cycle-configuration-name'. You can customize this variable.
;;
;; For example: If you use the configuration called "files-and-scratch" you
;; can cycle through all file buffers and *scratch* although your current
;; configuration perhaps is "files" which ignores buffer *scratch*.

;;; History:

;;; Code:

;; ----------------------------------------------------------------------
;; Globals for customization
;; ----------------------------------------------------------------------

(defgroup bs nil
  "Buffer Selection: Maintaining buffers by buffer menu."
Dave Love's avatar
Dave Love committed
133
  :version "21.1"
Dave Love's avatar
Dave Love committed
134
  :link '(emacs-commentary-link "bs")
135
  :link '(url-link "http://www.geekware.de/software/emacs")
Gerd Moellmann's avatar
Gerd Moellmann committed
136 137
  :group 'convenience)

138 139
(defgroup bs-appearance nil
  "Buffer Selection appearance: Appearance of bs buffer menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153
  :group 'bs)

(defcustom bs-attributes-list
  '((""       1   1 left  bs--get-marked-string)
    ("M"      1   1 left  bs--get-modified-string)
    ("R"      2   2 left  bs--get-readonly-string)
    ("Buffer" bs--get-name-length 10 left  bs--get-name)
    (""       1   1 left  " ")
    ("Size"   8   8 right bs--get-size-string)
    (""       1   1 left  " ")
    ("Mode"   12 12 right bs--get-mode-name)
    (""       2   2 left  "  ")
    ("File"   12 12 left  bs--get-file-name)
    (""       2   2 left  "  "))
154
  "List specifying the layout of a Buffer Selection Menu buffer.
Gerd Moellmann's avatar
Gerd Moellmann committed
155
Each entry specifies a column and is a list of the form of:
156
\(HEADER MINIMUM-LENGTH MAXIMUM-LENGTH ALIGNMENT FUN-OR-STRING)
157 158 159 160 161 162 163 164 165 166 167

HEADER         : String for header for first line or a function
                 which calculates column title.
MINIMUM-LENGTH : Minimum width of column (number or name of function).
                 The function must return a positive integer.
MAXIMUM-LENGTH : Maximum width of column (number or name of function)
                 (currently ignored).
ALIGNMENT      : Alignment of column (`left', `right', `middle').
FUN-OR-STRING  : Name of a function for calculating the value or a
                 string for a constant value.

168
The function gets as parameter the buffer where we have started
Gerd Moellmann's avatar
Gerd Moellmann committed
169
buffer selection and the list of all buffers to show.  The function must
170 171
return a string representing the column's value."
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
172 173 174 175
  :type '(repeat sexp))

(defun bs--make-header-match-string ()
  "Return a regexp matching the first line of a Buffer Selection Menu buffer."
176
  (concat "^\\(" (mapconcat #'car bs-attributes-list " *") " *$\\)"))
Gerd Moellmann's avatar
Gerd Moellmann committed
177

178
;; Font-Lock-Settings
Gerd Moellmann's avatar
Gerd Moellmann committed
179
(defvar bs-mode-font-lock-keywords
180
  (list ;; header in font-lock-type-face
Dave Love's avatar
Dave Love committed
181 182 183
   (list (bs--make-header-match-string)
	 '(1 font-lock-type-face append) '(1 'bold append))
   ;; Buffername embedded by *
184
   (list "^\\(.*\\*.*\\*.*\\)$" 1 'font-lock-constant-face)
Dave Love's avatar
Dave Love committed
185
   ;; Dired-Buffers
Yoni Rabkin's avatar
Yoni Rabkin committed
186
   '("^..\\(.*Dired .*\\)$" 1 font-lock-function-name-face)
Dave Love's avatar
Dave Love committed
187 188
   ;; the star for modified buffers
   '("^.\\(\\*\\) +[^\\*]"     1 font-lock-comment-face))
Gerd Moellmann's avatar
Gerd Moellmann committed
189 190 191
  "Default font lock expressions for Buffer Selection Menu.")

(defcustom bs-max-window-height 20
192
  "Maximal window height of Buffer Selection Menu."
193
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  :type 'integer)

(defvar bs-dont-show-regexp nil
  "Regular expression specifying which buffers not to show.
A buffer whose name matches this regular expression will not be
included in the buffer list.")

(defvar bs-must-show-regexp nil
  "Regular expression for specifying buffers which must be shown.
A buffer whose name matches this regular expression will be
included in the buffer list.
Note that this variable is temporary: if the configuration is changed
it is reset to nil.  Use `bs-must-always-show-regexp' to specify buffers
that must always be shown regardless of the configuration.")

(defcustom bs-must-always-show-regexp nil
210
  "Regular expression for specifying buffers to show always.
Gerd Moellmann's avatar
Gerd Moellmann committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
A buffer whose name matches this regular expression will
be shown regardless of current configuration of Buffer Selection Menu."
  :group 'bs
  :type '(choice (const :tag "Nothing at all" nil) regexp))

(defvar bs-dont-show-function nil
  "Function for specifying buffers not to show.
The function gets one argument - the buffer to test.  The function must
return a value different from nil to ignore the buffer in
Buffer Selection Menu.")

(defvar bs-must-show-function nil
  "Function for specifying buffers which must be shown.
The function gets one argument - the buffer to test.")

(defvar bs-buffer-sort-function nil
  "Sort function to sort the buffers that appear in Buffer Selection Menu.
228 229
The function gets two arguments - the buffers to compare.
It must return non-nil if the first buffer should sort before the second.")
Gerd Moellmann's avatar
Gerd Moellmann committed
230 231

(defcustom bs-maximal-buffer-name-column 45
232
  "Maximum column width for buffer names.
Gerd Moellmann's avatar
Gerd Moellmann committed
233 234 235 236
The column for buffer names has dynamic width.  The width depends on
maximal and minimal length of names of buffers to show.  The maximal
width is bounded by `bs-maximal-buffer-name-column'.
See also `bs-minimal-buffer-name-column'."
237
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
238 239 240
  :type 'integer)

(defcustom bs-minimal-buffer-name-column 15
241
  "Minimum column width for buffer names.
Gerd Moellmann's avatar
Gerd Moellmann committed
242 243 244 245
The column for buffer names has dynamic width.  The width depends on
maximal and minimal length of names of buffers to show.  The minimal
width is bounded by `bs-minimal-buffer-name-column'.
See also `bs-maximal-buffer-name-column'."
246
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
247 248 249 250 251 252 253 254
  :type 'integer)

(defconst bs-header-lines-length 2
  "Number of lines for headers in Buffer Selection Menu.")

(defcustom bs-configurations
  '(("all" nil nil nil nil nil)
    ("files" nil nil nil bs-visits-non-file bs-sort-buffer-interns-are-last)
255
    ("files-and-scratch" "^\\*scratch\\*$" nil nil bs-visits-non-file
Gerd Moellmann's avatar
Gerd Moellmann committed
256 257
     bs-sort-buffer-interns-are-last)
    ("all-intern-last" nil nil nil nil bs-sort-buffer-interns-are-last))
258
  "List of all configurations you can use in the Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
259
A configuration describes which buffers appear in Buffer Selection Menu
260
and also the order of buffers.  A configuration is a list with
Gerd Moellmann's avatar
Gerd Moellmann committed
261 262
six elements.  The first element is a string and describes the configuration.
The following five elements represent the values for Buffer Selection Menu
263 264
configuration variables `bs-must-show-regexp', `bs-must-show-function',
`bs-dont-show-regexp', `bs-dont-show-function' and `bs-buffer-sort-function'.
Gerd Moellmann's avatar
Gerd Moellmann committed
265
By setting these variables you define a configuration."
266
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
267 268 269
  :type '(repeat sexp))

(defcustom bs-default-configuration "files"
270
  "Name of default configuration used by the Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
271 272 273 274 275 276 277
\\<bs-mode-map>
Will be changed using key \\[bs-select-next-configuration].
Must be a string used in `bs-configurations' for naming a configuration."
  :group 'bs
  :type 'string)

(defcustom bs-alternative-configuration "all"
278
  "Name of configuration used when calling `bs-show' with \
Gerd Moellmann's avatar
Gerd Moellmann committed
279 280 281 282 283 284 285
\\[universal-argument] as prefix key.
Must be a string used in `bs-configurations' for naming a configuration."
  :group 'bs
  :type  'string)

(defvar bs-current-configuration bs-default-configuration
  "Name of current configuration.
286
Must be a string used in `bs-configurations' for naming a configuration.")
Gerd Moellmann's avatar
Gerd Moellmann committed
287 288

(defcustom bs-cycle-configuration-name nil
289
  "Name of configuration used when cycling through the buffer list.
Gerd Moellmann's avatar
Gerd Moellmann committed
290 291 292 293 294 295 296
A value of nil means to use current configuration `bs-default-configuration'.
Must be a string used in `bs-configurations' for naming a configuration."
  :group 'bs
  :type '(choice (const :tag "like current configuration" nil)
   string))

(defcustom bs-string-show-always "+"
297
  "String added in column 1 indicating a buffer will always be shown."
298
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
299 300 301
  :type 'string)

(defcustom bs-string-show-never "-"
302
  "String added in column 1 indicating a buffer will never be shown."
303
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
304 305 306
  :type 'string)

(defcustom bs-string-current "."
307
  "String added in column 1 indicating the current buffer."
308
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
309 310 311
  :type 'string)

(defcustom bs-string-current-marked "#"
312
  "String added in column 1 indicating the current buffer when it is marked."
313
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
314 315 316
  :type 'string)

(defcustom bs-string-marked ">"
317
  "String added in column 1 indicating a marked buffer."
318
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
319 320 321
  :type 'string)

(defcustom bs-string-show-normally  " "
322
  "String added in column 1 indicating an unmarked buffer."
323
  :group 'bs-appearance
Gerd Moellmann's avatar
Gerd Moellmann committed
324 325 326 327 328 329 330
  :type 'string)

(defvar bs--name-entry-length 20
  "Maximum length of all displayed buffer names.
Used internally, only.")

;; ----------------------------------------------------------------------
331
;; Internal globals
Gerd Moellmann's avatar
Gerd Moellmann committed
332 333
;; ----------------------------------------------------------------------

334
(defvar-local bs-buffer-show-mark nil
Gerd Moellmann's avatar
Gerd Moellmann committed
335
  "Flag for the current mode for showing this buffer.
336 337
A value of nil means buffer will be shown depending on the current
configuration.
Gerd Moellmann's avatar
Gerd Moellmann committed
338 339 340 341 342 343
A value of `never' means to never show the buffer.
A value of `always' means to show buffer regardless of the configuration.")

(defun bs--sort-by-name (b1 b2)
  "Compare buffers B1 and B2 by buffer name."
  (string< (buffer-name b1)
Dave Love's avatar
Dave Love committed
344
	   (buffer-name b2)))
Gerd Moellmann's avatar
Gerd Moellmann committed
345 346 347 348

(defun bs--sort-by-filename (b1 b2)
  "Compare buffers B1 and B2 by file name."
  (string< (or (buffer-file-name b1) "")
Dave Love's avatar
Dave Love committed
349
	   (or (buffer-file-name b2) "")))
Gerd Moellmann's avatar
Gerd Moellmann committed
350 351 352

(defun bs--sort-by-mode (b1 b2)
  "Compare buffers B1 and B2 by mode name."
353 354 355
  (save-current-buffer
    (string< (progn (set-buffer b1) (format-mode-line mode-name nil nil b1))
	     (progn (set-buffer b2) (format-mode-line mode-name nil nil b2)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
356 357 358

(defun bs--sort-by-size (b1 b2)
  "Compare buffers B1 and B2 by buffer size."
359
  (< (buffer-size b1) (buffer-size b2)))
Gerd Moellmann's avatar
Gerd Moellmann committed
360 361 362 363 364 365 366

(defcustom bs-sort-functions
  '(("by name"     bs--sort-by-name     "Buffer" region)
    ("by size"     bs--sort-by-size     "Size"   region)
    ("by mode"     bs--sort-by-mode     "Mode"   region)
    ("by filename" bs--sort-by-filename "File"   region)
    ("by nothing"  nil                  nil      nil))
367
  "List of all possible sorting aspects for Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
368
You can add a new entry with a call to `bs-define-sort-function'.
369
Each element is a list of four elements (NAME FUNCTION REGEXP-FOR-SORTING FACE).
Gerd Moellmann's avatar
Gerd Moellmann committed
370
NAME specifies the sort order defined by function FUNCTION.
371
FUNCTION nil means don't sort the buffer list.  Otherwise the function
Gerd Moellmann's avatar
Gerd Moellmann committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
must have two parameters - the buffers to compare.
REGEXP-FOR-SORTING is a regular expression which describes the
column title to highlight.
FACE is a face used to fontify the sorted column title.  A value of nil means
don't highlight."
  :group 'bs
  :type '(repeat sexp))

(defun bs-define-sort-function (name fun &optional regexp-for-sorting face)
  "Define a new function for buffer sorting in Buffer Selection Menu.
NAME specifies the sort order defined by function FUN.
A value of nil for FUN means don't sort the buffer list.  Otherwise the
functions must have two parameters - the buffers to compare.
REGEXP-FOR-SORTING is a regular expression which describes the
column title to highlight.
FACE is a face used to fontify the sorted column title.  A value of nil means
don't highlight.
The new sort aspect will be inserted into list `bs-sort-functions'."
  (let ((tupel (assoc name bs-sort-functions)))
    (if tupel
Dave Love's avatar
Dave Love committed
392
	(setcdr tupel (list fun regexp-for-sorting face))
Gerd Moellmann's avatar
Gerd Moellmann committed
393
      (setq bs-sort-functions
Dave Love's avatar
Dave Love committed
394 395
	    (cons (list name fun regexp-for-sorting face)
		  bs-sort-functions)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
396 397 398 399 400 401

(defvar bs--current-sort-function nil
  "Description of the current function for sorting the buffer list.
This is an element of `bs-sort-functions'.")

(defcustom bs-default-sort-name "by nothing"
402
  "Name of default sort behavior.
Gerd Moellmann's avatar
Gerd Moellmann committed
403 404 405 406 407
Must be \"by nothing\" or a string used in `bs-sort-functions' for
naming a sort behavior.  Default is \"by nothing\" which means no sorting."
  :group 'bs
  :type  'string
  :set (lambda (var-name value)
Dave Love's avatar
Dave Love committed
408 409 410
	 (set var-name value)
	 (setq bs--current-sort-function
	       (assoc value bs-sort-functions))))
Gerd Moellmann's avatar
Gerd Moellmann committed
411 412 413 414 415 416

(defvar bs--buffer-coming-from nil
  "The buffer in which the user started the current Buffer Selection Menu.")

(defvar bs--show-all nil
  "Flag whether showing all buffers regardless of current configuration.
417
Non-nil means to show all buffers.  Otherwise show buffers
Gerd Moellmann's avatar
Gerd Moellmann committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
defined by current configuration `bs-current-configuration'.")

(defvar bs--window-config-coming-from nil
  "Window configuration before starting Buffer Selection Menu.")

(defvar bs--intern-show-never "^ \\|\\*buffer-selection\\*"
  "Regular expression specifying which buffers never to show.
A buffer whose name matches this regular expression will never be
included in the buffer list.")

(defvar bs-current-list nil
  "List of buffers shown in Buffer Selection Menu.
Used internally, only.")

(defvar bs--marked-buffers nil
  "Currently marked buffers in Buffer Selection Menu.")

Alex Schroeder's avatar
Alex Schroeder committed
435 436 437 438 439 440
(defvar bs-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map " "       'bs-select)
    (define-key map "f"       'bs-select)
    (define-key map "v"       'bs-view)
    (define-key map "!"       'bs-select-in-one-window)
441
    (define-key map [mouse-2] 'bs-mouse-select)
Alex Schroeder's avatar
Alex Schroeder committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    (define-key map "F"       'bs-select-other-frame)
    (let ((key ?1))
      (while (<= key ?9)
	(define-key map (char-to-string key) 'digit-argument)
	(setq key (1+ key))))
    (define-key map "-"       'negative-argument)
    (define-key map "\e-"     'negative-argument)
    (define-key map "o"       'bs-select-other-window)
    (define-key map "\C-o"    'bs-tmp-select-other-window)
    (define-key map [mouse-3] 'bs-mouse-select-other-frame)
    (define-key map [up]      'bs-up)
    (define-key map "n"       'bs-down)
    (define-key map "p"       'bs-up)
    (define-key map [down]    'bs-down)
    (define-key map "\C-m"    'bs-select)
    (define-key map "b"       'bs-bury-buffer)
    (define-key map "s"       'bs-save)
    (define-key map "S"       'bs-show-sorted)
    (define-key map "a"       'bs-toggle-show-all)
    (define-key map "d"       'bs-delete)
    (define-key map "\C-d"    'bs-delete-backward)
    (define-key map "k"       'bs-delete)
    (define-key map "g"       'bs-refresh)
    (define-key map "C"       'bs-set-configuration-and-refresh)
    (define-key map "c"       'bs-select-next-configuration)
    (define-key map "q"       'bs-kill)
    ;; (define-key map "z"       'bs-kill)
    (define-key map "\C-c\C-c" 'bs-kill)
    (define-key map "\C-g"    'bs-abort)
    (define-key map "\C-]"    'bs-abort)
    (define-key map "%"       'bs-toggle-readonly)
    (define-key map "~"       'bs-clear-modified)
    (define-key map "M"       'bs-toggle-current-to-show)
    (define-key map "+"       'bs-set-current-buffer-to-show-always)
    ;;(define-key map "-"       'bs-set-current-buffer-to-show-never)
    (define-key map "t"       'bs-visit-tags-table)
    (define-key map "m"       'bs-mark-current)
    (define-key map "u"       'bs-unmark-current)
480 481
    (define-key map "U"       'bs-unmark-all)
    (define-key map "\177"    'bs-unmark-previous)
Alex Schroeder's avatar
Alex Schroeder committed
482 483 484 485
    (define-key map ">"       'scroll-right)
    (define-key map "<"       'scroll-left)
    (define-key map "?"       'bs-help)
    map)
Gerd Moellmann's avatar
Gerd Moellmann committed
486 487 488 489 490 491 492 493
  "Keymap of `bs-mode'.")

;; ----------------------------------------------------------------------
;; Functions
;; ----------------------------------------------------------------------

(defun bs-buffer-list (&optional list sort-description)
  "Return a list of buffers to be shown.
494
LIST is a list of buffers to test for appearance in Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
495 496 497 498 499 500
The result list depends on the global variables `bs-dont-show-regexp',
`bs-must-show-regexp', `bs-dont-show-function', `bs-must-show-function'
and `bs-buffer-sort-function'.
If SORT-DESCRIPTION isn't nil the list will be sorted by
a special function.  SORT-DESCRIPTION is an element of `bs-sort-functions'."
  (setq sort-description (or sort-description bs--current-sort-function)
Dave Love's avatar
Dave Love committed
501
	list (or list (buffer-list)))
Gerd Moellmann's avatar
Gerd Moellmann committed
502
  (let ((result nil))
503 504 505
    (dolist (buf list)
      (let* ((buffername (buffer-name buf))
	     (int-show-never (string-match-p bs--intern-show-never buffername))
Dave Love's avatar
Dave Love committed
506
	     (ext-show-never (and bs-dont-show-regexp
507 508
				  (string-match-p bs-dont-show-regexp
						  buffername)))
Dave Love's avatar
Dave Love committed
509
	     (extern-must-show (or (and bs-must-always-show-regexp
510
					(string-match-p
Dave Love's avatar
Dave Love committed
511 512 513
					 bs-must-always-show-regexp
					 buffername))
				   (and bs-must-show-regexp
514 515
					(string-match-p bs-must-show-regexp
							buffername))))
Dave Love's avatar
Dave Love committed
516 517
	     (extern-show-never-from-fun (and bs-dont-show-function
					      (funcall bs-dont-show-function
518
						       buf)))
Dave Love's avatar
Dave Love committed
519 520
	     (extern-must-show-from-fun (and bs-must-show-function
					     (funcall bs-must-show-function
521 522 523 524 525 526 527 528 529 530 531
						      buf)))
	     (show-flag (buffer-local-value 'bs-buffer-show-mark buf)))
	(when (or (eq show-flag 'always)
		  (and (or bs--show-all (not (eq show-flag 'never)))
		       (not int-show-never)
		       (or bs--show-all
			   extern-must-show
			   extern-must-show-from-fun
			   (and (not ext-show-never)
				(not extern-show-never-from-fun)))))
	  (setq result (cons buf result)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
532 533 534 535
    (setq result (reverse result))
    ;; The current buffer which was the start point of bs should be an element
    ;; of result list, so that we can leave with space and be back in the
    ;; buffer we started bs-show.
536 537 538 539
    (when (and bs--buffer-coming-from
	       (buffer-live-p bs--buffer-coming-from)
	       (not (memq bs--buffer-coming-from result)))
      (setq result (cons bs--buffer-coming-from result)))
Gerd Moellmann's avatar
Gerd Moellmann committed
540 541
    ;; sorting
    (if (and sort-description
Dave Love's avatar
Dave Love committed
542 543
	     (nth 1 sort-description))
	(setq result (sort result (nth 1 sort-description)))
Gerd Moellmann's avatar
Gerd Moellmann committed
544 545 546 547 548 549 550 551 552 553 554
      ;; else standard sorting
      (bs-buffer-sort result))))

(defun bs-buffer-sort (buffer-list)
  "Sort buffers in BUFFER-LIST according to `bs-buffer-sort-function'."
  (if bs-buffer-sort-function
      (sort buffer-list bs-buffer-sort-function)
    buffer-list))

(defun bs--redisplay (&optional keep-line-p sort-description)
  "Redisplay whole Buffer Selection Menu.
555
If KEEP-LINE-P is non-nil the point will stay on current line.
556
SORT-DESCRIPTION is an element of `bs-sort-functions'."
557
  (let ((line (count-lines 1 (point))))
Gerd Moellmann's avatar
Gerd Moellmann committed
558
    (bs-show-in-buffer (bs-buffer-list nil sort-description))
559
    (when keep-line-p
560 561
      (goto-char (point-min))
      (forward-line line))
Gerd Moellmann's avatar
Gerd Moellmann committed
562 563 564 565 566 567
    (beginning-of-line)))

(defun bs--goto-current-buffer ()
  "Goto line which represents the current buffer;
actually the line which begins with character in `bs-string-current' or
`bs-string-current-marked'."
Dave Love's avatar
Dave Love committed
568 569 570 571 572
  (let ((regexp (concat "^"
			(regexp-quote bs-string-current)
			"\\|^"
			(regexp-quote bs-string-current-marked)))
	point)
Gerd Moellmann's avatar
Gerd Moellmann committed
573 574
    (save-excursion
      (goto-char (point-min))
575 576 577 578
      (when (search-forward-regexp regexp nil t)
	(setq point (1- (point)))))
    (when point
      (goto-char point))))
Gerd Moellmann's avatar
Gerd Moellmann committed
579 580 581 582 583 584

(defun bs--current-config-message ()
  "Return a string describing the current `bs-mode' configuration."
  (if bs--show-all
      "Show all buffers."
    (format "Show buffer by configuration %S"
Dave Love's avatar
Dave Love committed
585
	    bs-current-configuration)))
Gerd Moellmann's avatar
Gerd Moellmann committed
586

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
(defun bs--track-window-changes (frame)
  "Track window changes to refresh the buffer list.
Used from `window-size-change-functions'."
  (let ((win (get-buffer-window "*buffer-selection*" frame)))
    (when win
      (with-selected-window win
	(bs--set-window-height)))))

(defun bs--remove-hooks ()
  "Remove `bs--track-window-changes' and auxiliary hooks."
  (remove-hook 'window-size-change-functions 'bs--track-window-changes)
  ;; Remove itself
  (remove-hook 'kill-buffer-hook 'bs--remove-hooks t)
  (remove-hook 'change-major-mode-hook 'bs--remove-hooks t))

602 603
(put 'bs-mode 'mode-class 'special)

604
(define-derived-mode bs-mode nil "Buffer-Selection-Menu"
605
  "Major mode for editing a subset of Emacs's buffers.
Gerd Moellmann's avatar
Gerd Moellmann committed
606 607 608
\\<bs-mode-map>
Aside from two header lines each line describes one buffer.
Move to a line representing the buffer you want to edit and select
609
buffer by \\[bs-select] or SPC.  Abort buffer list with \\[bs-kill].
Gerd Moellmann's avatar
Gerd Moellmann committed
610 611 612 613 614 615 616 617 618 619
There are many key commands similar to `Buffer-menu-mode' for
manipulating the buffer list and buffers.
For faster navigation each digit key is a digit argument.

\\[bs-select] or SPACE -- select current line's buffer and other marked buffers.
\\[bs-toggle-show-all]  -- toggle between all buffers and a special subset.
\\[bs-select-other-window] -- select current line's buffer in other window.
\\[bs-tmp-select-other-window] -- make another window display that buffer and
    remain in Buffer Selection Menu.
\\[bs-mouse-select] -- select current line's buffer and other marked buffers.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
620 621
\\[bs-save] -- save current line's buffer immediately.
\\[bs-delete] -- kill current line's buffer immediately.
Gerd Moellmann's avatar
Gerd Moellmann committed
622 623 624 625
\\[bs-toggle-readonly] -- toggle read-only status of current line's buffer.
\\[bs-clear-modified] -- clear modified-flag on that buffer.
\\[bs-mark-current] -- mark current line's buffer to be displayed.
\\[bs-unmark-current] -- unmark current line's buffer to be displayed.
626 627
\\[bs-unmark-all] -- unmark all buffer lines.
\\[bs-unmark-previous] -- unmark previous line's buffer to be displayed.
Gerd Moellmann's avatar
Gerd Moellmann committed
628 629 630 631 632 633
\\[bs-show-sorted] -- display buffer list sorted by next sort aspect.
\\[bs-set-configuration-and-refresh] -- ask user for a configuration and \
apply selected configuration.
\\[bs-select-next-configuration] -- select and apply next \
available Buffer Selection Menu configuration.
\\[bs-kill] -- leave Buffer Selection Menu without a selection.
634
\\[bs-toggle-current-to-show] -- toggle status of appearance.
Gerd Moellmann's avatar
Gerd Moellmann committed
635 636
\\[bs-set-current-buffer-to-show-always] -- mark current line's buffer \
to show always.
637
\\[bs-visit-tags-table] -- call `visit-tags-table' on current line's buffer.
Gerd Moellmann's avatar
Gerd Moellmann committed
638
\\[bs-help] -- display this help text."
639
  (buffer-disable-undo)
640
  (setq buffer-read-only t
Dave Love's avatar
Dave Love committed
641
	truncate-lines t
642 643 644 645 646
	show-trailing-whitespace nil)
  (setq-local font-lock-defaults '(bs-mode-font-lock-keywords t))
  (setq-local font-lock-verbose nil)
  (setq-local font-lock-global-modes '(not bs-mode))
  (setq-local revert-buffer-function 'bs-refresh)
647 648 649
  (add-hook 'window-size-change-functions 'bs--track-window-changes)
  (add-hook 'kill-buffer-hook 'bs--remove-hooks nil t)
  (add-hook 'change-major-mode-hook 'bs--remove-hooks nil t))
Gerd Moellmann's avatar
Gerd Moellmann committed
650

651 652 653
(defun bs--restore-window-config ()
  "Restore window configuration on the current frame."
  (when bs--window-config-coming-from
654 655 656 657
    (let ((frame (selected-frame)))
      (unwind-protect
	   (set-window-configuration bs--window-config-coming-from)
	(select-frame frame)))
658 659
    (setq bs--window-config-coming-from nil)))

Gerd Moellmann's avatar
Gerd Moellmann committed
660
(defun bs-kill ()
661
  "Let buffer disappear and reset window configuration."
Gerd Moellmann's avatar
Gerd Moellmann committed
662 663
  (interactive)
  (bury-buffer (current-buffer))
664
  (bs--restore-window-config))
Gerd Moellmann's avatar
Gerd Moellmann committed
665 666 667

(defun bs-abort ()
  "Ding and leave Buffer Selection Menu without a selection."
Dave Love's avatar
Dave Love committed
668
  (interactive)
Gerd Moellmann's avatar
Gerd Moellmann committed
669 670 671 672 673 674 675 676 677 678
  (ding)
  (bs-kill))

(defun bs-set-configuration-and-refresh ()
  "Ask user for a configuration and apply selected configuration.
Refresh whole Buffer Selection Menu."
  (interactive)
  (call-interactively 'bs-set-configuration)
  (bs--redisplay t))

679
(defun bs-refresh (&rest _ignored)
680 681
  "Refresh whole Buffer Selection Menu.
Arguments are IGNORED (for `revert-buffer')."
Gerd Moellmann's avatar
Gerd Moellmann committed
682 683 684 685 686 687
  (interactive)
  (bs--redisplay t))

(defun bs--set-window-height ()
  "Change the height of the selected window to suit the current buffer list."
  (unless (one-window-p t)
688
    (fit-window-to-buffer (selected-window) bs-max-window-height)))
Gerd Moellmann's avatar
Gerd Moellmann committed
689 690 691

(defun bs--current-buffer ()
  "Return buffer on current line.
692
Raise an error if not on a buffer line."
Gerd Moellmann's avatar
Gerd Moellmann committed
693 694
  (beginning-of-line)
  (let ((line (+ (- bs-header-lines-length)
Dave Love's avatar
Dave Love committed
695
		 (count-lines 1 (point)))))
696 697
    (when (< line 0)
      (error "You are on a header row"))
Gerd Moellmann's avatar
Gerd Moellmann committed
698 699 700 701 702
    (nth line bs-current-list)))

(defun bs--update-current-line ()
  "Update the entry on current line for Buffer Selection Menu."
  (let ((buffer (bs--current-buffer))
Dave Love's avatar
Dave Love committed
703
	(inhibit-read-only t))
Gerd Moellmann's avatar
Gerd Moellmann committed
704 705 706 707 708 709 710 711 712 713 714 715 716 717
    (beginning-of-line)
    (delete-region (point) (line-end-position))
    (bs--insert-one-entry buffer)
    (beginning-of-line)))

(defun bs-view ()
  "View current line's buffer in View mode.
Leave Buffer Selection Menu."
  (interactive)
  (view-buffer (bs--current-buffer)))

(defun bs-select ()
  "Select current line's buffer and other marked buffers.
If there are no marked buffers the window configuration before starting
718
Buffer Selection Menu will be restored.
Gerd Moellmann's avatar
Gerd Moellmann committed
719 720 721 722 723 724
If there are marked buffers each marked buffer and the current line's buffer
will be selected in a window.
Leave Buffer Selection Menu."
  (interactive)
  (let ((buffer (bs--current-buffer)))
    (bury-buffer (current-buffer))
725
    (bs--restore-window-config)
Gerd Moellmann's avatar
Gerd Moellmann committed
726
    (switch-to-buffer buffer)
727 728 729 730 731 732 733 734 735 736 737 738
    (when bs--marked-buffers
      ;; Some marked buffers for selection
      (let* ((all (delq buffer bs--marked-buffers))
	     (height (/ (1- (frame-height)) (1+ (length all)))))
	(delete-other-windows)
	(switch-to-buffer buffer)
	(dolist (buf all)
	  (split-window nil height)
	  (other-window 1)
	  (switch-to-buffer buf))
	;; goto window we have started bs.
	(other-window 1)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
739 740 741

(defun bs-select-other-window ()
  "Select current line's buffer by `switch-to-buffer-other-window'.
742
The window configuration before starting Buffer Selection Menu will be restored
Gerd Moellmann's avatar
Gerd Moellmann committed
743 744 745 746 747
unless there is no other window.  In this case a new window will be created.
Leave Buffer Selection Menu."
  (interactive)
  (let ((buffer (bs--current-buffer)))
    (bury-buffer (current-buffer))
748
    (bs--restore-window-config)
Gerd Moellmann's avatar
Gerd Moellmann committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    (switch-to-buffer-other-window buffer)))

(defun bs-tmp-select-other-window ()
  "Make the other window select this line's buffer.
The current window remains selected."
  (interactive)
  (let ((buffer (bs--current-buffer)))
    (display-buffer buffer t)))

(defun bs-select-other-frame ()
  "Select current line's buffer in new created frame.
Leave Buffer Selection Menu."
  (interactive)
  (let ((buffer (bs--current-buffer)))
    (bury-buffer (current-buffer))
764
    (bs--restore-window-config)
Gerd Moellmann's avatar
Gerd Moellmann committed
765 766 767 768 769
    (switch-to-buffer-other-frame buffer)))

(defun bs-mouse-select-other-frame (event)
  "Select selected line's buffer in new created frame.
Leave Buffer Selection Menu.
770
EVENT: a mouse click event."
Gerd Moellmann's avatar
Gerd Moellmann committed
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  (interactive "e")
  (mouse-set-point event)
  (bs-select-other-frame))

(defun bs-mouse-select (event)
  "Select buffer on mouse click EVENT.
Select buffer by `bs-select'."
  (interactive "e")
  (mouse-set-point event)
  (bs-select))

(defun bs-select-in-one-window ()
  "Select current line's buffer in one window and delete other windows.
Leave Buffer Selection Menu."
  (interactive)
  (bs-select)
  (delete-other-windows))

(defun bs-bury-buffer ()
  "Bury buffer on current line."
  (interactive)
  (bury-buffer (bs--current-buffer))
  (bs--redisplay t))

(defun bs-save ()
  "Save buffer on current line."
  (interactive)
798
  (with-current-buffer (bs--current-buffer)
Stefan Monnier's avatar
Stefan Monnier committed
799 800
    (save-buffer))
  (bs--update-current-line))
Gerd Moellmann's avatar
Gerd Moellmann committed
801 802 803 804 805 806 807

(defun bs-visit-tags-table ()
  "Visit the tags table in the buffer on this line.
See `visit-tags-table'."
  (interactive)
  (let ((file (buffer-file-name (bs--current-buffer))))
    (if file
Dave Love's avatar
Dave Love committed
808
	(visit-tags-table file)
Gerd Moellmann's avatar
Gerd Moellmann committed
809 810 811 812 813
      (error "Specified buffer has no file"))))

(defun bs-toggle-current-to-show ()
  "Toggle status of showing flag for buffer in current line."
  (interactive)
814 815
  (let ((res
         (with-current-buffer (bs--current-buffer)
816
           (setq bs-buffer-show-mark (pcase bs-buffer-show-mark
817 818
                                       ('nil   'never)
                                       ('never 'always)
819
                                       (_       nil))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    (bs--update-current-line)
    (bs--set-window-height)
    (bs--show-config-message res)))

(defun bs-set-current-buffer-to-show-always (&optional not-to-show-p)
  "Toggle status of buffer on line to `always shown'.
NOT-TO-SHOW-P: prefix argument.
With no prefix argument the buffer on current line is marked to show
always.  Otherwise it is marked to show never."
  (interactive "P")
  (if not-to-show-p
      (bs-set-current-buffer-to-show-never)
    (bs--set-toggle-to-show (bs--current-buffer) 'always)))

(defun bs-set-current-buffer-to-show-never ()
  "Toggle status of buffer on line to `never shown'."
  (interactive)
  (bs--set-toggle-to-show (bs--current-buffer) 'never))

(defun bs--set-toggle-to-show (buffer what)
  "Set value `bs-buffer-show-mark' of buffer BUFFER to WHAT.
Redisplay current line and display a message describing
the status of buffer on current line."
843
  (with-current-buffer buffer (setq bs-buffer-show-mark what))
Gerd Moellmann's avatar
Gerd Moellmann committed
844 845 846 847
  (bs--update-current-line)
  (bs--set-window-height)
  (bs--show-config-message what))

848 849 850
(defun bs--mark-unmark (count fun)
  "Call FUN on COUNT consecutive buffers of *buffer-selection*."
  (let ((dir (if (> count 0) 1 -1)))
851
    (dotimes (_i (abs count))
852 853 854 855 856
      (let ((buffer (bs--current-buffer)))
	(when buffer (funcall fun buffer))
	(bs--update-current-line)
	(bs-down dir)))))

Gerd Moellmann's avatar
Gerd Moellmann committed
857 858 859
(defun bs-mark-current (count)
  "Mark buffers.
COUNT is the number of buffers to mark.
860
Move point vertically down COUNT lines."
Gerd Moellmann's avatar
Gerd Moellmann committed
861
  (interactive "p")
862 863 864
  (bs--mark-unmark count
		   (lambda (buf)
		     (add-to-list 'bs--marked-buffers buf))))
Gerd Moellmann's avatar
Gerd Moellmann committed
865 866 867 868

(defun bs-unmark-current (count)
  "Unmark buffers.
COUNT is the number of buffers to unmark.
869
Move point vertically down COUNT lines."
Gerd Moellmann's avatar
Gerd Moellmann committed
870
  (interactive "p")
871 872 873
  (bs--mark-unmark count
		   (lambda (buf)
		     (setq bs--marked-buffers (delq buf bs--marked-buffers)))))
Gerd Moellmann's avatar
Gerd Moellmann committed
874

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
(defun bs-unmark-previous (count)
  "Unmark previous COUNT buffers.
Move point vertically up COUNT lines.
When called interactively a numeric prefix argument sets COUNT."
  (interactive "p")
  (forward-line (- count))
  (save-excursion (bs-unmark-current count)))

(defun bs-unmark-all ()
  "Unmark all buffers."
  (interactive)
  (let ((marked (string-to-char bs-string-marked))
        (current (string-to-char bs-string-current))
        (marked-cur (string-to-char bs-string-current-marked))
        (unmarked (string-to-char bs-string-show-normally))
        (inhibit-read-only t))
    (save-excursion
      (goto-char (point-min))
      (forward-line 2)
      (while (not (eobp))
        (if (eq (char-after) marked)
            (subst-char-in-region (point) (1+ (point)) marked unmarked)
          (when (eq (char-after) marked-cur)
            (subst-char-in-region (point) (1+ (point)) marked-cur current)))
        (forward-line 1))
      (setq bs--marked-buffers nil))))

Gerd Moellmann's avatar
Gerd Moellmann committed
902 903 904 905
(defun bs--show-config-message (what)
  "Show message indicating the new showing status WHAT.
WHAT is a value of nil, `never', or `always'."
  (bs-message-without-log (cond ((null what)
Dave Love's avatar
Dave Love committed
906 907 908 909
				 "Buffer will be shown normally.")
				((eq what 'never)
				 "Mark buffer to never be shown.")
				(t "Mark buffer to show always."))))
Gerd Moellmann's avatar
Gerd Moellmann committed
910 911 912 913 914

(defun bs-delete ()
  "Kill buffer on current line."
  (interactive)
  (let ((current (bs--current-buffer))
Dave Love's avatar
Dave Love committed
915
	(inhibit-read-only t))
916 917
    (unless (kill-buffer current)
      (error "Buffer was not deleted"))
Gerd Moellmann's avatar
Gerd Moellmann committed
918 919 920
    (setq bs-current-list (delq current bs-current-list))
    (beginning-of-line)
    (delete-region (point) (save-excursion
Dave Love's avatar
Dave Love committed
921 922
			     (end-of-line)
			     (if (eobp) (point) (1+ (point)))))
923 924 925 926
    (when (eobp)
      (backward-delete-char 1)
      (beginning-of-line)
      (recenter -1))
Gerd Moellmann's avatar
Gerd Moellmann committed
927 928 929 930 931 932 933 934
    (bs--set-window-height)))

(defun bs-delete-backward ()
  "Like `bs-delete' but go to buffer in front of current."
  (interactive)
  (let ((on-last-line-p (save-excursion (end-of-line) (eobp))))
    (bs-delete)
    (unless on-last-line-p
Dave Love's avatar
Dave Love committed
935
      (bs-up 1))))
Gerd Moellmann's avatar
Gerd Moellmann committed
936 937

(defun bs-show-sorted ()
938
  "Show buffer list sorted by next sort aspect."
Gerd Moellmann's avatar
Gerd Moellmann committed
939 940
  (interactive)
  (setq bs--current-sort-function
Dave Love's avatar
Dave Love committed
941 942
	(bs-next-config-aux (car bs--current-sort-function)
			    bs-sort-functions))
Gerd Moellmann's avatar
Gerd Moellmann committed
943 944 945 946 947 948 949 950 951
  (bs--redisplay)
  (bs--goto-current-buffer)
  (bs-message-without-log "Sorted %s" (car bs--current-sort-function)))

(defun bs-apply-sort-faces (&optional sort-description)
  "Set text properties for the sort described by SORT-DESCRIPTION.
SORT-DESCRIPTION is an element of `bs-sort-functions'.
Default is `bs--current-sort-function'."
  (let ((sort-description (or sort-description
Dave Love's avatar
Dave Love committed
952
			      bs--current-sort-function)))
Gerd Moellmann's avatar
Gerd Moellmann committed
953 954
    (save-excursion
      (goto-char (point-min))
955 956 957 958 959 960 961 962
      (when (and (nth 2 sort-description)
		 (search-forward-regexp (nth 2 sort-description) nil t))
	(let ((inhibit-read-only t))
	  (put-text-property (match-beginning 0)
			     (match-end 0)
			     'face
			     (or (nth 3 sort-description)
				 'region)))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
963 964 965 966 967 968 969 970 971 972 973

(defun bs-toggle-show-all ()
  "Toggle show all buffers / show buffers with current configuration."
  (interactive)
  (setq bs--show-all (not bs--show-all))
  (bs--redisplay)
  (bs--goto-current-buffer)
  (bs-message-without-log "%s" (bs--current-config-message)))

(defun bs-toggle-readonly ()
  "Toggle read-only status for buffer on current line.
974
Uses function `read-only-mode'."
Gerd Moellmann's avatar
Gerd Moellmann committed
975
  (interactive)
976
  (with-current-buffer (bs--current-buffer)
977
    (read-only-mode 'toggle))
978
  (bs--update-current-line))
Gerd Moellmann's avatar
Gerd Moellmann committed
979 980 981 982

(defun bs-clear-modified ()
  "Set modified flag for buffer on current line to nil."
  (interactive)
983 984
  (with-current-buffer (bs--current-buffer)
    (set-buffer-modified-p nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
985 986 987 988
  (bs--update-current-line))

(defun bs--nth-wrapper (count fun &rest args)
  "Call COUNT times function FUN with arguments ARGS."
989
  (dotimes (_i (or count 1))
990
    (apply fun args)))
Gerd Moellmann's avatar
Gerd Moellmann committed
991 992

(defun bs-up (arg)
993
  "Move point vertically up ARG lines in Buffer Selection Menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
994 995 996 997 998 999
  (interactive "p")
  (if (and arg (numberp arg) (< arg 0))
      (bs--nth-wrapper (- arg) 'bs--down)
    (bs--nth-wrapper arg 'bs--up)))

(defun bs--up ()
1000
  "Move point vertically up one line.
Gerd Moellmann's avatar
Gerd Moellmann committed
1001
If on top of buffer list go to last line."
1002 1003 1004 1005 1006
  (if (> (count-lines 1 (point)) bs-header-lines-length)
      (forward-line -1)
    (goto-char (point-max))
    (beginning-of-line)
    (recenter -1)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1007 1008

(defun bs-down (arg)
1009
  "Move point vertically down ARG lines in Buffer Selection Menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
1010 1011 1012 1013 1014 1015
  (interactive "p")
  (if (and arg (numberp arg) (< arg 0))
      (bs--nth-wrapper (- arg) 'bs--up)
    (bs--nth-wrapper arg 'bs--down)))

(defun bs--down ()
1016
  "Move point vertically down one line.
Gerd Moellmann's avatar
Gerd Moellmann committed
1017
If at end of buffer list go to first line."
1018
  (if (eq (line-end-position) (point-max))
1019
      (progn
Juanma Barranquero's avatar
Juanma Barranquero committed
1020
	(goto-char (point-min))
1021
	(forward-line bs-header-lines-length))
1022
    (forward-line 1)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1023 1024

(defun bs-visits-non-file (buffer)
1025
  "Return whether BUFFER visits no file.
Gerd Moellmann's avatar
Gerd Moellmann committed
1026 1027 1028 1029
A value of t means BUFFER belongs to no file.
A value of nil means BUFFER belongs to a file."
  (not (buffer-file-name buffer)))

1030
(defun bs-sort-buffer-interns-are-last (_b1 b2)
1031
  "Function for sorting internal buffers at the end of all buffers."
1032
  (string-match-p "^\\*" (buffer-name b2)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1033 1034 1035 1036 1037 1038

;; ----------------------------------------------------------------------
;; Configurations:
;; ----------------------------------------------------------------------

(defun bs-config-clear ()
1039
  "Reset all variables which specify a configuration.
Gerd Moellmann's avatar
Gerd Moellmann committed
1040 1041 1042 1043
These variables are `bs-dont-show-regexp', `bs-must-show-regexp',
`bs-dont-show-function', `bs-must-show-function' and
`bs-buffer-sort-function'."
  (setq bs-dont-show-regexp nil
Dave Love's avatar
Dave Love committed
1044 1045 1046 1047
	bs-must-show-regexp nil
	bs-dont-show-function nil
	bs-must-show-function nil
	bs-buffer-sort-function nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
1048 1049 1050 1051

(defun bs-config--only-files ()
  "Define a configuration for showing only buffers visiting a file."
  (bs-config-clear)
1052
  (setq ;; I want to see *-buffers at the end
Dave Love's avatar
Dave Love committed
1053 1054 1055
   bs-buffer-sort-function 'bs-sort-buffer-interns-are-last
   ;; Don't show files who don't belong to a file
   bs-dont-show-function 'bs-visits-non-file))
Gerd Moellmann's avatar
Gerd Moellmann committed
1056 1057 1058 1059

(defun bs-config--files-and-scratch ()
  "Define a configuration for showing buffer *scratch* and file buffers."
  (bs-config-clear)
1060
  (setq ;; I want to see *-buffers at the end
Dave Love's avatar
Dave Love committed
1061 1062 1063 1064
   bs-buffer-sort-function 'bs-sort-buffer-interns-are-last
   ;; Don't show files who don't belong to a file
   bs-dont-show-function 'bs-visits-non-file
   ;; Show *scratch* buffer.
1065
   bs-must-show-regexp "^\\*scratch\\*$"))
Gerd Moellmann's avatar
Gerd Moellmann committed
1066 1067 1068 1069 1070 1071 1072 1073

(defun bs-config--all ()
  "Define a configuration for showing all buffers.
Reset all according variables by `bs-config-clear'."
  (bs-config-clear))

(defun bs-config--all-intern-last ()
  "Define a configuration for showing all buffers.
1074
Internal buffers appear at end of all buffers."
Gerd Moellmann's avatar
Gerd Moellmann committed
1075 1076 1077 1078 1079 1080 1081 1082 1083
  (bs-config-clear)
  ;; I want to see *-buffers at the end
  (setq bs-buffer-sort-function 'bs-sort-buffer-interns-are-last))

(defun bs-set-configuration (name)
  "Set configuration to the one saved under string NAME in `bs-configurations'.
When called interactively ask user for a configuration and apply selected
configuration."
  (interactive (list (completing-read "Use configuration: "
Dave Love's avatar
Dave Love committed
1084 1085 1086
				      bs-configurations
				      nil
				      t)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1087 1088
  (let ((list (assoc name bs-configurations)))
    (if list
Dave Love's avatar
Dave Love committed
1089 1090 1091 1092 1093 1094 1095
	(if (listp list)
	    (setq bs-current-configuration name
		  bs-must-show-regexp     (nth 1 list)
		  bs-must-show-function   (nth 2 list)
		  bs-dont-show-regexp     (nth 3 list)
		  bs-dont-show-function   (nth 4 list)
		  bs-buffer-sort-function (nth 5 list))
Juanma Barranquero's avatar
Juanma Barranquero committed
1096
	  ;; for backward compatibility
Dave Love's avatar
Dave Love committed
1097
	  (funcall (cdr list)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
      ;; else
      (ding)
      (bs-message-without-log "No bs-configuration named %S." name))))

(defun bs-help ()
  "Help for `bs-show'."
  (interactive)
  (describe-function 'bs-mode))

(defun bs-next-config-aux (start-name list)
  "Get the next assoc after START-NAME in list LIST.
Will return the first if START-NAME is at end."
  (let ((assocs list)
Dave Love's avatar
Dave Love committed
1111 1112
	(length (length list))
	pos)
Gerd Moellmann's avatar
Gerd Moellmann committed
1113
    (while (and assocs (not pos))
1114 1115
      (when (string= (car (car assocs)) start-name)
	(setq pos (- length (length assocs))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1116 1117 1118
      (setq assocs (cdr assocs)))
    (setq pos (1+ pos))
    (if (eq pos length)
Dave Love's avatar
Dave Love committed
1119
	(car list)
Gerd Moellmann's avatar
Gerd Moellmann committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      (nth pos list))))

(defun bs-next-config (name)
  "Return next configuration with respect to configuration with name NAME."
  (bs-next-config-aux name bs-configurations))

(defun bs-select-next-configuration (&optional start-name)
  "Apply next configuration START-NAME and refresh buffer list.
If START-NAME is nil the current configuration `bs-current-configuration'
will be used."
  (interactive)
  (let ((config (bs-next-config (or start-name bs-current-configuration))))
    (bs-set-configuration (car config))
    (setq bs-default-configuration bs-current-configuration)
    (bs--redisplay t)
    (bs--set-window-height)
1136
    (bs-message-without-log "Selected configuration: %s" (car config))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

(defun bs-show-in-buffer (list)
  "Display buffer list LIST in buffer *buffer-selection*.
Select buffer *buffer-selection* and display buffers according to current
configuration `bs-current-configuration'.  Set window height, fontify buffer
and move point to current buffer."
  (setq bs-current-list list)
  (switch-to-buffer (get-buffer-create "*buffer-selection*"))
  (bs-mode)
  (let* ((inhibit-read-only t)
Dave Love's avatar
Dave Love committed
1147
	 (map-fun (lambda (entry)
1148
		    (string-width (buffer-name entry))))
Dave Love's avatar
Dave Love committed
1149 1150 1151 1152 1153
	 (max-length-of-names (apply 'max
				     (cons 0 (mapcar map-fun list))))
	 (name-entry-length (min bs-maximal-buffer-name-column
				 (max bs-minimal-buffer-name-column
				      max-length-of-names))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1154 1155 1156
    (erase-buffer)
    (setq bs--name-entry-length name-entry-length)
    (bs--show-header)
1157 1158 1159
    (dolist (buffer list)
      (bs--insert-one-entry buffer)
      (insert "\n"))
1160
    (delete-char -1)
Gerd Moellmann's avatar
Gerd Moellmann committed
1161 1162
    (bs--set-window-height)
    (bs--goto-current-buffer)
1163
    (font-lock-ensure)
1164 1165
    (bs-apply-sort-faces)
    (set-buffer-modified-p nil)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1166 1167 1168 1169 1170 1171 1172 1173

(defun bs-next-buffer (&optional buffer-list sorting-p)
  "Return next buffer and buffer list for buffer cycling in BUFFER-LIST.
Ignore sorting when SORTING-P is nil.
If BUFFER-LIST is nil the result of `bs-buffer-list' will be used as
buffer list.  The result is a cons of normally the second element of
BUFFER-LIST and the buffer list used for buffer cycling."
  (let* ((bs--current-sort-function (if sorting-p
Dave Love's avatar
Dave Love committed
1174 1175
					bs--current-sort-function))
	 (bs-buffer-list (or buffer-list (bs-buffer-list))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1176
    (cons (or (car (cdr bs-buffer-list))
Dave Love's avatar
Dave Love committed
1177 1178 1179
	      (car bs-buffer-list)
	      (current-buffer))
	  bs-buffer-list)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1180 1181 1182 1183 1184 1185 1186 1187

(defun bs-previous-buffer (&optional buffer-list sorting-p)
  "Return previous buffer and buffer list for buffer cycling in BUFFER-LIST.
Ignore sorting when SORTING-P is nil.
If BUFFER-LIST is nil the result of `bs-buffer-list' will be used as
buffer list.  The result is a cons of last element of BUFFER-LIST and the
buffer list used for buffer cycling."
  (let* ((bs--current-sort-function (if sorting-p
Dave Love's avatar
Dave Love committed
1188 1189
					bs--current-sort-function))
	 (bs-buffer-list (or buffer-list (bs-buffer-list))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1190
    (cons (or (car (last bs-buffer-list))
Dave Love's avatar
Dave Love committed
1191 1192
	      (current-buffer))
	  bs-buffer-list)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1193 1194 1195

(defun bs-message-without-log (&rest args)
  "Like `message' but don't log it on the message log.
1196
All arguments ARGS are transferred to function `message'."
Gerd Moellmann's avatar
Gerd Moellmann committed
1197 1198 1199 1200
  (let ((message-log-max nil))
    (apply 'message args)))

(defvar bs--cycle-list nil
1201
  "Current buffer list used for cycling.")
Gerd Moellmann's avatar
Gerd Moellmann committed
1202 1203 1204 1205 1206 1207 1208 1209

;;;###autoload
(defun bs-cycle-next ()
  "Select next buffer defined by buffer cycling.
The buffers taking part in buffer cycling are defined
by buffer configuration `bs-cycle-configuration-name'."
  (interactive)
  (let ((bs--buffer-coming-from (current-buffer))
Dave Love's avatar
Dave Love committed
1210 1211 1212 1213
	(bs-dont-show-regexp   bs-dont-show-regexp)
	(bs-must-show-regexp   bs-must-show-regexp)
	(bs-dont-show-function bs-dont-show-function)
	(bs-must-show-function bs-must-show-function)
1214 1215
	(bs--show-all          nil))
    (bs-set-configuration (or bs-cycle-configuration-name bs-default-configuration))
Gerd Moellmann's avatar
Gerd Moellmann committed
1216
    (let ((bs-buffer-sort-function nil)
Dave Love's avatar
Dave Love committed
1217
	  (bs--current-sort-function nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
1218
      (let* ((tupel (bs-next-buffer (if (or (eq last-command
Dave Love's avatar
Dave Love committed
1219 1220 1221 1222 1223 1224
						'bs-cycle-next)
					    (eq last-command
						'bs-cycle-previous))
					bs--cycle-list)))
	     (next (car tupel))
	     (cycle-list (cdr tupel)))
1225 1226 1227
        ;; We don't want the frame iconified if the only window in the frame
        ;; happens to be dedicated.
        (bury-buffer (current-buffer))
1228
	(switch-to-buffer next nil t)
Dave Love's avatar
Dave Love committed
1229 1230 1231 1232 1233
	(setq bs--cycle-list (append (cdr cycle-list)
				     (list (car cycle-list))))
	(bs-message-without-log "Next buffers: %s"
				(or (cdr bs--cycle-list)
				    "this buffer"))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1234 1235 1236 1237 1238 1239 1240 1241

;;;###autoload
(defun bs-cycle-previous ()
  "Select previous buffer defined by buffer cycling.
The buffers taking part in buffer cycling are defined
by buffer configuration `bs-cycle-configuration-name'."
  (interactive)
  (let ((bs--buffer-coming-from (current-buffer))
Dave Love's avatar
Dave Love committed
1242 1243 1244 1245
	(bs-dont-show-regexp   bs-dont-show-regexp)
	(bs-must-show-regexp   bs-must-show-regexp)
	(bs-dont-show-function bs-dont-show-function)
	(bs-must-show-function bs-must-show-function)
1246 1247
	(bs--show-all          nil))
    (bs-set-configuration (or bs-cycle-configuration-name bs-default-configuration))
Gerd Moellmann's avatar
Gerd Moellmann committed
1248
    (let ((bs-buffer-sort-function nil)
Dave Love's avatar
Dave Love committed
1249
	  (bs--current-sort-function nil))
Gerd Moellmann's avatar
Gerd Moellmann committed
1250
      (let* ((tupel (bs-previous-buffer (if (or (eq last-command
Dave Love's avatar
Dave Love committed
1251 1252 1253 1254 1255 1256
						    'bs-cycle-next)
						(eq last-command
						    'bs-cycle-previous))
					    bs--cycle-list)))
	     (prev-buffer (car tupel))
	     (cycle-list (cdr tupel)))
1257
	(switch-to-buffer prev-buffer nil t)
Dave Love's avatar
Dave Love committed
1258 1259 1260 1261 1262
	(setq bs--cycle-list (append (last cycle-list)
				     (reverse (cdr (reverse cycle-list)))))
	(bs-message-without-log "Previous buffers: %s"
				(or (reverse (cdr bs--cycle-list))
				    "this buffer"))))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1263 1264 1265 1266 1267 1268

(defun bs--get-value (fun &optional args)
  "Apply function FUN with arguments ARGS.
Return result of evaluation.  Will return FUN if FUN is a number
or a string."
  (cond ((numberp fun)
Dave Love's avatar
Dave Love committed
1269 1270 1271 1272
	 fun)
	((stringp fun)
	 fun)
	(t (apply fun args))))
Gerd Moellmann's avatar
Gerd Moellmann committed
1273

1274
(defun bs--get-marked-string (start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1275 1276
  "Return a string which describes whether current buffer is marked.
START-BUFFER is the buffer where we started buffer selection.
1277
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
1278 1279 1280
The result string is one of `bs-string-current', `bs-string-current-marked',
`bs-string-marked', `bs-string-show-normally', `bs-string-show-never', or
`bs-string-show-always'."
1281
  (cond ;; current buffer is the buffer we started buffer selection.
Dave Love's avatar
Dave Love committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
   ((eq (current-buffer) start-buffer)
    (if (memq (current-buffer) bs--marked-buffers)
	bs-string-current-marked	; buffer is marked
      bs-string-current))
   ;; current buffer is marked
   ((memq (current-buffer) bs--marked-buffers)
    bs-string-marked)
   ;; current buffer hasn't a special mark.
   ((null bs-buffer-show-mark)
    bs-string-show-normally)
   ;; current buffer has a mark not to show itself.
   ((eq bs-buffer-show-mark 'never)
    bs-string-show-never)
   ;; otherwise current buffer is marked to show always.
   (t
    bs-string-show-always)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1298

1299
(defun bs--get-modified-string (_start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1300 1301
  "Return a string which describes whether current buffer is modified.
START-BUFFER is the buffer where we started buffer selection.
1302
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
1303 1304
  (if (buffer-modified-p) "*" " "))

1305
(defun bs--get-readonly-string (_start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1306 1307
  "Return a string which describes whether current buffer is read only.
START-BUFFER is the buffer where we started buffer selection.
1308
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
1309 1310
  (if buffer-read-only "%" " "))

1311
(defun bs--get-size-string (_start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1312 1313
  "Return a string which describes the size of current buffer.
START-BUFFER is the buffer where we started buffer selection.
1314
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
Gerd Moellmann's avatar
Gerd Moellmann committed
1315 1316
  (int-to-string (buffer-size)))

1317
(defun bs--get-name (_start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1318 1319 1320 1321
  "Return name of current buffer for Buffer Selection Menu.
The name of current buffer gets additional text properties
for mouse highlighting.
START-BUFFER is the buffer where we started buffer selection.
1322
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
1323 1324 1325
  (propertize (buffer-name)
              'help-echo "mouse-2: select this buffer, mouse-3: select in other frame"
              'mouse-face 'highlight))
Gerd Moellmann's avatar
Gerd Moellmann committed
1326

1327
(defun bs--get-mode-name (start-buffer _all-buffers)
Gerd Moellmann's avatar
Gerd Moellmann committed
1328 1329
  "Return the name of mode of current buffer for Buffer Selection Menu.
START-BUFFER is the buffer where we started buffer selection.
1330
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
1331
  (format-mode-line mode-name nil nil start-buffer))
Gerd Moellmann's avatar
Gerd Moellmann committed
1332

1333
(defun bs--get-file-name (_start-buffer _all-buffers)
1334
  "Return string for column `File' in Buffer Selection Menu.
Gerd Moellmann's avatar
Gerd Moellmann committed
1335
This is the variable `buffer-file-name' of current buffer.
1336
If not visiting a file, `list-buffers-directory' is returned instead.
Gerd Moellmann's avatar
Gerd Moellmann committed
1337
START-BUFFER is the buffer where we started buffer selection.
1338
ALL-BUFFERS is the list of buffers appearing in Buffer Selection Menu."
1339 1340 1341
  (propertize (or buffer-file-name
		  (bound-and-true-p list-buffers-directory)
		  "")
1342 1343
              'mouse-face 'highlight
              'help-echo "mouse-2: select this buffer, mouse-3: select in other frame"))
Gerd Moellmann's avatar
Gerd Moellmann committed
1344 1345 1346 1347 1348 1349 1350

(defun bs--insert-one-entry (buffer)
  "Generate one entry for buffer BUFFER in Buffer Selection Menu.
It goes over all columns described in `bs-attributes-list'
and evaluates corresponding string.  Inserts string in current buffer;
normally *buffer-selection*."
  (let ((string "")
Dave Love's avatar
Dave Love committed
1351
	(to-much 0)
Gerd Moellmann's avatar
Gerd Moellmann committed
1352
        (apply-args (append (list bs--buffer-coming-from bs-current-list))))
1353
    (with-current-buffer buffer
1354 1355 1356 1357 1358 1359
      (dolist (column bs-attributes-list)
	(let* ((min (bs--get-value (nth 1 column)))
	       (new-string (bs--format-aux (bs--get-value (nth 4 column) ; fun
							  apply-args)
					   (nth 3 column)                ; align
					   (- min to-much)))
1360
	       (len (string-width new-string)))
Dave Love's avatar
Dave Love committed
1361
	  (setq string (concat string new-string))
1362 1363 1364
	  (when (> len min)
	    (setq to-much (- len min))))))
    (insert string)))
Gerd Moellmann's avatar
Gerd Moellmann committed
1365 1366

(defun bs--format-aux (string align len)
1367
  "Pad STRING to length LEN with alignment ALIGN.
Gerd Moellmann's avatar
Gerd Moellmann committed
1368
ALIGN is one of the symbols `left', `middle', or `right'."
1369 1370 1371 1372 1373 1374
  (let* ((width (length string))
         (len (max len width)))
    (format (format "%%%s%ds" (if (eq align 'right) "" "