louxiu
louxiu

Reputation: 2915

How to redirect standard output to a file in Elisp using EMACS

I use with-output-to-temp-buffer function, redirect the standard output to it, save it to a file, switch back to previous buffer, then kill the temp buffer.

(require 'find-lisp)
(with-output-to-temp-buffer "*my output*" 
  (mapc 'print (find-lisp-find-files "~/project/clisp" "\\.lisp$"))
  (setq prev-buffer (buffer-name))
  (switch-to-buffer "*my output*")
  (write-region nil nil "test")
  (switch-to-buffer prev-buffer)
  (kill-buffer "*my output*")
  )

But error below occur. I don't know why.

Debugger entered--Lisp error: (error "Selecting deleted buffer")

PS: Is there more elegant way to achieve this in elsip(redirect standard output to a file). Thanks

Upvotes: 3

Views: 1274

Answers (1)

legoscia
legoscia

Reputation: 41528

This error occurs because with-output-to-temp-buffer tries to display the buffer after evaluating its body, but at that point you have already deleted the buffer. I think with-temp-file is the macro you're looking for. Its docstring says:

(with-temp-file FILE &rest BODY)

Create a new buffer, evaluate BODY there, and write the buffer to FILE.

You can then bind standard-output to the new buffer, something like:

(with-temp-file "test.txt"
  (let ((standard-output (current-buffer)))
    (mapc 'print (find-lisp-find-files "~/project/clisp" "\\.lisp$"))))

Upvotes: 9

Related Questions