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
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: ")
(save-match-data
(mapc (lambda (buffer)
(cond
((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))
(t
(with-current-buffer buffer
(erase-buffer)))))
(buffer-list))))
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 ()
(interactive)
(with-current-buffer (gdb-get-buffer 'gdb-inferior-io)
(erase-buffer)))
(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 ()
(interactive)
(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
withget-buffer
? Commented Jun 30, 2020 at 12:55 -
2Never 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, usewith-current-buffer
, or for more complex casessave-excursion
andset-buffer
. Commented Jun 30, 2020 at 18:33