If I use the internal C function `write-region' instead of `write-file' from "files.el", then the following code works with my Emacs23, because `write-region' doesn't call the Emacs file-hooks:
Code: Select all
(defvar autobk-default-dir (expand-file-name "~/.emacsbk/"))
(defun autobk-save ()
"Write the entire buffer contents as text to a backup file."
(write-region nil nil (format "%s%s_%s.bak" autobk-default-dir (buffer-name)
(format-time-string "%Y-%m-%d" (current-time)))))
(add-hook 'before-save-hook 'autobk-save)
Note that in contrast to the `write-file' function, `write-region' is a plain and stupid "write buffer contents to destination" function that doesn't check if the "~/.emacsbk/" directory exists or is writable at all. But it writes an error message to the *Messages* buffer if something goes wrong. The first two nil arguments mean "write the entire buffer contents as text, don't care about anything else".
The `autobk-save' function could be improved by adding Elisp code to check if the directory exists and is writable, or automatically creates the directory if it doesn't exist. See the Elisp manual, chapter "Files" that also describes the functions for directories which on Unix and Linux are files as well.
Another alternative would be to use Elisp functions like `copy-file' for simple harddisk "copy and rename" operations *before* opening and *after* saving a file.