* lisp/buff-menu.el (list-buffers--refresh): Mark `size' as right-align.
[emacs/old-mirror.git] / lisp / emacs-lisp / tabulated-list.el
blobe56fea585530bc90567ea2ca0b23d51ed4c06006
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 - `:right-align': if non-nil, the column should be right-aligned.
56 - `:pad-right': Number of additional padding spaces to the
57 right of the column (defaults to 1 if omitted).")
58 (make-variable-buffer-local 'tabulated-list-format)
60 (defvar tabulated-list-use-header-line t
61 "Whether the Tabulated List buffer should use a header line.")
62 (make-variable-buffer-local 'tabulated-list-use-header-line)
64 (defvar tabulated-list-entries nil
65 "Entries displayed in the current Tabulated List buffer.
66 This should be either a function, or a list.
67 If a list, each element has the form (ID [DESC1 ... DESCN]),
68 where:
69 - ID is nil, or a Lisp object uniquely identifying this entry,
70 which is used to keep the cursor on the \"same\" entry when
71 rearranging the list. Comparison is done with `equal'.
73 - Each DESC is a column descriptor, one for each column
74 specified in `tabulated-list-format'. A descriptor is either
75 a string, which is printed as-is, or a list (LABEL . PROPS),
76 which means to use `insert-text-button' to insert a text
77 button with label LABEL and button properties PROPS.
78 The string, or button label, must not contain any newline.
80 If `tabulated-list-entries' is a function, it is called with no
81 arguments and must return a list of the above form.")
82 (make-variable-buffer-local 'tabulated-list-entries)
84 (defvar tabulated-list-padding 0
85 "Number of characters preceding each Tabulated List mode entry.
86 By default, lines are padded with spaces, but you can use the
87 function `tabulated-list-put-tag' to change this.")
88 (make-variable-buffer-local 'tabulated-list-padding)
90 (defvar tabulated-list-revert-hook nil
91 "Hook run before reverting a Tabulated List buffer.
92 This is commonly used to recompute `tabulated-list-entries'.")
94 (defvar tabulated-list-printer 'tabulated-list-print-entry
95 "Function for inserting a Tabulated List entry at point.
96 It is called with two arguments, ID and COLS. ID is a Lisp
97 object identifying the entry, and COLS is a vector of column
98 descriptors, as documented in `tabulated-list-entries'.")
99 (make-variable-buffer-local 'tabulated-list-printer)
101 (defvar tabulated-list-sort-key nil
102 "Sort key for the current Tabulated List mode buffer.
103 If nil, no additional sorting is performed.
104 Otherwise, this should be a cons cell (NAME . FLIP).
105 NAME is a string matching one of the column names in
106 `tabulated-list-format' (the corresponding SORT entry in
107 `tabulated-list-format' then specifies how to sort). FLIP, if
108 non-nil, means to invert the resulting sort.")
109 (make-variable-buffer-local 'tabulated-list-sort-key)
111 (defsubst tabulated-list-get-id (&optional pos)
112 "Return the entry ID of the Tabulated List entry at POS.
113 The value is an ID object from `tabulated-list-entries', or nil.
114 POS, if omitted or nil, defaults to point."
115 (get-text-property (or pos (point)) 'tabulated-list-id))
117 (defsubst tabulated-list-get-entry (&optional pos)
118 "Return the Tabulated List entry at POS.
119 The value is a vector of column descriptors, or nil if there is
120 no entry at POS. POS, if omitted or nil, defaults to point."
121 (get-text-property (or pos (point)) 'tabulated-list-entry))
123 (defun tabulated-list-put-tag (tag &optional advance)
124 "Put TAG in the padding area of the current line.
125 TAG should be a string, with length <= `tabulated-list-padding'.
126 If ADVANCE is non-nil, move forward by one line afterwards."
127 (unless (stringp tag)
128 (error "Invalid argument to `tabulated-list-put-tag'"))
129 (unless (> tabulated-list-padding 0)
130 (error "Unable to tag the current line"))
131 (save-excursion
132 (beginning-of-line)
133 (when (tabulated-list-get-entry)
134 (let ((beg (point))
135 (inhibit-read-only t))
136 (forward-char tabulated-list-padding)
137 (insert-and-inherit
138 (let ((width (string-width tag)))
139 (if (<= width tabulated-list-padding)
140 (concat tag
141 (make-string (- tabulated-list-padding width) ?\s))
142 (truncate-string-to-width tag tabulated-list-padding))))
143 (delete-region beg (+ beg tabulated-list-padding)))))
144 (if advance
145 (forward-line)))
147 (defvar tabulated-list-mode-map
148 (let ((map (copy-keymap special-mode-map)))
149 (set-keymap-parent map button-buffer-map)
150 (define-key map "n" 'next-line)
151 (define-key map "p" 'previous-line)
152 (define-key map "S" 'tabulated-list-sort)
153 (define-key map [follow-link] 'mouse-face)
154 (define-key map [mouse-2] 'mouse-select-window)
155 map)
156 "Local keymap for `tabulated-list-mode' buffers.")
158 (defvar tabulated-list-sort-button-map
159 (let ((map (make-sparse-keymap)))
160 (define-key map [header-line mouse-1] 'tabulated-list-col-sort)
161 (define-key map [header-line mouse-2] 'tabulated-list-col-sort)
162 (define-key map [mouse-1] 'tabulated-list-col-sort)
163 (define-key map [mouse-2] 'tabulated-list-col-sort)
164 (define-key map "\C-m" 'tabulated-list-sort)
165 (define-key map [follow-link] 'mouse-face)
166 map)
167 "Local keymap for `tabulated-list-mode' sort buttons.")
169 (defvar tabulated-list-glyphless-char-display
170 (let ((table (make-char-table 'glyphless-char-display nil)))
171 (set-char-table-parent table glyphless-char-display)
172 ;; Some text terminals can't display the Unicode arrows; be safe.
173 (aset table 9650 (cons nil "^"))
174 (aset table 9660 (cons nil "v"))
175 table)
176 "The `glyphless-char-display' table in Tabulated List buffers.")
178 (defvar tabulated-list--header-string nil)
179 (defvar tabulated-list--header-overlay nil)
181 (defun tabulated-list-init-header ()
182 "Set up header line for the Tabulated List buffer."
183 ;; FIXME: Should share code with tabulated-list-print-col!
184 (let ((x (max tabulated-list-padding 0))
185 (button-props `(help-echo "Click to sort by column"
186 mouse-face highlight
187 keymap ,tabulated-list-sort-button-map))
188 (cols nil))
189 (push (propertize " " 'display `(space :align-to ,x)) cols)
190 (dotimes (n (length tabulated-list-format))
191 (let* ((col (aref tabulated-list-format n))
192 (label (nth 0 col))
193 (width (nth 1 col))
194 (props (nthcdr 3 col))
195 (pad-right (or (plist-get props :pad-right) 1))
196 (right-align (plist-get props :right-align))
197 (next-x (+ x pad-right width)))
198 (push
199 (cond
200 ;; An unsortable column
201 ((not (nth 2 col))
202 (propertize label 'tabulated-list-column-name label))
203 ;; The selected sort column
204 ((equal (car col) (car tabulated-list-sort-key))
205 (apply 'propertize
206 (concat label
207 (cond
208 ((> (+ 2 (length label)) width) "")
209 ((cdr tabulated-list-sort-key) " â–²")
210 (t " â–¼")))
211 'face 'bold
212 'tabulated-list-column-name label
213 button-props))
214 ;; Unselected sortable column.
215 (t (apply 'propertize label
216 'tabulated-list-column-name label
217 button-props)))
218 cols)
219 (when right-align
220 (let ((shift (- width (string-width (car cols)))))
221 (when (> shift 0)
222 (setq cols
223 (cons (car cols)
224 (cons (propertize (make-string shift ?\s)
225 'display
226 `(space :align-to ,(+ x shift)))
227 (cdr cols))))
228 (setq x (+ x shift)))))
229 (if (> pad-right 0)
230 (push (propertize " "
231 'display `(space :align-to ,next-x)
232 'face 'fixed-pitch)
233 cols))
234 (setq x next-x)))
235 (setq cols (apply 'concat (nreverse cols)))
236 (if tabulated-list-use-header-line
237 (setq header-line-format cols)
238 (setq header-line-format nil)
239 (set (make-local-variable 'tabulated-list--header-string) cols))))
241 (defun tabulated-list-print-fake-header ()
242 "Insert a fake Tabulated List \"header line\" at the start of the buffer."
243 (goto-char (point-min))
244 (let ((inhibit-read-only t))
245 (insert tabulated-list--header-string "\n")
246 (if tabulated-list--header-overlay
247 (move-overlay tabulated-list--header-overlay (point-min) (point))
248 (set (make-local-variable 'tabulated-list--header-overlay)
249 (make-overlay (point-min) (point))))
250 (overlay-put tabulated-list--header-overlay 'face 'underline)))
252 (defun tabulated-list-revert (&rest ignored)
253 "The `revert-buffer-function' for `tabulated-list-mode'.
254 It runs `tabulated-list-revert-hook', then calls `tabulated-list-print'."
255 (interactive)
256 (unless (derived-mode-p 'tabulated-list-mode)
257 (error "The current buffer is not in Tabulated List mode"))
258 (run-hooks 'tabulated-list-revert-hook)
259 (tabulated-list-print t))
261 (defun tabulated-list--column-number (name)
262 (let ((len (length tabulated-list-format))
263 (n 0)
264 found)
265 (while (and (< n len) (null found))
266 (if (equal (car (aref tabulated-list-format n)) name)
267 (setq found n))
268 (setq n (1+ n)))
269 (or found
270 (error "No column named %s" name))))
272 (defun tabulated-list-print (&optional remember-pos)
273 "Populate the current Tabulated List mode buffer.
274 This sorts the `tabulated-list-entries' list if sorting is
275 specified by `tabulated-list-sort-key'. It then erases the
276 buffer and inserts the entries with `tabulated-list-printer'.
278 Optional argument REMEMBER-POS, if non-nil, means to move point
279 to the entry with the same ID element as the current line."
280 (let ((inhibit-read-only t)
281 (entries (if (functionp tabulated-list-entries)
282 (funcall tabulated-list-entries)
283 tabulated-list-entries))
284 entry-id saved-pt saved-col)
285 (and remember-pos
286 (setq entry-id (tabulated-list-get-id))
287 (setq saved-col (current-column)))
288 (erase-buffer)
289 (unless tabulated-list-use-header-line
290 (tabulated-list-print-fake-header))
291 ;; Sort the entries, if necessary.
292 (when (and tabulated-list-sort-key
293 (car tabulated-list-sort-key))
294 (let* ((sort-column (car tabulated-list-sort-key))
295 (n (tabulated-list--column-number sort-column))
296 (sorter (nth 2 (aref tabulated-list-format n))))
297 ;; Is the specified column sortable?
298 (when sorter
299 (when (eq sorter t)
300 (setq sorter ; Default sorter checks column N:
301 (lambda (A B)
302 (setq A (aref (cadr A) n))
303 (setq B (aref (cadr B) n))
304 (string< (if (stringp A) A (car A))
305 (if (stringp B) B (car B))))))
306 (setq entries (sort entries sorter))
307 (if (cdr tabulated-list-sort-key)
308 (setq entries (nreverse entries)))
309 (unless (functionp tabulated-list-entries)
310 (setq tabulated-list-entries entries)))))
311 ;; Print the resulting list.
312 (dolist (elt entries)
313 (and entry-id
314 (equal entry-id (car elt))
315 (setq saved-pt (point)))
316 (apply tabulated-list-printer elt))
317 (set-buffer-modified-p nil)
318 ;; If REMEMBER-POS was specified, move to the "old" location.
319 (if saved-pt
320 (progn (goto-char saved-pt)
321 (move-to-column saved-col)
322 (recenter))
323 (goto-char (point-min)))))
325 (defun tabulated-list-print-entry (id cols)
326 "Insert a Tabulated List entry at point.
327 This is the default `tabulated-list-printer' function. ID is a
328 Lisp object identifying the entry to print, and COLS is a vector
329 of column descriptors."
330 (let ((beg (point))
331 (x (max tabulated-list-padding 0))
332 (ncols (length tabulated-list-format))
333 (inhibit-read-only t))
334 (if (> tabulated-list-padding 0)
335 (insert (make-string x ?\s)))
336 (dotimes (n ncols)
337 (setq x (tabulated-list-print-col n (aref cols n) x)))
338 (insert ?\n)
339 (put-text-property beg (point) 'tabulated-list-id id)
340 (put-text-property beg (point) 'tabulated-list-entry cols)))
342 (defun tabulated-list-print-col (n col-desc x)
343 "Insert a specified Tabulated List entry at point.
344 N is the column number, COL-DESC is a column descriptor \(see
345 `tabulated-list-entries'), and X is the column number at point.
346 Return the column number after insertion."
347 ;; TODO: don't truncate to `width' if the next column is align-right
348 ;; and has some space left.
349 (let* ((format (aref tabulated-list-format n))
350 (name (nth 0 format))
351 (width (nth 1 format))
352 (props (nthcdr 3 format))
353 (pad-right (or (plist-get props :pad-right) 1))
354 (right-align (plist-get props :right-align))
355 (label (if (stringp col-desc) col-desc (car col-desc)))
356 (label-width (string-width label))
357 (help-echo (concat (car format) ": " label))
358 (opoint (point))
359 (not-last-col (< (1+ n) (length tabulated-list-format))))
360 ;; Truncate labels if necessary (except last column).
361 (and not-last-col
362 (> label-width width)
363 (setq label (truncate-string-to-width label width nil nil t)
364 label-width width))
365 (setq label (bidi-string-mark-left-to-right label))
366 (when (and right-align (> width label-width))
367 (let ((shift (- width label-width)))
368 (insert (propertize (make-string shift ?\s)
369 'display `(space :align-to ,(+ x shift))))
370 (setq width (- width shift))
371 (setq x (+ x shift))))
372 (if (stringp col-desc)
373 (insert (propertize label 'help-echo help-echo))
374 (apply 'insert-text-button label (cdr col-desc)))
375 (let ((next-x (+ x pad-right width)))
376 ;; No need to append any spaces if this is the last column.
377 (when not-last-col
378 (when (> pad-right 0) (insert (make-string pad-right ?\s)))
379 (insert (propertize
380 (make-string (- next-x x label-width pad-right) ?\s)
381 'display `(space :align-to ,next-x))))
382 (put-text-property opoint (point) 'tabulated-list-column-name name)
383 next-x)))
385 (defun tabulated-list-delete-entry ()
386 "Delete the Tabulated List entry at point.
387 Return a list (ID COLS), where ID is the ID of the deleted entry
388 and COLS is a vector of its column descriptors. Move point to
389 the beginning of the deleted entry. Return nil if there is no
390 entry at point.
392 This function only changes the buffer contents; it does not alter
393 `tabulated-list-entries'."
394 ;; Assume that each entry occupies one line.
395 (let* ((id (tabulated-list-get-id))
396 (cols (tabulated-list-get-entry))
397 (inhibit-read-only t))
398 (when cols
399 (delete-region (line-beginning-position) (1+ (line-end-position)))
400 (list id cols))))
402 (defun tabulated-list-set-col (col desc &optional change-entry-data)
403 "Change the Tabulated List entry at point, setting COL to DESC.
404 COL is the column number to change, or the name of the column to change.
405 DESC is the new column descriptor, which is inserted via
406 `tabulated-list-print-col'.
408 If CHANGE-ENTRY-DATA is non-nil, modify the underlying entry data
409 by setting the appropriate slot of the vector originally used to
410 print this entry. If `tabulated-list-entries' has a list value,
411 this is the vector stored within it."
412 (let* ((opoint (point))
413 (eol (line-end-position))
414 (pos (line-beginning-position))
415 (id (tabulated-list-get-id pos))
416 (entry (tabulated-list-get-entry pos))
417 (prop 'tabulated-list-column-name)
418 (inhibit-read-only t)
419 name)
420 (cond ((numberp col)
421 (setq name (car (aref tabulated-list-format col))))
422 ((stringp col)
423 (setq name col
424 col (tabulated-list--column-number col)))
426 (error "Invalid column %s" col)))
427 (unless entry
428 (error "No Tabulated List entry at position %s" opoint))
429 (unless (equal (get-text-property pos prop) name)
430 (while (and (setq pos
431 (next-single-property-change pos prop nil eol))
432 (< pos eol)
433 (not (equal (get-text-property pos prop) name)))))
434 (when (< pos eol)
435 (delete-region pos (next-single-property-change pos prop nil eol))
436 (goto-char pos)
437 (tabulated-list-print-col col desc (current-column))
438 (if change-entry-data
439 (aset entry col desc))
440 (put-text-property pos (point) 'tabulated-list-id id)
441 (put-text-property pos (point) 'tabulated-list-entry entry)
442 (goto-char opoint))))
444 (defun tabulated-list-col-sort (&optional e)
445 "Sort Tabulated List entries by the column of the mouse click E."
446 (interactive "e")
447 (let* ((pos (event-start e))
448 (obj (posn-object pos)))
449 (with-current-buffer (window-buffer (posn-window pos))
450 (tabulated-list--sort-by-column-name
451 (get-text-property (if obj (cdr obj) (posn-point pos))
452 'tabulated-list-column-name
453 (car obj))))))
455 (defun tabulated-list-sort (&optional n)
456 "Sort Tabulated List entries by the column at point.
457 With a numeric prefix argument N, sort the Nth column."
458 (interactive "P")
459 (let ((name (if n
460 (car (aref tabulated-list-format n))
461 (get-text-property (point)
462 'tabulated-list-column-name))))
463 (tabulated-list--sort-by-column-name name)))
465 (defun tabulated-list--sort-by-column-name (name)
466 (when (and name (derived-mode-p 'tabulated-list-mode))
467 ;; Flip the sort order on a second click.
468 (if (equal name (car tabulated-list-sort-key))
469 (setcdr tabulated-list-sort-key
470 (not (cdr tabulated-list-sort-key)))
471 (setq tabulated-list-sort-key (cons name nil)))
472 (tabulated-list-init-header)
473 (tabulated-list-print t)))
475 ;;; The mode definition:
477 (define-derived-mode tabulated-list-mode special-mode "Tabulated"
478 "Generic major mode for browsing a list of items.
479 This mode is usually not used directly; instead, other major
480 modes are derived from it, using `define-derived-mode'.
482 In this major mode, the buffer is divided into multiple columns,
483 which are labeled using the header line. Each non-empty line
484 belongs to one \"entry\", and the entries can be sorted according
485 to their column values.
487 An inheriting mode should usually do the following in their body:
489 - Set `tabulated-list-format', specifying the column format.
490 - Set `tabulated-list-revert-hook', if the buffer contents need
491 to be specially recomputed prior to `revert-buffer'.
492 - Maybe set a `tabulated-list-entries' function (see below).
493 - Maybe set `tabulated-list-printer' (see below).
494 - Maybe set `tabulated-list-padding'.
495 - Call `tabulated-list-init-header' to initialize `header-line-format'
496 according to `tabulated-list-format'.
498 An inheriting mode is usually accompanied by a \"list-FOO\"
499 command (e.g. `list-packages', `list-processes'). This command
500 creates or switches to a buffer and enables the major mode in
501 that buffer. If `tabulated-list-entries' is not a function, the
502 command should initialize it to a list of entries for displaying.
503 Finally, it should call `tabulated-list-print'.
505 `tabulated-list-print' calls the printer function specified by
506 `tabulated-list-printer', once for each entry. The default
507 printer is `tabulated-list-print-entry', but a mode that keeps
508 data in an ewoc may instead specify a printer function (e.g., one
509 that calls `ewoc-enter-last'), with `tabulated-list-print-entry'
510 as the ewoc pretty-printer."
511 (setq truncate-lines t)
512 (setq buffer-read-only t)
513 (set (make-local-variable 'revert-buffer-function)
514 'tabulated-list-revert)
515 (set (make-local-variable 'glyphless-char-display)
516 tabulated-list-glyphless-char-display))
518 (put 'tabulated-list-mode 'mode-class 'special)
520 (provide 'tabulated-list)
522 ;; Local Variables:
523 ;; coding: utf-8
524 ;; End:
526 ;;; tabulated-list.el ends here