;;
;; $Id: q-signature.el,v 1.5 1995/07/22 03:38:44 qjb Exp $
;; $Source: /home/qjb/elisp/q/RCS/q-signature.el,v $
;; $Author: qjb $
;;
;; Handle selection from among multiple email signatures.
;;
;; Set the variable q-signature-file the to the name of the file that
;; contains the signatures.  See documentation strings of functions here
;; for more details.
;;

(defvar q-signature-file (expand-file-name "~/login/email-signatures")
  "*File that contains email signatures")

(defvar q-signature-alist nil "*List of email signatures")

(defun q-parse-signature-file ()
  "Parse file containing email signatures.
The email signatures file is free format.  Signatures are enclosed in the
following types of blocks:

:Name:
This is the contents of the signature named `Name'
:End Name:

Any other text is ingored."
  (interactive)
  (let (
	(buf (get-buffer-create (concat (make-temp-name "*") "*")))
	(block-regexp "^:\\([^:]+\\):[ \t]*$")
	name
	sig-value
	end-regexp
	exp-start
	)
    (setq q-signature-alist nil)
    (save-excursion
      (set-buffer buf)
      (erase-buffer)
      (if (file-exists-p q-signature-file)
	  (progn
	    (insert-file-contents q-signature-file)
	    (while (re-search-forward block-regexp (point-max) t)
	      (setq name (buffer-substring (match-beginning 1) (match-end 1)))
	      (setq end-regexp (concat "^:End " name ":[ \t]*$"))
	      (setq exp-start (1+ (point)))
	      (if (re-search-forward end-regexp (point-max) t)
		  (progn
		    (save-excursion
		      (beginning-of-line 1)
		      (setq sig-value (buffer-substring exp-start (point)))
		      )
		    (setq q-signature-alist
			  (cons (list name sig-value) q-signature-alist)
			  )
		    )
		(error (concat "parse-signature-file: Can't find end of "
			       name " in " q-signature-file))
		)
	      )
	    )
	)
      (kill-buffer buf)
      )
    )
  )
  
(defun q-insert-signature (name)
  "Insert one of the signatures in q-signature-alist"
  (interactive (list (let ((completion-ignore-case t)
			   (prompt "Which email signature? "))
		       (and q-signature-alist
			   (completing-read prompt q-signature-alist nil t)
			   )
		       )
		     )
	       )
  (if name
      (let (result)
	(if (setq result (assoc name q-signature-alist))
	    (progn
	      (if (not (bolp))
		  (insert "\n\n")
		(if (not (save-excursion
			   (beginning-of-line 0)
			   (looking-at "^\\s-+$")))
		    (insert "\n")
		  )
		)
	      (insert "--\n")
	      (insert (car (cdr result)))
	      )
	  (error (concat "q-insert-signature: unknown signature " name))
	  )
	)
    (error "q-insert-signature: no known signatures")
    )
  )
