I use the Emacs desktop module to save my open buffers between sessions. However I found that this accumulates more buffers than I want, so I wrote a small function to clean up the buffer list immediately before saving to the desktop file. This works as expected, but for strange reasons the .emacs.desktop gets scrambled occasionally, i.e. it contains a part of another buffer at its start, then the intended contents and then the result of the other buffer. I don't have the slightest idea, why this happens. Here is an excerpt from my .emacs file:
(defun kill-old-buffers ()
"Kill buffers from end of buffer list (not used recently) until no more than 50 buffers are left. Remove temporary buffers first"
(interactive)
(let* (desktop-buffer (current-buffer))
(dolist (buffer (buffer-list))
(if (or (string-match "^\*" (buffer-name buffer)) (string-match "\.hpp$" (buffer-name buffer)))
(kill-buffer buffer)
)
)
(setq all-buffers (reverse (buffer-list)))
(while (> (safe-length all-buffers) 50)
(setq buffer (pop all-buffers))
(if (not (string-equal (buffer-name buffer) (buffer-name (current-buffer))))
(kill-buffer buffer)
)
)
(switch-to-buffer desktop-buffer)
))
;; Kill old rarely-used buffers before saving
(add-hook 'desktop-save-hook
'(lambda () (kill-old-buffers)))
Any help would be appreciated.
I'm not sure if your function is really the cause of your problem. If it should be the case, the wrong usage of the
let*
that scottfrazer pointed out might be the cause. But you don't even need thatlet*
(andswitch-to-buffer
) at all, becausesave-excursion
, andOTOH, you should have used
let
instead of thesetq
s in the lower half of your function, becausesetq
will otherwise change a variable from an enclosing lexical scope. In this case you might very well have stomped over abuffer
variable from the function that's executing thedesktop-save-hook
which is another potential cause of your problem.But you don't need those
let
s either because you can do the second loop with anotherdolist
. You can get rid of those first 50 buffers that you don't want to loop over withnthcdr
.Here's my improved version of
kill-old-buffers
: