I have my eshell opened in a window and in another window I have *Scratch*
as a open buffer. I want to redirect the output of a command like say ls
to *Scratch*
. Is it possible? If yes, then how can I do it? Thanks.
2 Answers
Yes:
ls >(get-buffer "*scratch*")
Or even
ls > #<buffer *scratch*>
See this question for more details.
-
Can you elaborate on your answer?– user12563Commented Feb 5, 2019 at 19:26
-
-
I think you don't even need the word "buffer",
ls > #<*scratch*>
seems to work too.– OmarCommented Feb 5, 2019 at 19:53 -
@Omar Yes Omar, they have simplified that. (Don't know the version where this was introduced.)– TobiasCommented Apr 30, 2020 at 11:54
The following answer uses a different approach than was suggested by the original poster. In this example, we use shell-command-to-string
: https://www.gnu.org/software/emacs/manual/html_node/elisp/Synchronous-Processes.html
The default-directory
in this example is hard-coded to "~/"
, which may or may not be the default-directory
of the *scratch*
buffer. We use let*
(instead of just plain old let
) so that shell-command-to-string
respects the hard-coded default-directory
that was let*
-bound on the preceding line. If the *scratch*
buffer did not already exist, then a new one will be created and its default-directory
will be "~/"
. We go to the bottom of the *scratch*
buffer just in case point
was somewhere else. If the buffer is not already visible, then display it in another window.
To try out this example, type M-x eval-expression
and paste the snippet into the mini-buffer when prompted and press the return key.
(let* ((default-directory "~/")
(string (shell-command-to-string "ls"))
(buffer (get-buffer-create "*scratch*")))
(with-current-buffer buffer
(goto-char (point-max))
(insert string))
(unless (get-buffer-window "*scratch*")
(display-buffer buffer t)))