time-stamp.el 26.8 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1 2
;;; time-stamp.el --- Maintain last change time stamps in files edited by Emacs

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1989, 1993-1995, 1997, 2000-2020 Free Software
4
;; Foundation, Inc.
Erik Naggum's avatar
Erik Naggum committed
5

6 7
;; This file is part of GNU Emacs.

Paul Eggert's avatar
Paul Eggert committed
8
;; Maintainer: Stephen Gildea <stepheng+emacs@gildea.com>
Richard M. Stallman's avatar
Richard M. Stallman committed
9 10
;; Keywords: tools

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
15

Eli Zaretskii's avatar
Eli Zaretskii committed
16
;; GNU Emacs is distributed in the hope that it will be useful,
Richard M. Stallman's avatar
Richard M. Stallman committed
17 18 19 20 21
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
23 24 25

;;; Commentary:

26 27
;; A template in a file can be updated with a new time stamp when
;; you save the file.  For example:
28
;;     static char *ts = "sdmain.c Time-stamp: <2001-08-13 10:20:51 gildea>";
29

30
;; To use time-stamping, add this line to your init file:
31
;;     (add-hook 'before-save-hook 'time-stamp)
32 33 34 35
;; Now any time-stamp templates in your files will be updated automatically.

;; See the documentation for the functions `time-stamp'
;; and `time-stamp-toggle-active' for details.
Erik Naggum's avatar
Erik Naggum committed
36

Richard M. Stallman's avatar
Richard M. Stallman committed
37 38
;;; Code:

39 40 41 42 43
(defgroup time-stamp nil
  "Maintain last change time stamps in files edited by Emacs."
  :group 'data
  :group 'extensions)

44
(defcustom time-stamp-format "%Y-%02m-%02d %02H:%02M:%02S %l"
Lute Kamstra's avatar
Lute Kamstra committed
45
  "Format of the string inserted by \\[time-stamp].
46
This is a string, used verbatim except for character sequences beginning
Dave Love's avatar
Dave Love committed
47
with %, as follows.  The values of non-numeric formatted items depend
48 49
on the locale setting recorded in `system-time-locale' and
`locale-coding-system'.  The examples here are for the default
50
\(`C') locale.
51

52 53 54 55
%:A  weekday name: `Monday'             %#A gives uppercase: `MONDAY'
%3a  abbreviated weekday: `Mon'         %#a gives uppercase: `MON'
%:B  month name: `January'              %#B gives uppercase: `JANUARY'
%3b  abbreviated month: `Jan'           %#b gives uppercase: `JAN'
56 57 58 59 60
%02d day of month
%02H 24-hour clock hour
%02I 12-hour clock hour
%02m month number
%02M minute
61
%#p  `am' or `pm'                       %P  gives uppercase: `AM' or `PM'
62 63
%02S seconds
%w   day number of week, Sunday is 0
64
%02y 2-digit year: `03'                 %Y  4-digit year: `2003'
65 66
%Z   time zone name: `EST'              %#Z gives lowercase: `est'
%5z  time zone offset: `-0500' (since Emacs 27; see note below)
67 68 69

Non-date items:
%%   a literal percent character: `%'
70 71 72
%f   file name without directory        %F  gives absolute pathname
%l   login name                         %L  full name of logged-in user
%q   unqualified host name              %Q  fully-qualified host name
73 74 75
%h   mail host name

Decimal digits between the % and the type character specify the
76
field width.  Strings are truncated on the right.
77
A leading zero in the field width zero-fills a number.
78 79

For example, to get the format used by the `date' command,
80
use \"%3a %3b %2d %02H:%02M:%02S %Z %Y\".
81

82 83 84
The default padding of some formats has changed to be more compatible
with format-time-string.  To be compatible with older versions of Emacs,
specify a padding width (as shown) or use the : modifier to request the
85 86 87 88
transitional behavior (again, as shown).

The behavior of `%5z' is new in Emacs 27.  If your files might be
edited by older versions of Emacs also, do not use this format yet."
89
  :type 'string
90
  :group 'time-stamp
91
  :version "27.1")
92
;;;###autoload(put 'time-stamp-format 'safe-local-variable 'stringp)
93

94
(defcustom time-stamp-active t
Lute Kamstra's avatar
Lute Kamstra committed
95
  "Non-nil to enable time-stamping of buffers by \\[time-stamp].
96 97 98 99 100 101
Can be toggled by \\[time-stamp-toggle-active].
See also the variable `time-stamp-warn-inactive'."
  :type 'boolean
  :group 'time-stamp)

(defcustom time-stamp-warn-inactive t
102
  "Have \\[time-stamp] warn if a buffer did not get time-stamped.
103 104 105
If non-nil, a warning is displayed if `time-stamp-active' has
deactivated time stamping and the buffer contains a template that
otherwise would have been updated."
106
  :type 'boolean
107 108
  :group 'time-stamp
  :version "19.29")
109 110

(defcustom time-stamp-time-zone nil
111
  "The time zone to be used by \\[time-stamp].
112
Its format is that of the ZONE argument of the `format-time-string' function."
113 114 115
  :type '(choice (const :tag "Emacs local time" nil)
                 (const :tag "Universal Time" t)
                 (const :tag "system wall clock time" wall)
116 117 118 119 120
                 (string :tag "TZ environment variable value")
                 (list :tag "Offset and name"
                       (integer :tag "Offset (seconds east of UTC)")
                       (string :tag "Time zone abbreviation"))
                 (integer :tag "Offset (seconds east of UTC)"))
121 122
  :group 'time-stamp
  :version "20.1")
123 124 125 126 127 128 129 130 131 132 133 134 135
;;;###autoload(put 'time-stamp-time-zone 'safe-local-variable 'time-stamp-zone-type-p)

;;;###autoload
(defun time-stamp-zone-type-p (zone)
  "Return whether or not ZONE is of the correct type for a timezone rule.
Valid ZONE values are described in the documentation of `format-time-string'."
  (or (memq zone '(nil t wall))
      (stringp zone)
      (and (consp zone)
           (integerp (car zone))
           (consp (cdr zone))
           (stringp (cadr zone)))
      (integerp zone)))
136

137
;;; Do not change time-stamp-line-limit, time-stamp-start,
138 139 140 141
;;; time-stamp-end, time-stamp-pattern, time-stamp-inserts-lines,
;;; or time-stamp-count in your .emacs or you will be incompatible
;;; with other people's files!  If you must change them, do so only
;;; in the local variables section of the file itself.
Richard M. Stallman's avatar
Richard M. Stallman committed
142

143

144
(defvar time-stamp-line-limit 8	    ;Do not change!
145
  "Lines of a file searched; positive counts from start, negative from end.
146 147
The patterns `time-stamp-start' and `time-stamp-end' must be found in
the first (last) `time-stamp-line-limit' lines of the file for the
148 149
file to be time-stamped by \\[time-stamp].  A value of 0 searches the
entire buffer (use with care).
150

151 152 153 154 155 156 157
This value can also be set with the variable `time-stamp-pattern'.

Do not change `time-stamp-line-limit', `time-stamp-start',
`time-stamp-end', or `time-stamp-pattern' for yourself or you will be
incompatible with other people's files!  If you must change them for some
application, do so in the local variables section of the time-stamped file
itself.")
158
;;;###autoload(put 'time-stamp-line-limit 'safe-local-variable 'integerp)
Richard M. Stallman's avatar
Richard M. Stallman committed
159

160
(defvar time-stamp-start "Time-stamp:[ \t]+\\\\?[\"<]+"    ;Do not change!
Richard M. Stallman's avatar
Richard M. Stallman committed
161
  "Regexp after which the time stamp is written by \\[time-stamp].
162
See also the variables `time-stamp-end' and `time-stamp-line-limit'.
Richard M. Stallman's avatar
Richard M. Stallman committed
163

164 165 166 167 168 169 170
This value can also be set with the variable `time-stamp-pattern'.

Do not change `time-stamp-line-limit', `time-stamp-start',
`time-stamp-end', or `time-stamp-pattern' for yourself or you will be
incompatible with other people's files!  If you must change them for some
application, do so in the local variables section of the time-stamped file
itself.")
171
;;;###autoload(put 'time-stamp-start 'safe-local-variable 'stringp)
Richard M. Stallman's avatar
Richard M. Stallman committed
172

173
(defvar time-stamp-end "\\\\?[\">]"    ;Do not change!
Richard M. Stallman's avatar
Richard M. Stallman committed
174
  "Regexp marking the text after the time stamp.
175
\\[time-stamp] deletes the text between the first match of `time-stamp-start'
176 177
and the following match of `time-stamp-end', then writes the
time stamp specified by `time-stamp-format' between them.
178

179 180
This value can also be set with the variable `time-stamp-pattern'.

181 182 183 184 185 186
The end text normally starts on the same line as the start text ends,
but if there are any newlines in `time-stamp-format', the same number
of newlines must separate the start and end.  \\[time-stamp] tries
to not change the number of lines in the buffer.  `time-stamp-inserts-lines'
controls this behavior.

187
Do not change `time-stamp-start', `time-stamp-end', `time-stamp-pattern',
188
or `time-stamp-inserts-lines' for yourself or you will be incompatible
189 190
with other people's files!  If you must change them for some application,
do so in the local variables section of the time-stamped file itself.")
191
;;;###autoload(put 'time-stamp-end 'safe-local-variable 'stringp)
192

Richard M. Stallman's avatar
Richard M. Stallman committed
193

194
(defvar time-stamp-inserts-lines nil    ;Do not change!
195
  "Whether \\[time-stamp] can change the number of lines in a file.
196 197 198 199 200 201 202 203 204 205 206 207
If nil, \\[time-stamp] skips as many lines as there are newlines in
`time-stamp-format' before looking for the `time-stamp-end' pattern,
thus it tries not to change the number of lines in the buffer.
If non-nil, \\[time-stamp] starts looking for the end pattern
immediately after the start pattern.  This behavior can cause
unexpected changes in the buffer if used carelessly, but it is useful
for generating repeated time stamps.

Do not change `time-stamp-end' or `time-stamp-inserts-lines' for
yourself or you will be incompatible with other people's files!
If you must change them for some application, do so in the local
variables section of the time-stamped file itself.")
208
;;;###autoload(put 'time-stamp-inserts-lines 'safe-local-variable 'symbolp)
209 210 211


(defvar time-stamp-count 1		;Do not change!
212
  "How many templates \\[time-stamp] will look for in a buffer.
213
The same time stamp will be written in each case.
214 215 216 217 218

Do not change `time-stamp-count' for yourself or you will be
incompatible with other people's files!  If you must change it for
some application, do so in the local variables section of the
time-stamped file itself.")
219
;;;###autoload(put 'time-stamp-count 'safe-local-variable 'integerp)
220 221


222
(defvar time-stamp-pattern nil		;Do not change!
223
  "Convenience variable setting all `time-stamp' location and format values.
224
This string has four parts, each of which is optional.
225 226
These four parts set `time-stamp-line-limit', `time-stamp-start',
`time-stamp-format', and `time-stamp-end'.  See the documentation
227 228 229 230
for each of these variables for details.

The first part is a number followed by a slash; the number sets the number
of lines at the beginning (negative counts from end) of the file searched
231
for the time stamp.  The number and the slash may be omitted to use the
232 233 234 235 236
normal value.

The second part is a regexp identifying the pattern preceding the time stamp.
This part may be omitted to use the normal pattern.

237
The third part specifies the format of the time stamp inserted.  See
238
the documentation for `time-stamp-format' for details.  Specify this
239 240 241 242 243
part as \"%%\" to use the normal format.

The fourth part is a regexp identifying the pattern following the time stamp.
This part may be omitted to use the normal pattern.

244
Examples:
245 246 247 248

\"-10/\" (sets only `time-stamp-line-limit')

\"-9/^Last modified: %%$\" (sets `time-stamp-line-limit',
249
`time-stamp-start' and `time-stamp-end')
250

251 252
\"@set Time-stamp: %:B %1d, %Y$\" (sets `time-stamp-start',
`time-stamp-format' and `time-stamp-end')
253

254 255
\"newcommand{\\\\\\\\timestamp}{%%}\" (sets `time-stamp-start'
and `time-stamp-end')
256

257 258 259 260 261
Do not change `time-stamp-pattern' `time-stamp-line-limit',
`time-stamp-start', or `time-stamp-end' for yourself or you will be
incompatible with other people's files!  If you must change them for
some application, do so only in the local variables section of the
time-stamped file itself.")
262
;;;###autoload(put 'time-stamp-pattern 'safe-local-variable 'stringp)
263 264


265

266
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
267
(defun time-stamp ()
268
  "Update the time stamp string(s) in the buffer.
269
A template in a file can be automatically updated with a new time stamp
270
every time you save the file.  Add this line to your init file:
271
    (add-hook \\='before-save-hook \\='time-stamp)
Luc Teirlinck's avatar
Luc Teirlinck committed
272
or customize `before-save-hook' through Custom.
273 274 275 276 277
Normally the template must appear in the first 8 lines of a file and
look like one of the following:
      Time-stamp: <>
      Time-stamp: \" \"
The time stamp is written between the brackets or quotes:
278
      Time-stamp: <2001-02-18 10:20:51 gildea>
279 280 281 282 283 284 285 286

The time stamp is updated only if the variable
`time-stamp-active' is non-nil.
The format of the time stamp is set by the variable
`time-stamp-pattern' or `time-stamp-format'.
The variables `time-stamp-pattern', `time-stamp-line-limit',
`time-stamp-start', `time-stamp-end', `time-stamp-count', and
`time-stamp-inserts-lines' control finding the template."
Richard M. Stallman's avatar
Richard M. Stallman committed
287
  (interactive)
288
  (let ((line-limit time-stamp-line-limit)
289 290
	(ts-start time-stamp-start)
	(ts-format time-stamp-format)
291 292 293 294 295 296
	(ts-end time-stamp-end)
	(ts-count time-stamp-count)
	(format-lines 0)
	(end-lines 1)
	(start nil)
	search-limit)
297 298
    (if (stringp time-stamp-pattern)
	(progn
299
	  (string-match "\\`\\(\\(-?[0-9]+\\)/\\)?\\([^%]+\\)?\\(\\(%[-.,:@+_ #^()0-9]*[A-Za-z%][^%]*\\)*%[-.,:@+_ #^()0-9]*[A-Za-z%]\\)?\\([^%]+\\)?\\'" time-stamp-pattern)
300 301
	  (and (match-beginning 2)
	       (setq line-limit
302
		     (string-to-number (match-string 2 time-stamp-pattern))))
303 304 305 306 307
	  (and (match-beginning 3)
	       (setq ts-start (match-string 3 time-stamp-pattern)))
	  (and (match-beginning 4)
	       (not (string-equal (match-string 4 time-stamp-pattern) "%%"))
	       (setq ts-format (match-string 4 time-stamp-pattern)))
308 309
	  (and (match-beginning 6)
	       (setq ts-end (match-string 6 time-stamp-pattern)))))
310 311
    (cond ((not (integerp line-limit))
	   (setq line-limit 8)
312
	   (message "time-stamp-line-limit is not an integer")
313
	   (sit-for 1)))
314 315 316 317 318 319 320 321 322
    (cond ((not (integerp ts-count))
	   (setq ts-count 1)
	   (message "time-stamp-count is not an integer")
	   (sit-for 1))
	  ((< ts-count 1)
	   ;; We need to call time-stamp-once at least once
	   ;; to output any warnings about time-stamp not being active.
	   (setq ts-count 1)))
    ;; Figure out what lines the end should be on.
323 324 325 326
    (if (stringp ts-format)
	(let ((nl-start 0))
	  (while (string-match "\n" ts-format nl-start)
	    (setq format-lines (1+ format-lines) nl-start (match-end 0)))))
327 328 329 330
    (let ((nl-start 0))
      (while (string-match "\n" ts-end nl-start)
	(setq end-lines (1+ end-lines) nl-start (match-end 0))))
    ;; Find overall what lines to look at
331 332 333 334 335 336 337
    (save-excursion
      (save-restriction
	(widen)
	(cond ((> line-limit 0)
	       (goto-char (setq start (point-min)))
	       (forward-line line-limit)
	       (setq search-limit (point)))
338
	      ((< line-limit 0)
339 340
	       (goto-char (setq search-limit (point-max)))
	       (forward-line line-limit)
341 342 343
	       (setq start (point)))
	      (t			;0 => no limit (use with care!)
	       (setq start (point-min))
344 345 346 347 348 349 350 351 352 353 354
	       (setq search-limit (point-max))))))
    (while (and start
		(< start search-limit)
		(> ts-count 0))
      (setq start (time-stamp-once start search-limit ts-start ts-end
				   ts-format format-lines end-lines))
      (setq ts-count (1- ts-count))))
  nil)

(defun time-stamp-once (start search-limit ts-start ts-end
			ts-format format-lines end-lines)
355
  "Update one time stamp.  Internal routine called by \\[time-stamp].
356 357 358 359 360 361 362 363 364 365
Returns the end point, which is where `time-stamp' begins the next search."
  (let ((case-fold-search nil)
	(end nil)
	end-search-start
	(end-length nil))
    (save-excursion
      (save-restriction
	(widen)
	;; Find the location of the time stamp.
	(while (and (< (goto-char start) search-limit)
366
		    (not end)
367
		    (re-search-forward ts-start search-limit 'move))
368
	  (setq start (point))
369 370 371 372 373 374 375 376 377 378 379 380 381 382
	  (if (not time-stamp-inserts-lines)
	      (forward-line format-lines))
	  (setq end-search-start (max start (point)))
	  (if (= (forward-line end-lines) 0)
	      (progn
	       (and (bolp) (backward-char))
	       (let ((line-end (min (point) search-limit)))
		 (if (>= line-end end-search-start)
		     (progn
		      (goto-char end-search-start)
		      (if (re-search-forward ts-end line-end t)
			  (progn
			    (setq end (match-beginning 0))
			    (setq end-length (- (match-end 0) end))))))))))))
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    (if end
	(progn
	  ;; do all warnings outside save-excursion
	  (cond
	   ((not time-stamp-active)
	    (if time-stamp-warn-inactive
		;; don't signal an error in a write-file-hook
		(progn
		  (message "Warning: time-stamp-active is off; did not time-stamp buffer.")
		  (sit-for 1))))
	   ((not (and (stringp ts-start)
		      (stringp ts-end)))
	    (message "time-stamp-start or time-stamp-end is not a string")
	    (sit-for 1))
	   (t
	    (let ((new-time-stamp (time-stamp-string ts-format)))
399 400 401
	      (if (and (stringp new-time-stamp)
		       (not (string-equal (buffer-substring start end)
					  new-time-stamp)))
402 403 404 405 406 407 408 409
		  (save-excursion
		    (save-restriction
		      (widen)
		      (delete-region start end)
		      (goto-char start)
		      (insert-and-inherit new-time-stamp)
		      (setq end (point))
		      ;; remove any tabs used to format time stamp
410 411 412 413 414 415 416 417
		      (if (search-backward "\t" start t)
			  (progn
			    (untabify start end)
			    (setq end (point))))))))))))
    ;; return the location after this time stamp, if there was one
    (and end end-length
	 (+ end end-length))))

Richard M. Stallman's avatar
Richard M. Stallman committed
418

419 420
;;;###autoload
(defun time-stamp-toggle-active (&optional arg)
421
  "Toggle `time-stamp-active', setting whether \\[time-stamp] updates a buffer.
422
With ARG, turn time stamping on if and only if arg is positive."
423 424 425 426 427
  (interactive "P")
  (setq time-stamp-active
	(if (null arg)
	    (not time-stamp-active)
	  (> (prefix-numeric-value arg) 0)))
428 429
  (message "time-stamp is now %s." (if time-stamp-active "active" "off")))

430 431
(defun time-stamp--format (format time)
  (format-time-string format time time-stamp-time-zone))
432

433
(defun time-stamp-string (&optional ts-format time)
434
  "Generate the new string to be inserted by \\[time-stamp].
435
Optionally use format TS-FORMAT instead of `time-stamp-format' to
436 437
format the string.  Optional second argument TIME is only for testing;
normally the current time is used."
438
  (if (stringp (or ts-format (setq ts-format time-stamp-format)))
439
      (time-stamp-string-preprocess ts-format time)))
440

441

442 443 444
(defconst time-stamp-no-file "(no file)"
  "String to use when the buffer is not associated with a file.")

445 446 447
;;; time-stamp is transitioning to be compatible with format-time-string.
;;; During the process, this function implements
;;; intermediate, compatible formats.
448 449 450 451 452 453 454
;;;      At all times, all the formats recommended in the doc string
;;; of time-stamp-format will work not only in the current version of
;;; Emacs, but in all versions that have been released within the past
;;; two years.
;;;      The : modifier is a temporary conversion feature used to resolve
;;; ambiguous formats--formats that are changing (over time) incompatibly.
(defun time-stamp-string-preprocess (format &optional time)
Dave Love's avatar
Dave Love committed
455 456 457
  "Use a FORMAT to format date, time, file, and user information.
Optional second argument TIME is only for testing.
Implements non-time extensions to `format-time-string'
458
and all `time-stamp-format' compatibility."
459 460 461 462 463 464 465
  (let ((fmt-len (length format))
	(ind 0)
	cur-char
	(prev-char nil)
	(result "")
	field-width
	field-result
466
	alt-form change-case upcase
467 468 469 470 471 472 473 474 475
	(paren-level 0))
    (while (< ind fmt-len)
      (setq cur-char (aref format ind))
      (setq
       result
       (concat result
      (cond
       ((eq cur-char ?%)
	;; eat any additional args to allow for future expansion
476
	(setq alt-form 0 change-case nil upcase nil field-width "")
477 478 479 480 481 482 483
	(while (progn
		 (setq ind (1+ ind))
		 (setq cur-char (if (< ind fmt-len)
				    (aref format ind)
				  ?\0))
		 (or (eq ?. cur-char)
		     (eq ?, cur-char) (eq ?: cur-char) (eq ?@ cur-char)
Dave Love's avatar
Dave Love committed
484
		     (eq ?- cur-char) (eq ?+ cur-char) (eq ?_ cur-char)
485
		     (eq ?\s cur-char) (eq ?# cur-char) (eq ?^ cur-char)
486 487 488 489 490 491 492 493
		     (and (eq ?\( cur-char)
			  (not (eq prev-char ?\\))
			  (setq paren-level (1+ paren-level)))
		     (if (and (eq ?\) cur-char)
			      (not (eq prev-char ?\\))
			      (> paren-level 0))
			 (setq paren-level (1- paren-level))
		       (and (> paren-level 0)
494 495 496 497 498 499 500 501 502 503 504 505 506
			    (< ind fmt-len)))
		     (if (and (<= ?0 cur-char) (>= ?9 cur-char))
			 ;; get format width
			 (let ((field-index ind))
			   (while (progn
				    (setq ind (1+ ind))
				    (setq cur-char (if (< ind fmt-len)
						       (aref format ind)
						     ?\0))
				    (and (<= ?0 cur-char) (>= ?9 cur-char))))
			   (setq field-width (substring format field-index ind))
			   (setq ind (1- ind))
			   t))))
507 508 509
	  (setq prev-char cur-char)
	  ;; some characters we actually use
	  (cond ((eq cur-char ?:)
510
		 (setq alt-form (1+ alt-form)))
511
		((eq cur-char ?#)
512 513 514 515 516 517 518
		 (setq change-case t))
		((eq cur-char ?^)
		 (setq upcase t))
		((eq cur-char ?-)
		 (setq field-width "1"))
		((eq cur-char ?_)
		 (setq field-width "2"))))
519 520 521
	(setq field-result
	(cond
	 ((eq cur-char ?%)
522
	  "%")
523
	 ((eq cur-char ?a)		;day of week
524
          (if (> alt-form 0)
525 526 527 528 529 530
               (if (string-equal field-width "")
                   (time-stamp--format "%A" time)
                 "")			;discourage "%:3a"
            (if (or change-case upcase)
                (time-stamp--format "%#a" time)
	      (time-stamp--format "%a" time))))
531
	 ((eq cur-char ?A)
532 533 534
	  (if (or change-case upcase (not (string-equal field-width "")))
	      (time-stamp--format "%#A" time)
	    (time-stamp--format "%A" time)))
535
	 ((eq cur-char ?b)		;month name
536
          (if (> alt-form 0)
537 538 539 540 541 542
               (if (string-equal field-width "")
                   (time-stamp--format "%B" time)
                 "")			;discourage "%:3b"
            (if (or change-case upcase)
                (time-stamp--format "%#b" time)
	      (time-stamp--format "%b" time))))
543
	 ((eq cur-char ?B)
544 545 546
	  (if (or change-case upcase (not (string-equal field-width "")))
	      (time-stamp--format "%#B" time)
	    (time-stamp--format "%B" time)))
547
	 ((eq cur-char ?d)		;day of month, 1-31
548
	  (time-stamp-do-number cur-char alt-form field-width time))
549
	 ((eq cur-char ?H)		;hour, 0-23
550
	  (time-stamp-do-number cur-char alt-form field-width time))
551
	 ((eq cur-char ?I)		;hour, 1-12
552
	  (time-stamp-do-number cur-char alt-form field-width time))
553
	 ((eq cur-char ?m)		;month number, 1-12
554
	  (time-stamp-do-number cur-char alt-form field-width time))
555
	 ((eq cur-char ?M)		;minute, 0-59
556
	  (time-stamp-do-number cur-char alt-form field-width time))
557
	 ((eq cur-char ?p)		;am or pm
558 559 560
	  (if change-case
              (time-stamp--format "%#p" time)
            (time-stamp--format "%p" time)))
561
	 ((eq cur-char ?P)		;AM or PM
562
	  (time-stamp--format "%p" time))
563
	 ((eq cur-char ?S)		;seconds, 00-60
564
	  (time-stamp-do-number cur-char alt-form field-width time))
565
	 ((eq cur-char ?w)		;weekday number, Sunday is 0
566
	  (time-stamp--format "%w" time))
567
	 ((eq cur-char ?y)		;year
568
          (if (> alt-form 0)
569
              (string-to-number (time-stamp--format "%Y" time))
570 571 572 573 574
            (if (or (string-equal field-width "")
                    (<= (string-to-number field-width) 2))
                (string-to-number (time-stamp--format "%y" time))
              (time-stamp-conv-warn (format "%%%sy" field-width) "%Y")
              (string-to-number (time-stamp--format "%Y" time)))))
575
	 ((eq cur-char ?Y)		;4-digit year
576
	  (string-to-number (time-stamp--format "%Y" time)))
577
	 ((eq cur-char ?z)		;time zone offset
578 579
	  (if change-case
	      ""			;discourage %z variations
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
            (cond ((= alt-form 0)
                   (if (string-equal field-width "")
                       (progn
                         (time-stamp-conv-warn "%z" "%#Z")
                         (time-stamp--format "%#Z" time))
                     (cond ((string-equal field-width "1")
                            (setq field-width "3")) ;%-z -> "+00"
                           ((string-equal field-width "2")
                            (setq field-width "5")) ;%_z -> "+0000"
                           ((string-equal field-width "4")
                            (setq field-width "0"))) ;discourage %4z
                     (time-stamp--format "%z" time)))
                  ((= alt-form 1)
                   (time-stamp--format "%:z" time))
                  ((= alt-form 2)
                   (time-stamp--format "%::z" time))
                  ((= alt-form 3)
                   (time-stamp--format "%:::z" time)))))
598
	 ((eq cur-char ?Z)              ;time zone name
599
	  (if change-case
600 601
	      (time-stamp--format "%#Z" time)
	    (time-stamp--format "%Z" time)))
602 603 604 605 606 607 608 609 610 611 612
	 ((eq cur-char ?f)		;buffer-file-name, base name only
	  (if buffer-file-name
	      (file-name-nondirectory buffer-file-name)
	    time-stamp-no-file))
	 ((eq cur-char ?F)		;buffer-file-name, full path
	  (or buffer-file-name
	      time-stamp-no-file))
	 ((eq cur-char ?s)		;system name
	  (system-name))
	 ((eq cur-char ?u)		;user name
	  (user-login-name))
613 614
	 ((eq cur-char ?U)		;user full name
	  (user-full-name))
615 616 617 618
	 ((eq cur-char ?l)		;logname (undocumented user name alt)
	  (user-login-name))
	 ((eq cur-char ?L)		;(undocumented alt user full name)
	  (user-full-name))
619
	 ((eq cur-char ?h)		;mail host name
620
	  (or mail-host-address (system-name)))
621 622 623 624 625 626 627
	 ((eq cur-char ?q)		;(undocumented unqual hostname)
	  (let ((qualname (system-name)))
	    (if (string-match "\\." qualname)
		(substring qualname 0 (match-beginning 0))
	      qualname)))
	 ((eq cur-char ?Q)		;(undocumented fully-qualified host)
	  (system-name))
628
	 ))
629
        (and (numberp field-result)
630
             (= alt-form 0)
631 632 633
             (string-equal field-width "")
             ;; no width provided; set width for default
             (setq field-width "02"))
634 635 636 637 638 639 640 641
	(let ((padded-result
	       (format (format "%%%s%c"
			       field-width
			       (if (numberp field-result) ?d ?s))
		       (or field-result ""))))
	  (let* ((initial-length (length padded-result))
		 (desired-length (if (string-equal field-width "")
				     initial-length
642
				   (string-to-number field-width))))
643
	    (if (> initial-length desired-length)
644
		;; truncate strings on right
645 646
		(if (stringp field-result)
		    (substring padded-result 0 desired-length)
647
                  padded-result)	;numbers don't truncate
648
	      padded-result))))
649 650 651 652 653
       (t
	(char-to-string cur-char)))))
      (setq ind (1+ ind)))
    result))

654
(defun time-stamp-do-number (format-char alt-form field-width time)
Dave Love's avatar
Dave Love committed
655 656 657
  "Handle compatible FORMAT-CHAR where only default width/padding will change.
ALT-FORM is whether `#' specified.  FIELD-WIDTH is the string
width specification or \"\".  TIME is the time to convert."
658
  (let ((format-string (concat "%" (char-to-string format-char))))
659
    (if (and (> alt-form 0) (not (string-equal field-width "")))
660
	""				;discourage "%:2d" and the like
661
      (string-to-number (time-stamp--format format-string time)))))
662 663

(defvar time-stamp-conversion-warn t
664 665
  "Warn about soon-to-be-unsupported forms in `time-stamp-format'.
If nil, these warnings are disabled, which would be a bad idea!
666 667 668
You really need to update your files instead.

The new formats will work with old versions of Emacs.
669 670
New formats are being recommended now to allow `time-stamp-format'
to change in the future to be compatible with `format-time-string'.
671 672 673 674
The new forms being recommended now will continue to work then.")


(defun time-stamp-conv-warn (old-form new-form)
675
  "Display a warning about a soon-to-be-obsolete format.
676
Suggests replacing OLD-FORM with NEW-FORM."
677 678
  (cond
   (time-stamp-conversion-warn
679
    (with-current-buffer (get-buffer-create "*Time-stamp-compatibility*")
680 681 682 683 684
      (goto-char (point-max))
      (if (bobp)
	  (progn
	    (insert
	     "The formats recognized in time-stamp-format will change in a future release\n"
685
	     "to be more compatible with the format-time-string function.\n\n"
686 687 688
	     "The following obsolescent time-stamp-format construct(s) were found:\n\n")))
      (insert "\"" old-form "\" -- use " new-form "\n"))
    (display-buffer "*Time-stamp-compatibility*"))))
689

Richard M. Stallman's avatar
Richard M. Stallman committed
690 691 692
(provide 'time-stamp)

;;; time-stamp.el ends here