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