The Complete Computing Environment

Emacs Persistent Scratch

(provide 'cce/persistent-scratch)

By default, my machine drops me in to a *scratch* buffer. Originally designed to be an lisp playground that you could dive right in to on start up, it's sort of eclipsed that for me in to a general purpose buffer, where I will put things like elisp I am prototyping or playtesting, small snippets of code that I want to use in dayjob, etc. But when you kill emacs, or it dies, that buffer disappears. This code will save the Scratch buffer every five minutes and restores it on Emacs startup.

(defun save-persistent-scratch ()
  "Write the contents of *scratch* to the file name
  (with-current-buffer (get-buffer-create "*scratch*")
    (write-region (point-min) (point-max) "~/.emacs.d/persistent-scratch")))

(defun load-persistent-scratch ()
  "Load the contents of `persistent-scratch-file-name' into the
  scratch buffer, clearing its contents first."
  (if (file-exists-p "~/.emacs.d/persistent-scratch")
      (with-current-buffer (get-buffer "*scratch*")
        (delete-region (point-min) (point-max))
        (insert-file-contents "~/.emacs.d/persistent-scratch"))))

(add-hook 'after-cce-hook 'load-persistent-scratch)
(add-hook 'kill-emacs-hook 'save-persistent-scratch)

(if (not (boundp 'cce/save-persistent-scratch-timer))
    (setq cce/save-persistent-scratch-timer
          (run-with-idle-timer 300 t 'save-persistent-scratch)))