;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) 1994 by William M. Perry (wmperry@spry.com)
;;;
;;; This file is not part of GNU Emacs, but the same permissions apply.
;;;
;;; GNU Emacs is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 2, or (at your option)
;;; any later version.
;;;
;;; GNU Emacs is distributed in the hope that it will be useful,
;;; 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
;;; along with GNU Emacs; see the file COPYING.  If not, write to
;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Experimental mailcap parsing stuff
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Data structures
;;; ---------------
;;; The mailcap structure is an assoc list of assoc lists.
;;; 1st assoc list is keyed on the major content-type
;;; 2nd assoc list is keyed on the minor content-type (which can be a regexp)
;;;
;;; Which looks like:
;;; -----------------
;;; (
;;;  ("application"
;;;   ("postscript" . <info>)
;;;  )
;;;  ("text"
;;;   ("plain" . <info>)
;;;  )
;;; )
;;;
;;; Where <info> is another assoc list of the various information
;;; related to the mailcap RFC.  This is keyed on the lowercase
;;; attribute name (viewer, test, etc).  This looks like:
;;; (("viewer" . viewerinfo)
;;;  ("test"   . testinfo)
;;;  ("xxxx"   . "string")
;;; )
;;;
;;; Where viewerinfo specifies how the content-type is viewed.  Can be
;;; a string, in which case it is run through a shell, with
;;; appropriate parameters, or a symbol, in which case the symbol is
;;; funcall'd, with the buffer as an argument.
;;;
;;; testinfo is a list of strings, or nil.  If nil, it means the
;;; viewer specified is always valid.  If it is a list of strings,
;;; these are used to determine whether a viewer passes the 'test' or
;;; not.
;;;
;;; The main interface to this code is:
;;;
;;; To set everything up:
;;;
;;;  (mm-parse-mailcaps [path])
;;;
;;;  Where PATH is a unix-style path specification (: separated list
;;;  of strings).  If PATH is nil, the environment variable MAILCAPS
;;;  will be consulted.  If there is no environment variable, then a
;;;  default list of paths is used.
;;;
;;; To retrieve the information:
;;;  (mm-mime-info st [nd] [request])
;;;
;;;  Where st and nd are positions in a buffer that contain the
;;;  content-type header information of a mail/news/whatever message.
;;;  st can optionally be a string that contains the content-type
;;;  information.
;;;
;;;  Third argument REQUEST specifies what information to return.  If
;;;  it is nil or the empty string, the viewer (second field of the
;;;  mailcap entry) will be returned.  If it is a string, then the
;;;  mailcap field corresponding to that string will be returned
;;;  (print, description, whatever).  If a number, then all the
;;;  information for this specific viewer is returned.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Variables, etc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst mm-version (let ((x "$Revision: 1.24 $"))
		       (string-match "Revision: \\([^ \\\t\\\n]+\\)" x)
		       (substring x (match-beginning 1) (match-end 1)))
  "Version # of MM package")

(defvar mm-parse-args-syntax-table
  (copy-syntax-table emacs-lisp-mode-syntax-table)
  "A syntax table for parsing sgml attributes")

