help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Maybe we can improve this function call-process-to-string?


From: Stefan Monnier
Subject: Re: Maybe we can improve this function call-process-to-string?
Date: Thu, 08 Apr 2021 13:49:42 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/28.0.50 (gnu/linux)

> (defun call-process-to-string (program &optional infile display &rest args)
>   (let* ((buffer-name "Output")
>        (buffer (generate-new-buffer buffer-name))
>        (status (apply #'call-process program infile buffer display args))
>        (current-buffer (current-buffer))
>        (output (if status
>                    (progn 
>                      (switch-to-buffer buffer)
>                      (buffer-string))
>                  "")))
>     (switch-to-buffer current-buffer)
>     output))

The docstring of `switch-to-buffer` is fairly long, but the first
5 lines are recommended reading:

    Display buffer BUFFER-OR-NAME in the selected window.
    
    WARNING: This is NOT the way to work on another buffer temporarily
    within a Lisp program!  Use `set-buffer' instead.  That avoids
    messing with the window-buffer correspondences.

Also the above code forgot to kill the buffer you created.
I recommend `with-temp-buffer` here instead:

    (with-temp-buffer
      (apply #'call-process program infile t display args)
      (buffer-string))


-- Stefan




reply via email to

[Prev in Thread] Current Thread [Next in Thread]