* lisp/buff-menu.el: Convert to Tabulated List mode.
[emacs.git] / lisp / emacs-lisp / tabulated-list.el
blob4291f3aacc6ba017fe11cb035ec48cc82be9e437
1 ;;; tabulated-list.el --- generic major mode for tabulated lists -*- lexical-binding: t -*-
3 ;; Copyright (C) 2011-2012 Free Software Foundation, Inc.
5 ;; Author: Chong Yidong <cyd@stupidchicken.com>
6 ;; Keywords: extensions, lisp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
13 ;; any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This file defines Tabulated List mode, a generic major mode for
26 ;; displaying lists of tabulated data, intended for other major modes
27 ;; to inherit from. It provides several utility routines, e.g. for
28 ;; pretty-printing lines of tabulated data to fit into the appropriate
29 ;; columns.
31 ;; For usage information, see the documentation of `tabulated-list-mode'.
33 ;; This package originated from Tom Tromey's Package Menu mode,
34 ;; extended and generalized to be used by other modes.
36 ;;; Code:
38 (defvar tabulated-list-format nil
39 "The format of the current Tabulated List mode buffer.
40 This should be a vector of elements (NAME WIDTH SORT . PROPS),
41 where:
42 - NAME is a string describing the column.
43 This is the label for the column in the header line.
44 Different columns must have non-`equal' names.
45 - WIDTH is the width to reserve for the column.
46 For the final element, its numerical value is ignored.
47 - SORT specifies how to sort entries by this column.
48 If nil, this column cannot be used for sorting.
49 If t, sort by comparing the string value printed in the column.
50 Otherwise, it should be a predicate function suitable for
51 `sort', accepting arguments with the same form as the elements
52 of `tabulated-list-entries'.
53 - PROPS is a plist of additional column properties.
54 Currently supported properties are:
55 - `:pad-right': Number of additional padding spaces to the
56 right of the column (defaults to 1 if omitted).")
57 (make-variable-buffer-local 'tabulated-list-format)
59 (defvar tabulated-list-entries nil
60 "Entries displayed in the current Tabulated List buffer.
61 This should be either a function, or a list.
62 If a list, each element has the form (ID [DESC1 ... DESCN]),
63 where:
64 - ID is nil, or a Lisp object uniquely identifying this entry,
65 which is used to keep the cursor on the \"same\" entry when
66 rearranging the list. Comparison is done with `equal'.
68 - Each DESC is a column descriptor, one for each column
69 specified in `tabulated-list-format'. A descriptor is either
70 a string, which is printed as-is, or a list (LABEL . PROPS),
71 which means to use `insert-text-button' to insert a text
72 button with label LABEL and button properties PROPS.
73 The string, or button label, must not contain any newline.
75 If `tabulated-list-entries' is a function, it is called with no
76 arguments and must return a list of the above form.")
77 (make-variable-buffer-local 'tabulated-list-entries)
79 (defvar tabulated-list-padding 0
80 "Number of characters preceding each Tabulated List mode entry.
81 By default, lines are padded with spaces, but you can use the
82 function `tabulated-list-put-tag' to change this.")
83 (make-variable-buffer-local 'tabulated-list-padding)
85 (defvar tabulated-list-revert-hook nil
86 "Hook run before reverting a Tabulated List buffer.
87 This is commonly used to recompute `tabulated-list-entries'.")
89 (defvar tabulated-list-printer 'tabulated-list-print-entry
90 "Function for inserting a Tabulated List entry at point.
91 It is called with two arguments, ID and COLS. ID is a Lisp
92 object identifying the entry, and COLS is a vector of column
93 descriptors, as documented in `tabulated-list-entries'.")
94 (make-variable-buffer-local 'tabulated-list-printer)
96 (defvar tabulated-list-sort-key nil
97 "Sort key for the current Tabulated List mode buffer.
98 If nil, no additional sorting is performed.
99 Otherwise, this should be a cons cell (NAME . FLIP).
100 NAME is a string matching one of the column names in
101 `tabulated-list-format' (the corresponding SORT entry in
102 `tabulated-list-format' then specifies how to sort). FLIP, if
103 non-nil, means to invert the resulting sort.")
104 (make-variable-buffer-local 'tabulated-list-sort-key)
106 (defsubst tabulated-list-get-id (&optional pos)
107 "Return the entry ID of the Tabulated List entry at POS.
108 The value is an ID object from `tabulated-list-entries', or nil.
109 POS, if omitted or nil, defaults to point."
110 (get-text-property (or pos (point)) 'tabulated-list-id))
112 (defsubst tabulated-list-get-entry (&optional pos)
113 "Return the Tabulated List entry at POS.
114 The value is a vector of column descriptors, or nil if there is
115 no entry at POS. POS, if omitted or nil, defaults to point."
116 (get-text-property (or pos (point)) 'tabulated-list-entry))
118 (defun tabulated-list-put-tag (tag &optional advance)
119 "Put TAG in the padding area of the current line.
120 TAG should be a string, with length <= `tabulated-list-padding'.
121 If ADVANCE is non-nil, move forward by one line afterwards."
122 (unless (stringp tag)
123 (error "Invalid argument to `tabulated-list-put-tag'"))
124 (unless (> tabulated-list-padding 0)
125 (error "Unable to tag the current line"))
126 (save-excursion
127 (beginning-of-line)
128 (when (tabulated-list-get-entry)
129 (let ((beg (point))
130 (inhibit-read-only t))
131 (forward-char tabulated-list-padding)
132 (insert-and-inherit
133 (let ((width (string-width tag)))
134 (if (<= width tabulated-list-padding)
135 (concat tag
136 (make-string (- tabulated-list-padding width) ?\s))
137 (truncate-string-to-width tag tabulated-list-padding))))
138 (delete-region beg (+ beg tabulated-list-padding)))))
139 (if advance
140 (forward-line)))
142 (defvar tabulated-list-mode-map
143 (let ((map (copy-keymap special-mode-map)))
144 (set-keymap-parent map button-buffer-map)
145 (define-key map "n" 'next-line)
146 (define-key map "p" 'previous-line)
147 (define-key map "S" 'tabulated-list-sort)
148 (define-key map [follow-link] 'mouse-face)
149 (define-key map [mouse-2] 'mouse-select-window)
150 map)
151 "Local keymap for `tabulated-list-mode' buffers.")
153 (defvar tabulated-list-sort-button-map
154 (let ((map (make-sparse-keymap)))
155 (define-key map [header-line mouse-1] 'tabulated-list-col-sort)
156 (define-key map [header-line mouse-2] 'tabulated-list-col-sort)
157 (define-key map [follow-link] 'mouse-face)
158 map)
159 "Local keymap for `tabulated-list-mode' sort buttons.")
161 (defvar tabulated-list-glyphless-char-display
162 (let ((table (make-char-table 'glyphless-char-display nil)))
163 (set-char-table-parent table glyphless-char-display)
164 ;; Some text terminals can't display the Unicode arrows; be safe.
165 (aset table 9650 (cons nil "^"))
166 (aset table 9660 (cons nil "v"))
167 table)
168 "The `glyphless-char-display' table in Tabulated List buffers.")
170 (defun tabulated-list-init-header ()
171 "Set up header line for the Tabulated List buffer."
172 (let ((x (max tabulated-list-padding 0))
173 (button-props `(help-echo "Click to sort by column"
174 mouse-face highlight
175 keymap ,tabulated-list-sort-button-map))
176 (cols nil))
177 (push (propertize " " 'display `(space :align-to ,x)) cols)
178 (dotimes (n (length tabulated-list-format))
179 (let* ((col (aref tabulated-list-format n))
180 (label (nth 0 col))
181 (width (nth 1 col))
182 (props (nthcdr 3 col))
183 (pad-right (or (plist-get props :pad-right) 1)))
184 (setq x (+ x pad-right width))
185 (push
186 (cond
187 ;; An unsortable column
188 ((not (nth 2 col)) label)
189 ;; The selected sort column
190 ((equal (car col) (car tabulated-list-sort-key))
191 (apply 'propertize
192 (concat label
193 (cond
194 ((> (+ 2 (length label)) width)
196 ((cdr tabulated-list-sort-key)
197 " ▲")
198 (t " ▼")))
199 'face 'bold
200 'tabulated-list-column-name (car col)
201 button-props))
202 ;; Unselected sortable column.
203 (t (apply 'propertize label
204 'tabulated-list-column-name (car col)
205 button-props)))
206 cols)
207 (if (> pad-right 0)
208 (push (propertize " "
209 'display `(space :align-to ,x)
210 'face 'fixed-pitch)
211 cols))))
212 (setq header-line-format (mapconcat 'identity (nreverse cols) ""))))
214 (defun tabulated-list-revert (&rest ignored)
215 "The `revert-buffer-function' for `tabulated-list-mode'.
216 It runs `tabulated-list-revert-hook', then calls `tabulated-list-print'."
217 (interactive)
218 (unless (derived-mode-p 'tabulated-list-mode)
219 (error "The current buffer is not in Tabulated List mode"))
220 (run-hooks 'tabulated-list-revert-hook)
221 (tabulated-list-print t))
223 (defun tabulated-list--column-number (name)
224 (let ((len (length tabulated-list-format))
225 (n 0)
226 found)
227 (while (and (< n len) (null found))
228 (if (equal (car (aref tabulated-list-format n)) name)
229 (setq found n))
230 (setq n (1+ n)))
231 (or found
232 (error "No column named %s" name))))
234 (defun tabulated-list-print (&optional remember-pos)
235 "Populate the current Tabulated List mode buffer.
236 This sorts the `tabulated-list-entries' list if sorting is
237 specified by `tabulated-list-sort-key'. It then erases the
238 buffer and inserts the entries with `tabulated-list-printer'.
240 Optional argument REMEMBER-POS, if non-nil, means to move point
241 to the entry with the same ID element as the current line."
242 (let ((inhibit-read-only t)
243 (entries (if (functionp tabulated-list-entries)
244 (funcall tabulated-list-entries)
245 tabulated-list-entries))
246 entry-id saved-pt saved-col)
247 (and remember-pos
248 (setq entry-id (tabulated-list-get-id))
249 (setq saved-col (current-column)))
250 (erase-buffer)
251 ;; Sort the buffers, if necessary.
252 (when (and tabulated-list-sort-key
253 (car tabulated-list-sort-key))
254 (let* ((sort-column (car tabulated-list-sort-key))
255 (n (tabulated-list--column-number sort-column))
256 (sorter (nth 2 (aref tabulated-list-format n))))
257 ;; Is the specified column sortable?
258 (when sorter
259 (when (eq sorter t)
260 (setq sorter ; Default sorter checks column N:
261 (lambda (A B)
262 (setq A (aref (cadr A) n))
263 (setq B (aref (cadr B) n))
264 (string< (if (stringp A) A (car A))
265 (if (stringp B) B (car B))))))
266 (setq entries (sort entries sorter))
267 (if (cdr tabulated-list-sort-key)
268 (setq entries (nreverse entries)))
269 (unless (functionp tabulated-list-entries)
270 (setq tabulated-list-entries entries)))))
271 ;; Print the resulting list.
272 (dolist (elt entries)
273 (and entry-id
274 (equal entry-id (car elt))
275 (setq saved-pt (point)))
276 (apply tabulated-list-printer elt))
277 (set-buffer-modified-p nil)
278 ;; If REMEMBER-POS was specified, move to the "old" location.
279 (if saved-pt
280 (progn (goto-char saved-pt)
281 (move-to-column saved-col)
282 (recenter))
283 (goto-char (point-min)))))
285 (defun tabulated-list-print-entry (id cols)
286 "Insert a Tabulated List entry at point.
287 This is the default `tabulated-list-printer' function. ID is a
288 Lisp object identifying the entry to print, and COLS is a vector
289 of column descriptors."
290 (let ((beg (point))
291 (x (max tabulated-list-padding 0))
292 (ncols (length tabulated-list-format))
293 (inhibit-read-only t))
294 (if (> tabulated-list-padding 0)
295 (insert (make-string x ?\s)))
296 (dotimes (n ncols)
297 (setq x (tabulated-list-print-col n (aref cols n) x)))
298 (insert ?\n)
299 (put-text-property beg (point) 'tabulated-list-id id)
300 (put-text-property beg (point) 'tabulated-list-entry cols)))
302 (defun tabulated-list-print-col (n col-desc x)
303 "Insert a specified Tabulated List entry at point.
304 N is the column number, COL-DESC is a column descriptor \(see
305 `tabulated-list-entries'), and X is the column number at point.
306 Return the column number after insertion."
307 (let* ((format (aref tabulated-list-format n))
308 (name (nth 0 format))
309 (width (nth 1 format))
310 (props (nthcdr 3 format))
311 (pad-right (or (plist-get props :pad-right) 1))
312 (label (if (stringp col-desc) col-desc (car col-desc)))
313 (help-echo (concat (car format) ": " label))
314 (opoint (point))
315 (not-last-col (< (1+ n) (length tabulated-list-format))))
316 ;; Truncate labels if necessary (except last column).
317 (and not-last-col
318 (> (string-width label) width)
319 (setq label (truncate-string-to-width label width nil nil t)))
320 (setq label (bidi-string-mark-left-to-right label))
321 (if (stringp col-desc)
322 (insert (propertize label 'help-echo help-echo))
323 (apply 'insert-text-button label (cdr col-desc)))
324 (setq x (+ x pad-right width))
325 ;; No need to append any spaces if this is the last column.
326 (if not-last-col
327 (indent-to x pad-right))
328 (put-text-property opoint (point) 'tabulated-list-column-name name)
331 (defun tabulated-list-delete-entry ()
332 "Delete the Tabulated List entry at point.
333 Return a list (ID COLS), where ID is the ID of the deleted entry
334 and COLS is a vector of its column descriptors. Move point to
335 the beginning of the deleted entry. Return nil if there is no
336 entry at point.
338 This function only changes the buffer contents; it does not alter
339 `tabulated-list-entries'."
340 ;; Assume that each entry occupies one line.
341 (let* ((id (tabulated-list-get-id))
342 (cols (tabulated-list-get-entry))
343 (inhibit-read-only t))
344 (when cols
345 (delete-region (line-beginning-position) (1+ (line-end-position)))
346 (list id cols))))
348 (defun tabulated-list-set-col (col desc &optional change-entry-data)
349 "Change the Tabulated List entry at point, setting COL to DESC.
350 COL is the column number to change, or the name of the column to change.
351 DESC is the new column descriptor, which is inserted via
352 `tabulated-list-print-col'.
354 If CHANGE-ENTRY-DATA is non-nil, modify the underlying entry data
355 by setting the appropriate slot of the vector originally used to
356 print this entry. If `tabulated-list-entries' has a list value,
357 this is the vector stored within it."
358 (let* ((opoint (point))
359 (eol (line-end-position))
360 (pos (line-beginning-position))
361 (id (tabulated-list-get-id pos))
362 (entry (tabulated-list-get-entry pos))
363 (prop 'tabulated-list-column-name)
364 (inhibit-read-only t)
365 name)
366 (cond ((numberp col)
367 (setq name (car (aref tabulated-list-format col))))
368 ((stringp col)
369 (setq name col
370 col (tabulated-list--column-number col)))
372 (error "Invalid column %s" col)))
373 (unless entry
374 (error "No Tabulated List entry at position %s" opoint))
375 (unless (equal (get-text-property pos prop) name)
376 (while (and (setq pos
377 (next-single-property-change pos prop nil eol))
378 (< pos eol)
379 (not (equal (get-text-property pos prop) name)))))
380 (when (< pos eol)
381 (delete-region pos (next-single-property-change pos prop nil eol))
382 (goto-char pos)
383 (tabulated-list-print-col col desc (current-column))
384 (if change-entry-data
385 (aset entry col desc))
386 (put-text-property pos (point) 'tabulated-list-id id)
387 (put-text-property pos (point) 'tabulated-list-entry entry)
388 (goto-char opoint))))
390 (defun tabulated-list-col-sort (&optional e)
391 "Sort Tabulated List entries by the column of the mouse click E."
392 (interactive "e")
393 (let* ((pos (event-start e))
394 (obj (posn-object pos))
395 (name (get-text-property (if obj (cdr obj) (posn-point pos))
396 'tabulated-list-column-name
397 (car obj))))
398 (with-current-buffer (window-buffer (posn-window pos))
399 (tabulated-list--sort-by-column-name name))))
401 (defun tabulated-list-sort (&optional n)
402 "Sort Tabulated List entries by the column at point.
403 With a numeric prefix argument N, sort the Nth column."
404 (interactive "P")
405 (let ((name (if n
406 (car (aref tabulated-list-format n))
407 (get-text-property (point)
408 'tabulated-list-column-name))))
409 (tabulated-list--sort-by-column-name name)))
411 (defun tabulated-list--sort-by-column-name (name)
412 (when (derived-mode-p 'tabulated-list-mode)
413 ;; Flip the sort order on a second click.
414 (if (equal name (car tabulated-list-sort-key))
415 (setcdr tabulated-list-sort-key
416 (not (cdr tabulated-list-sort-key)))
417 (setq tabulated-list-sort-key (cons name nil)))
418 (tabulated-list-init-header)
419 (tabulated-list-print t)))
421 ;;; The mode definition:
423 (define-derived-mode tabulated-list-mode special-mode "Tabulated"
424 "Generic major mode for browsing a list of items.
425 This mode is usually not used directly; instead, other major
426 modes are derived from it, using `define-derived-mode'.
428 In this major mode, the buffer is divided into multiple columns,
429 which are labeled using the header line. Each non-empty line
430 belongs to one \"entry\", and the entries can be sorted according
431 to their column values.
433 An inheriting mode should usually do the following in their body:
435 - Set `tabulated-list-format', specifying the column format.
436 - Set `tabulated-list-revert-hook', if the buffer contents need
437 to be specially recomputed prior to `revert-buffer'.
438 - Maybe set a `tabulated-list-entries' function (see below).
439 - Maybe set `tabulated-list-printer' (see below).
440 - Maybe set `tabulated-list-padding'.
441 - Call `tabulated-list-init-header' to initialize `header-line-format'
442 according to `tabulated-list-format'.
444 An inheriting mode is usually accompanied by a \"list-FOO\"
445 command (e.g. `list-packages', `list-processes'). This command
446 creates or switches to a buffer and enables the major mode in
447 that buffer. If `tabulated-list-entries' is not a function, the
448 command should initialize it to a list of entries for displaying.
449 Finally, it should call `tabulated-list-print'.
451 `tabulated-list-print' calls the printer function specified by
452 `tabulated-list-printer', once for each entry. The default
453 printer is `tabulated-list-print-entry', but a mode that keeps
454 data in an ewoc may instead specify a printer function (e.g., one
455 that calls `ewoc-enter-last'), with `tabulated-list-print-entry'
456 as the ewoc pretty-printer."
457 (setq truncate-lines t)
458 (setq buffer-read-only t)
459 (set (make-local-variable 'revert-buffer-function)
460 'tabulated-list-revert)
461 (set (make-local-variable 'glyphless-char-display)
462 tabulated-list-glyphless-char-display))
464 (put 'tabulated-list-mode 'mode-class 'special)
466 (provide 'tabulated-list)
468 ;; Local Variables:
469 ;; coding: utf-8
470 ;; End:
472 ;;; tabulated-list.el ends here