(modify-syntax-entry ?' "\"" mm-parse-args-syntax-table)
(modify-syntax-entry ?` "\"" mm-parse-args-syntax-table)

(defvar mm-mime-data
  '(
    ("multipart"   . (
		      ("appledouble". (("viewer" . w3-save-binary-file)
				       ("type"   . "multipart/appledouble")))
		      ("digest"     . (("viewer" . w3-save-binary-file)
				       ("type"   . "multipart/digest")))
		      )
     )
    ("application" . (
		      ("x-gzip"     . (("viewer" . "gzip -dc %s")
				       ("type"   . "application/x-gzip")
				       ("copiousoutput")))
		      ("postscript" . (("viewer" . "ghostview %s")
				       ("type" . "application/postscript")
				       ("test" . (getenv "DISPLAY"))))
		      ("postscript" . (("viewer" . "ps2ascii %s")
				       ("type" . "application/postscript")
				       ("test" . (not (getenv "DISPLAY")))
				       ("copiousoutput")))
		      ("x-www-pem-reply" .
		       (("viewer" . (w3-decode-pgp/pem "pem"))
			("type" . "application/x-www-pem-reply")
			))
		      ("x-www-pgp-reply" .
		       (("viewer" . (w3-decode-pgp/pem "pgp"))
			("type" . "application/x-www-pgp-reply")))
		      ))
    ("audio"       . (
		      (".*" . (("viewer" . "showaudio")
			       ("type" . "audio/*")))
		      ))
    ("message"     . (
		      ))
    ("image"       . (
		      ("x-xwd" . (("viewer" . "xwud -in %s")
				  ("type" . "image/x-xwd")
				  ("compose" . "xwd -frame > %s")
				  ("test" . (getenv "DISPLAY"))))
		      (".*" . (("viewer" . "xv -perfect %s")
			       ("type" . "image/*")
			       ("test" . (getenv "DISPLAY"))))
		      ))
    ("text"        . (
		      ("plain" . (("viewer" . indented-text-mode)
				  ("needsterminal")
				  ("compose" . "gnuclient %s")
				  ("type"   . "text/plain")))
		      ("html"  . (("viewer" . w3-prepare-buffer)
				  ("type" . "text/html")))
		      ))
    ("video"       . (
		      ("mpeg" . (("viewer" . "mpeg_play %s")
				 ("type"   . "video/mpeg")
				 ("test" . (getenv "DISPLAY"))))
		      ))
    ("archive"     . (
		      ("tar"  . (("viewer" . tar-mode)
				 ("type" . "archive/tar")
				 ("test" . (fboundp 'tar-mode))))
		      ))
    )
  "*The mailcap structure is an assoc list of assoc lists.
1st assoc list is keyed on the major content-type
2nd assoc list is keyed on the minor content-type (which can be a regexp)

Which looks like:
-----------------
(
 (\"application\"
  (\"postscript\" . <info>)
 )
 (\"text\"
  (\"plain\" . <info>)
 )
)

Where <info> is another assoc list of the various information
related to the mailcap RFC.  This is keyed on the lowercase
attribute name (viewer, test, etc).  This looks like:
((\"viewer\" . viewerinfo)
 (\"test\"   . testinfo)
 (\"xxxx\"   . \"string\")
)

Where viewerinfo specifies how the content-type is viewed.  Can be
a string, in which case it is run through a shell, with
appropriate parameters, or a symbol, in which case the symbol is
funcall'd, with the buffer as an argument.

testinfo is a list of strings, or nil.  If nil, it means the
viewer specified is always valid.  If it is a list of strings,
these are used to determine whether a viewer passes the 'test' or
not.
")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The mailcap parser
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mm-in-assoc (elt list)
  "Check to see if ELT matches any of the regexps in the car elements of LIST"
  (let (rslt)
    (while (and list (not rslt))
      (and (car (car list))
	   (string-match (car (car list)) elt)
	   (setq rslt (car list)))
      (setq list (cdr list)))
    rslt))

(defun mm-replace-regexp (regexp to-string)
  "Quiet replace-regexp."
  (goto-char (point-min))
  (while (re-search-forward regexp nil t)
    (replace-match to-string t nil)))

(defun mm-parse-mailcaps (&optional path)
  "Parse out all the mailcaps specified in a unix-style path string PATH"
  (setq path
	(or path (getenv "MAILCAPS")
	    (concat "/etc/mailcap:/usr/etc/mailcap:/usr/local/etc/mailcap:"
		    (expand-file-name "~/.mailcap"))))
  (let ((fnames (mm-string-to-tokens path ?:)) fname)
    (while fnames
      (setq fname (car fnames))
      (if (and (file-exists-p fname) (file-readable-p fname))
	  (mm-parse-mailcap (car fnames)))
      (setq fnames (cdr fnames)))))

(defun mm-parse-mailcap (fname)
  "Parse out the mailcap file specified by FNAME"
  (let (major				; The major mime type (image/audio/etc)
	minor				; The minor mime type (gif, basic, etc)
	save-pos			; Misc saved positions used in parsing
	viewer				; How to view this mime type
	info				; Misc info about this mime type
	old-major			; Does the major area exist in the
					; mm-mime-data assoc list yet?
	)
    (save-excursion
      (set-buffer (get-buffer-create " *mailcap*"))
      (erase-buffer)
      (insert-file-contents fname)
      (set-syntax-table mm-parse-args-syntax-table)
      (mm-replace-regexp "#.*" "")	         ; Remove all comments
      (mm-replace-regexp "\\\n+" "\\\n")         ; And blank lines
      (mm-replace-regexp "\\\\[ \\\t\\\n]+" " ") ; And collapse spaces
      (mm-replace-regexp (concat (regexp-quote "\\") "[ \\\t]*\\\n") "")
      (goto-char (point-max))
      (skip-chars-backward " \\\t\\\n")
      (delete-region (point) (point-max))
      (goto-char (point-min))
      (while (not (eobp))
	(skip-chars-forward " \\\t\\\n")
	(setq save-pos (point)
	      info nil)
	(skip-chars-forward "^/;")
	(downcase-region save-pos (point))
	(setq major (buffer-substring save-pos (point)))
	(skip-chars-forward "/ \\\t\\\n")
	(setq save-pos (point))
	(skip-chars-forward "^;")
	(downcase-region save-pos (point))
	(setq minor
	      (cond
	       ((= ?* (or (char-after save-pos) 0)) ".*")
	       ((= (point) save-pos) ".*")
	       (t (buffer-substring save-pos (point)))))
	(skip-chars-forward "; \\\t\\\n")
	;;; Got the major/minor chunks, now for the viewers/etc
	;;; The first item _must_ be a viewer, according to the
	;;; RFC for mailcap files (#1343)
	(skip-chars-forward "; \\\t\\\n")
	(setq save-pos (point))
	(skip-chars-forward "^;\\\n")
	(if (= (or (char-after save-pos) 0) ?')
	    (setq viewer (progn
			   (narrow-to-region (1+ save-pos) (point))
			   (goto-char (point-min))
			   (prog1
			       (read (current-buffer))
			     (goto-char (point-max))
			     (widen))))
	  (setq viewer (buffer-substring save-pos (point))))
	(setq save-pos (point))
	(end-of-line)
	(setq info (nconc (list (cons "viewer" viewer)
				(cons "type" (concat major "/"
						     (if (string= minor ".*")
							 "*" minor))))
			  (mm-parse-mailcap-extras save-pos (point)))
	      old-major (assoc major mm-mime-data))
	(mm-mailcap-entry-passes-test info)
	(cond
	 ((null old-major)		; New major area
	  (setq mm-mime-data
		(cons (cons major (list (cons minor info)))
		      mm-mime-data)))
	 (t 
	  (setcdr old-major (cons (cons minor info) (cdr old-major)))))))))

(defun mm-parse-mailcap-extras (st nd)
  "Grab all the extra stuff from a mailcap entry"
  (let (
	name				; From name=
	value				; its value
	results				; Assoc list of results
	name-pos			; Start of XXXX= position
	val-pos				; Start of value position
	done				; Found end of \'d ;s?
	)
    (save-restriction
      (narrow-to-region st nd)
      (goto-char (point-min))
      (skip-chars-forward " \\\n\\\t;")
      (while (not (eobp))
	(setq done nil)
	(skip-chars-forward " \";\\\n\\\t")
	(setq name-pos (point))
	(skip-chars-forward "^ \\\n\\\t=")
	(downcase-region name-pos (point))
	(setq name (buffer-substring name-pos (point)))
	(skip-chars-forward " \\\t\\\n")
	(if (/= (or (char-after (point)) 0)  ?=) ; There is no value
	    (setq value nil)
	  (skip-chars-forward " \\\t\\\n=")
	  (setq val-pos (point))
	  (if (memq (char-after val-pos) '(?\" ?'))
	      (progn
		(forward-sexp 1)
		(setq val-pos (1+ val-pos))
		(backward-char 1))
	    (while (not done)
	      (skip-chars-forward "^;")
	      (if (= (or (char-after (1- (point))) 0) ?\\ )
		  (progn
		    (subst-char-in-region (1- (point)) (point) ?\\ ? )
		    (skip-chars-forward ";"))
		(setq done t))))
	  (setq	value (buffer-substring val-pos (point))))
	(setq results (cons (cons name value) results)))
      results)))  

(defun mm-string-to-tokens (str &optional delim)
  "Return a list of words from the string STR"
  (setq delim (or delim ? ))
  (let (results y)
    (mapcar
     (function
      (lambda (x)
	(cond
	 ((and (= x delim) y) (setq results (cons y results) y nil))
	 ((/= x delim) (setq y (concat y (char-to-string x))))
	 (t nil)))) str)
    (nreverse (cons y results))))

(defun mm-mailcap-entry-passes-test (info)
  "Return t iff a mailcap entry passes its test clause
or no test clause is present."
  (let (status				; Call-process-regions return value
	(test (assoc "test" info)); The test clause
	)
    (setq status (and test (mm-string-to-tokens (cdr test))))
    (if (and (assoc "needsx11" info) (not (getenv "DISPLAY")))
	(setq status nil)
      (cond
       ((and (equal (nth 0 status) "test")
	     (equal (nth 1 status) "-n")
	     (or (equal (nth 2 status) "$DISPLAY")
		 (equal (nth 2 status) "\"$DISPLAY\"")))
	(setq status (if (getenv "DISPLAY") t nil)))
       ((and (equal (nth 0 status) "test")
	     (equal (nth 1 status) "-z")
	     (or (equal (nth 2 status) "$DISPLAY")
		 (equal (nth 2 status) "\"$DISPLAY\"")))
	(setq status (if (getenv "DISPLAY") nil t)))
       (test nil)
       (t nil)))
    (and test (listp test) (setcdr test status))))

(defun mm-parse-args (st nd)
  "Return an assoc list of attribute/value pairs from an SGML-type string"
  (let (
	name				; From name=
	value				; its value
	results				; Assoc list of results
	name-pos			; Start of XXXX= position
	val-pos				; Start of value position
	)
    (save-restriction
      (narrow-to-region st nd)
      (goto-char (point-min))
      (while (not (eobp))
	(skip-chars-forward " \\\n\\\t")
	(setq name-pos (point))
	(skip-chars-forward "^ \\\n\\\t=")
	(downcase-region name-pos (point))
	(setq name (buffer-substring name-pos (point)))
	(skip-chars-forward " \\\t\\\n")
	(if (/= (or (char-after (point)) 0)  ?=) ; There is no value
	    (setq value nil)
	  (skip-chars-forward " \\\t\\\n=")
	  (setq val-pos (point)
		value
		(cond
		 ((or (= (or (char-after val-pos) 0) ?\")
		      (= (or (char-after val-pos) 0) ?'))
		  (buffer-substring (1+ val-pos)
				    (condition-case ()
					(prog2
					    (forward-sexp 1)
					    (1- (point))
					  (skip-chars-forward "\""))
				      (error
				       (skip-chars-forward "^ \\\t\\\n")
				       (point)))))
		 (t
		  (buffer-substring val-pos
				    (progn
				      (skip-chars-forward "^ \\\t\\\n")
				      (point)))))))
	(setq results (cons (cons name value) results)))
      results)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The action routines.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mm-possible-viewers (major minor)
  "Return a list of possible viewers from MAJOR for minor type MINOR"
  (let ((exact '())
	(wildcard '()))
    (while major
      (cond
       ((equal (car (car major)) minor)
	(setq exact (cons (cdr (car major)) exact)))
       ((string-match (car (car major)) minor)
	(setq wildcard (cons (cdr (car major)) wildcard))))
      (setq major (cdr major)))
    (nconc (nreverse exact) (nreverse wildcard))))

(defun mm-unescape-mime-test (test type-info)
  (let ((buff (get-buffer-create " *unescape*"))
	save-pos save-chr subst)
    (cond
     ((symbolp test) test)
     ((and (listp test) (symbolp (car test))) test)
     ((or (stringp test)
	  (and (listp test) (stringp (car test))
	       (setq test (mapconcat 'identity test " "))))
      (save-excursion
	(set-buffer buff)
	(erase-buffer)
	(insert test)
	(goto-char (point-min))
	(while (not (eobp))
	  (skip-chars-forward "^%")
	  (if (/= (skip-chars-backward "\\\\") 0) ; It is an escaped %
	      (progn
		(delete-char 1)
		(skip-chars-forward "%."))
	    (setq save-pos (point))
	    (skip-chars-forward "%")
	    (setq save-chr (char-after (point)))
	    (cond
	     ((null save-chr) nil)
	     ((= save-chr ?t)
	      (delete-region save-pos (progn (forward-char 1) (point)))
	      (insert (or (cdr (assoc "type" type-info)) "\"\"")))
	     ((= save-chr ?M)
	      (delete-region save-pos (progn (forward-char 1) (point)))
	      (insert "\"\""))
	     ((= save-chr ?n)
	      (delete-region save-pos (progn (forward-char 1) (point)))
	      (insert "\"\""))
	     ((= save-chr ?F)
	      (delete-region save-pos (progn (forward-char 1) (point)))
	      (insert "\"\""))
	     ((= save-chr ?{)
	      (forward-char 1)
	      (skip-chars-forward "^}")
	      (downcase-region (+ 2 save-pos) (point))
	      (setq subst (buffer-substring (+ 2 save-pos) (point)))
	      (delete-region save-pos (1+ (point)))
	      (insert (or (cdr (assoc subst type-info)) "\"\"")))
	     (t nil))))
	(buffer-string)))
     (t (error "Bad value to mm-unescape-mime-test. %S" test)))))

(defun mm-viewer-passes-test (viewer-info type-info)
  "Return non-nil iff the viewer specified by VIEWER-INFO passes its
test clause (if any)."
  (let* ((test-info   (assoc "test"   viewer-info))
	 (test (cdr test-info))
	 (viewer (cdr (assoc "viewer" viewer-info)))
	 status
	 parsed-test
	)
    (cond
     ((not test-info) t)		; No test clause
     ((not test) nil)			; Already failed test
     ((eq test t) t)			; Already passed test
     ((and (symbolp test)		; Lisp function as test
	   (fboundp test))
      (funcall test type-info))
     ((and (symbolp test)		; Lisp variable as test
	   (boundp test))
      (symbol-value test))
     ((and (listp test)			; List to be eval'd
	   (symbolp (car test)))
      (eval test))
     (t
      (setq test (mm-unescape-mime-test test type-info))
      (if (string-match "[ \\\t]" test)
	  (setq test (list (substring test 0 (match-beginning 0))
			   nil nil nil
			   (substring test (match-end 0) nil)))
	(setq test (list test nil nil nil)))
      (setq status (apply 'call-process test))
      (= 0 status)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The main whabbo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mm-mime-info (st &optional nd request)
  "Get the mime viewer command for HEADERLINE, return nil if none found.
Expects a complete content-type header line as its argument.  This can
be simple like text/html, or complex like text/plain; charset=blah; foo=bar

Third argument REQUEST specifies what information to return.  If it is
nil or the empty string, the viewer (second field of the mailcap
entry) will be returned.  If it is a string, then the mailcap field
corresponding to that string will be returned (print, description,
whatever).  If a number, then all the information for this specific
viewer is returned.
"
  (let (
	major				; Major encoding (text, etc)
	minor				; Minor encoding (html, etc)
	info				; Other info
	save-pos			; Misc. position during parse
	major-info			; (assoc major mm-mime-data)
	minor-info			; (assoc minor major-info)
	test				; current test proc.
	viewers				; Possible viewers
	passed				; Viewers that passed the test
	viewer				; The one and only viewer
	)
    (save-excursion
      (cond
       ((null st)
	(set-buffer (get-buffer-create " *mimeparse*"))
	(erase-buffer)
	(insert "text/plain")
	(setq st (point-min)))
       ((stringp st)
	(set-buffer (get-buffer-create " *mimeparse*"))
	(erase-buffer)
	(insert st)
	(setq st (point-min)))
       ((null nd)
	(narrow-to-region st (progn (goto-char st) (end-of-line) (point))))
       (t (narrow-to-region st nd)))
      (goto-char st)
      (skip-chars-forward ": \\\t\\\n")
      (buffer-enable-undo)
      (setq viewer
	    (catch 'mm-exit
	      (setq save-pos (point))
	      (skip-chars-forward "^/")
	      (downcase-region save-pos (point))
	      (setq major (buffer-substring save-pos (point)))
	      (if (not (setq major-info (cdr (assoc major mm-mime-data))))
		  (throw 'mm-exit nil))
	      (skip-chars-forward "/ \\\t\\\n")
	      (setq save-pos (point))
	      (skip-chars-forward "^ \\\t\\\n;")
	      (downcase-region save-pos (point))
	      (setq minor (buffer-substring save-pos (point)))
	      (if (not
		   (setq viewers (mm-possible-viewers major-info minor)))
		  (throw 'mm-exit nil))
	      (skip-chars-forward "; \\\t")
	      (if (eolp)
		  nil				; No qualifiers
		(setq save-pos (point))
		(end-of-line)
		(subst-char-in-region save-pos (point) ?\; ? )
		(setq info (mm-parse-args save-pos (point)))
		(condition-case ()
		    (undo)			; Put the ;s back in
		  (error nil))
		)
	      (while viewers
		(if (mm-viewer-passes-test (car viewers) info)
		    (progn
		      (setq passed (list (car viewers))
			    viewers (cdr viewers))
		      (while viewers
			(if (and
			     (not
			      (stringp (cdr (assoc "viewer" (car viewers)))))
			     (mm-viewer-passes-test (car viewers) info))
			    (setq passed (cons (car viewers) passed)))
			(setq viewers (cdr viewers)))
		      (setq viewers passed
			    passed (cdr (nreverse passed)))
		      (throw 'mm-exit (car viewers))))
		(setq viewers (cdr viewers)))))
      (if (and (stringp (cdr (assoc "viewer" viewer)))
	       passed)
	  (setq viewer (car passed)))
      (widen)
      (cond
       ((and (null viewer) (not (equal major "default")))
	(mm-mime-info "default" nil request))
       ((or (null request) (equal request ""))
	(mm-unescape-mime-test (cdr (assoc "viewer" viewer)) viewer))
       ((stringp request) (mm-unescape-mime-test
			   (cdr (assoc (downcase request) viewer)) viewer))
       (t viewer)))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Experimental MIME-types parsing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar mm-mime-extensions
  '(
    (""          . "text/plain")
    (".ai"       . "application/postscript")
    (".aif"      . "audio/aiff")
    (".aifc"     . "audio/aiff")
    (".aiff"     . "audio/aiff")
    (".au"       . "audio/ulaw")
    (".avi"      . "video/x-msvideo")
    (".bcpio"    . "application/x-bcpio")
    (".bin"      . "application/octet-stream")
    (".cpio"     . "application/x-cpio")
    (".csh"      . "application/x-csh")
    (".dvi"      . "application/x-dvi")
    (".el"       . "application/emacs-lisp")
    (".eps"      . "application/postscript")
    (".etx"      . "text/x-setext")
    (".fax"      . "image/x-fax")
    (".gif"      . "image/gif")
    (".hdf"      . "application/x-hdf")
    (".hqx"      . "application/mac-binhex40")
    (".htm"      . "text/html")
    (".html"     . "text/html")
    (".icon"     . "image/x-icon")
    (".ief"      . "image/ief")
    (".jpe"      . "image/jpeg")
    (".jpeg"     . "image/jpeg")
    (".jpg"      . "image/jpeg")
    (".macp"     . "image/x-macpaint")
    (".man"      . "application/x-troff-man")
    (".me"       . "application/x-troff-me")
    (".mov"      . "video/quicktime")
    (".mov"      . "video/quicktime")
    (".movie"    . "video/x-sgi-movie")
    (".mpeg"     . "video/mpeg")
    (".mpg"      . "video/mpeg")
    (".ms"       . "application/x-troff-ms")
    (".nc"       . "application/x-netcdf")
    (".oda"      . "application/oda")
    (".pbm"      . "image/x-portable-bitmap")
    (".pdf"      . "application/pdf")
    (".pgm"      . "image/portable-graymap")
    (".pict"     . "image/pict")
    (".pnm"      . "image/x-portable-anymap")
    (".ppm"      . "image/portable-pixmap")
    (".ps"       . "application/postscript")
    (".qt"       . "video/quicktime")
    (".ras"      . "image/x-raster")
    (".rgb"      . "image/x-rgb")
    (".rtf"      . "application/rtf")
    (".rtx"      . "text/richtext")
    (".sh"       . "application/x-sh")
    (".snd"      . "audio/basic")
    (".src"      . "application/x-wais-source")
    (".tar"      . "archive/tar")
    (".tcl"      . "application/x-tcl")
    (".tex"      . "application/tex")
    (".texi"     . "application/texinfo")
    (".tga"      . "image/x-targa")
    (".tif"      . "image/tiff")
    (".tiff"     . "image/tiff")
    (".tr"       . "application/x-troff")
    (".troff"    . "application/x-troff")
    (".tsv"      . "text/tab-separated-values")
    (".txt"      . "text/plain")
    (".wav"      . "audio/x-wav")
    (".xbm"      . "image/xbm")
    (".xpm"      . "image/x-pixmap")
    (".xwd"      . "image/windowdump")
    (".zip"      . "application/zip")
    )
  "*An assoc list of file extensions and the MIME content-types they
correspond to")

(defun mm-parse-mimetypes (&optional path)
  "Parse out all the mimetypes specified in a unix-style path string PATH"
  (setq path
	(or path (getenv "MIMETYPES")
	    (concat (expand-file-name "~/.mime-types") ":"
		    "/etc/mime-types:/usr/etc/mime-types:"
		    "/usr/local/etc/mime-types:"
		    "/usr/local/www/conf/mime-types")))
  (let ((fnames (mm-string-to-tokens path ?:)) fname)
    (while fnames
      (setq fname (car fnames))
      (if (and (file-exists-p fname) (file-readable-p fname))
	  (mm-parse-mimetype-file (car fnames)))
      (setq fnames (cdr fnames)))))

(defun mm-parse-mimetype-file (fname)
  "Parse out a mime-types file"
  (let (type				; The MIME type for this line
	extns				; The extensions for this line
	save-pos			; Misc. saved buffer positions
	)
    (save-excursion
      (set-buffer (get-buffer-create " *mime-types*"))
      (erase-buffer)
      (insert-file-contents fname)
      (mm-replace-regexp "#.*" "")
      (mm-replace-regexp "\\\n+" "\n")
      (mm-replace-regexp "[ \\\t]+$" "")
      (goto-char (point-max))
      (skip-chars-backward " \\\t\\\n")
      (delete-region (point) (point-max))
      (goto-char (point-min))
      (while (not (eobp))
	(skip-chars-forward " \\\t\\\n")
	(setq save-pos (point))
	(skip-chars-forward "^ \\\t")
	(downcase-region save-pos (point))
	(setq type (buffer-substring save-pos (point)))
	(while (not (eolp))
	  (skip-chars-forward " \\\t")
	  (setq save-pos (point))
	  (skip-chars-forward "^ \\\t\\\n")
	  (setq extns (cons (buffer-substring save-pos (point)) extns)))
	(while extns
	  (setq mm-mime-extensions
		(cons
		 (cons (if (= (string-to-char (car extns)) ?.)
			   (car extns)
			 (concat "." (car extns))) type) mm-mime-extensions)
		extns (cdr extns)))))))

(defun mm-extension-to-mime (extn)
  "Return the MIME content type of the file extensions EXTN"
  (if (and (stringp extn)
	   (not (= (string-to-char extn) ?.)))
      (setq extn (concat "." extn)))
  (cdr (assoc (downcase extn) mm-mime-extensions)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Editing/Composition of body parts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mm-compose-type (type)
  "Compose a body section of MIME-type TYPE."
  (let* ((info (mm-mime-info type nil 5))
	 (fnam (w3-generate-unique-filename))
	 (comp (or (cdr (assoc "compose" info))))
	 (ctyp (cdr (assoc "composetyped" info)))
	 (buff (get-buffer-create " *mimecompose*"))
	 (typeit (not ctyp))
	 (retval "")
	 (usef nil))
    (setq comp (mm-unescape-mime-test (or comp ctyp) info))
    (while (string-match "\\([^\\\\]\\)%s" comp)
      (setq comp (concat (substring comp 0 (match-end 1)) fnam
			 (substring comp (match-end 0) nil))
	    usef t))
    (call-process (or (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
		  nil (if usef nil buff) nil "-c" comp)
    (setq retval
	  (concat
	   (if typeit (concat "Content-type: " type "\r\n\r\n") "")
	   (if usef
	       (save-excursion
		 (set-buffer buff)
		 (erase-buffer)
		 (insert-file-contents fnam)
		 (buffer-string))
	     (save-excursion
	       (set-buffer buff)
	       (buffer-string)))
	   "\r\n"))
    retval))	

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Miscellaneous MIME viewers written in elisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;; multipart/alternative -> Show display of choices
;;; multipart/mixed       -> Break chunks into cached file area
;;; multipart/digest
;;; multipart/parallel
;;; multipart/appledoble
;;; multipart/header-set
;;; message/rfc822
;;; message/partial
;;; message/external-body
;;; message/news
;;; application/octet-stream -> save to disk
;;; application/rtf
;;; application/mac-binhex40
;;; text/richtext         -> convert to HTML
;;; 


(provide 'mm)
