Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an Emacs Elisp function how to open a new buffer window, print a string to it, then close it with the keyboard press 'q'?

I am relatively new to elisp and I do not know how to phrase my question to find the answer on Google

I would like to define a function to:

  • open a new buffer
  • print a string into that buffer
  • close the buffer and window when the user focuses it and presses 'q'

What I have tried is

(defun test ()
    (switch-to-buffer-other-window "*test*")
    (erase-buffer)
    (insert "hello from *test*")
    (kill-this-buffer))

(test)

But that does not work the way I want it to.

For clarity, here is an image breakdown of what I would like the function to do:

Initial setup

enter image description here

The function test is executed

enter image description here

Focus remains on the initial buffer, then buffer named *test* is focused and q is pressed on the keyboard

enter image description here

The window configuration now does not have *test* in it and focus returns to the initial buffer

I plan on using this function to print my personal keybindings into the *test* buffer so I do not have to open my .emacs to see them

like image 246
zzelman Avatar asked Nov 18 '25 16:11

zzelman


1 Answers

You might be looking for macro with-help-window:

(defun test ()
  (interactive)
  (with-help-window "*test*"
    (princ "hello from test")))

If you want to be able to use insert instead of princ, then you can use this:

(defun test ()
  (interactive)
  (with-help-window "*test*"
    (with-current-buffer "*test*"
      (princ "hello from test"))))

(If you are using an older Emacs that does not have with-help-window then you can use with-output-to-temp-buffer instead.)

(The interactive is just so you can test it easily.)

like image 63
Drew Avatar answered Nov 21 '25 06:11

Drew