For example in gdb mode, there is a buffer named *input/output of <program name>*, that I want to clear each time I press C-c l.

2 Answers 2


In general, if you don't know the exact name of the buffer, you need to call buffer-list to obtain the list of buffers and filter the result to only act on the desired buffer(s).

Untested code:

(defun erase-buffers-matching (regexp)
  "Erase the content of all buffers whose name matches REGEXP."
  (interactive "sErase buffers matching: ")
    (mapc (lambda (buffer)
             ((not (string-match regexp (buffer-name buffer))))
             ((and (buffer-file-name buffer) (buffer-modified-p buffer))
              (message "Skipping buffer %s with unsaved data" (buffer-name buffer))
              (with-current-buffer buffer

For the specific case of the GDB program output buffer, GDB keeps track of it. It's the gdb-inferior-io buffer.

(defun erase-gdb-inferior-io-buffer ()
  (with-current-buffer (gdb-get-buffer 'gdb-inferior-io)
(global-set-key (kbd "C-c l") 'erase-gdb-inferior-io-buffer)

If this is something you want to do often, you could define a function for it in your .emacs file. Otherwise you could type it out in scratch, evaluate it and then assign it a key binding?

You could try:

(defun my/clear_buffer ()
  (let ((tmp (buffer-name)))
  (if (get-buffer "<buffer name>")              ;; check if buffer exists
      (progn (switch-to-buffer "<buffer name>") ;; switch to the buffer
         (erase-buffer)                         ;; erase it
         (switch-to-buffer tmp)))))             ;; switch back

  • The thing is that <buffer name> is not constant, it changes with the program being debugged. Is there a way to get the buffer by regexp instead? so I can use only the substring *input/output of with get-buffer?
    – Bite Bytes
    Jun 30, 2020 at 12:55
  • 2
    Never use switch-to-buffer to act on a buffer. It's for changing which buffer is displayed on a window. To act on a buffer from Lisp code, use with-current-buffer, or for more complex cases save-excursion and set-buffer. Jun 30, 2020 at 18:33

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.