;; -*- Emacs-Lisp -*-
;; header.el
;; $Id: header.el,v 1.8 2020/02/11 23:04:46 yuuji Exp $
;; Last modified Wed Feb 12 08:03:21 2020 on firestorm
;; Update count: 46

;; [Installation]
;;
;; (autoload 'header-insert "header" "Put stamp in file header" t)
;; (add-hook 'write-file-hooks 'header-insert)
;;
;; [To enable file header stamping]
;;
;; Put the following prefix within 1000 bytes.
;;
;;	Last modified
;;	Update count

(defvar header-stamp-start (concat "Last " "modified" "\\|\\bdate:\\s(")
  "REGEXP after which time-stamp is written.")
(defvar header-stamp-end "$\\|\\s)\\|\\*/"
  "Delete between stamp-string-start and stamp-string-end")
(defvar header-stamp-need-by nil
  "*Non-nil puts the `by $USER' at the end of stamp string.")
(defvar header-stamp-function 'current-time-string
  "*Function to insert time-stamp string")
(defvar header-stamp-limit 1000
  "*Maximum point value to which header prefix searched.")

(defvar header-count-start (concat "Update " "count\\b")
  "REGEXP of update counts title")
(defvar header-count-end "\\($\\)\\|\\([0-9]+\\)\\|\\*/"
  "REGEXP of update counts header end")

(provide 'header)
(defun header-insert ()
  "Insert file name and modified time at the head of file."
  (interactive)
  (let ((header-starts
	 (concat "\\(" header-stamp-start "\\)\\|\\("
		 header-count-start "\\)")))
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward header-starts header-stamp-limit t)
	(cond
	 ((match-beginning 1)
	  (delete-region
	   (point)
	   (save-excursion (re-search-forward header-stamp-end nil t)
		  (match-beginning 0)))
	  (or (save-excursion (forward-char -1) (looking-at "\\s("))
	      (insert " "))
	  (insert (funcall header-stamp-function) " on "
		  (substring (system-name)
			     0
			     (string-match "\\."  (system-name)))
		  (if header-stamp-need-by
		      (concat " by " (user-login-name)) "")))
	 ((match-beginning 2)
	  (let ((beg (point)) (count 0))
	    (re-search-forward header-count-end nil t)
	    (if (match-beginning 2)
		(setq count
		      (1+
		       (string-to-number
			(buffer-substring
			 (match-beginning 2) (match-end 2))))))
	    (delete-region beg (point))
	    (insert (format ": %d" count)))))))
    ;; write-file-hooks must return nil if success.
    nil))


;; Local variables:
;; header-stamp-limit:	200
;; End: