20.3.6 Updating Time Stamps Automatically

You can arrange to have a time stamp in a file be updated automatically each time you save the file. (A time stamp may also be called a date stamp or a last modified time.) Having a time stamp in the text of a file ensures that the time the file was written will be preserved even if the file is copied or transformed in a way that loses the file system’s modification time.

There are two steps to setting up automatic time stamping. First, the file needs a time stamp template somewhere in the first eight lines. The template looks like this:

Time-stamp: <>

or (your choice) like this:

Time-stamp: " "

With that template in place, you can update the current buffer’s time stamp once immediately with the command M-x time-stamp. Emacs will check for a template; if a template is found, Emacs will write the current date, time, author, and/or other info between the brackets or quotes. (If the buffer has no template, time-stamp does nothing.) After the first time stamp, the line might look like this:

Time-stamp: <1993-07-06 11:05:14 terryg>

Second, configure your Emacs to run time-stamp whenever it saves a file, by adding time-stamp to before-save-hook (see Hooks). You can either use M-x customize-option (see Customizing Specific Items) to customize the option before-save-hook, or you can edit your init file adding this line:

(add-hook 'before-save-hook 'time-stamp)