1

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.

1

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)
0

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

2
  • 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 '20 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. – Gilles 'SO- stop being evil' Jun 30 '20 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.