Some time ago I coded a certain Elisp tool (for internal use at Wiadomości Matematyczne) and I needed to preserve the value of some variable between Emacs sessions. I asked how to do this on the Emacs mailing list, and I received a whole lot of very interesting and worthwhile responses. I decided to stay simple, though, and used the snippet of code I mentioned there to just add some variable and its value to init.el
. For your convenience, here is the code – although I strongly suggest reading the mentioned thread before using it. My use-case is quite specific, and for most cases the solution described there will be better. Use this at your own risk!
(defun make-variable-persistent (variable-name) "Save VARIABLE-NAME to `custom-file' or `init-file'." (when (y-or-n-p (format "I am going to save variable `%s' in %s. Should I proceed? " variable-name user-init-file)) (with-temp-file user-init-file (let ((sentinel-text (format "\n;; Persistent variable `%s'. Do not edit manually!\n" variable-name))) (insert-file-contents user-init-file) (if (search-forward sentinel-text nil t) (if (not (looking-at-p (format "^(setq %s" variable-name))) (error "Broken init file") (kill-sexp) (when (eq (char-after (point)) ?\n) (delete-char 1))) (goto-char (point-max)) (insert sentinel-text))) (insert (format "(setq %s %S)\n" variable-name (symbol-value variable-name))))))