-1

I want to print an alist in a specific named buffer, which I have to create if it does not exist. either by tabulated-list-format or using table-contents. How can I adapt these two functions to print an alist in a specified named buffer ?

(defun print-alist (alist)
  (let ((buffer (get-buffer-create "*Messages*")))
    (with-current-buffer buffer
      (setq tabulated-list-format
            [("Key" 20 t)
             ("Value" 20 t)])
      (setq tabulated-list-sort-key (cons "Key" nil))
      (setq tabulated-list-entries
            (mapcar (lambda (pair)
                      (list (car pair) (cdr pair)))
                    alist))
      (tabulated-list-init-header)
      (tabulated-list-print))
    (display-buffer buffer)))

(defun print-alist2 (alist)
  (let ((table-format '("%-20s %-20s\n"))
        (table-contents (mapcar (lambda (pair)
                                  (list (car pair) (cdr pair)))
                                alist)))
    (message (apply 'format table-format
                    (cons '("Key" "Value") table-contents)))))

1 Answer 1

0

The question isn't clear, as it doesn't say anything about arg ALIST other than that it's an alist.


Your print-alist works as you request, provided ALIST is of a form expected for tabulated-list-entries: a list, each element of which has the form (ID [DESC1 DESC2]), as described in C-h v tabulated-list-entries, for the two-column case you impose by your value of tabulated-list-format.

(setq foo '((a . ["a1" "a2"]) (b . ["b1" "b2"]) (c . ["c1" "c2"])))
(print-alist foo)

(But some advice: Don't use buffer *Messages* for your output. Just let Emacs continue to use that for what it usually does with it.)

If you intend to use some other form of alist then just transform its elements to the form needed. (E.g., you can use function vector, if necessary.)


For your print-alist2, here's a quick-and-dirty fix (with a different kind of alist). But again, it makes little sense to print such a table to *Messages*.

(setq foo '((a1 . a2) (b1 . b2) (c1 . c2)))

(defun print-alist2 (alist)
  (let ((table-format "%-20s %-20s\n"))
    (message (format table-format "Key" "Value"))
  (dolist (ii  alist)
    (message (format table-format (car ii) (cdr ii))))))
2
  • How can I write ta a different buffer ?
    – Dilna
    Commented Jun 13, 2023 at 17:45
  • write-file, write-region, etc. Ask Emacs.
    – Drew
    Commented Jun 13, 2023 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.