Projectile has a function to close all buffers related to a project (projectile-kill-buffers). Normally I also open non project related files during the day or emacs opens them when I'm stepping through compiler errors. Is there a way to close all buffers except project and special buffers?

1 Answer 1


Save the below function to your emacs init and call it via M-x.

By default this function will kill all buffers except the ones that belong to a projectile project or are special.

The same function will also kill special buffers (except *scratch* and *Messages*) if called with a prefix like C-u.

(defun modi/kill-non-project-buffers (&optional kill-special)
  "Kill buffers that do not belong to a `projectile' project.

With prefix argument (`C-u'), also kill the special buffers."
  (interactive "P")
  (let ((bufs (buffer-list (selected-frame))))
    (dolist (buf bufs)
      (with-current-buffer buf
        (let ((buf-name (buffer-name buf)))
          (when (or (null (projectile-project-p))
                    (and kill-special
                         (string-match "^\*" buf-name)))
            ;; Preserve buffers with names starting with *scratch or *Messages
            (unless (string-match "^\\*\\(\\scratch\\|Messages\\)" buf-name)
              (message "Killing buffer %s" buf-name)
              (kill-buffer buf))))))))

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.