f5d327c80215a238f6efbebbee780812a89006aa
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- Functions for displaying MIME parts
2 ;; Copyright (C) 1998,99 Free Software Foundation, Inc.
3
4 ;; Author: William M. Perry <wmperry@aventail.com>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30 (require 'mail-parse)
31
32 (defvar mailcap-parse-args-syntax-table
33   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
34     (modify-syntax-entry ?' "\"" table)
35     (modify-syntax-entry ?` "\"" table)
36     (modify-syntax-entry ?{ "(" table)
37     (modify-syntax-entry ?} ")" table)
38     table)
39   "A syntax table for parsing sgml attributes.")
40
41 (defvar mailcap-mime-data
42   '(("application"
43      ("x-x509-ca-cert"
44       (viewer . ssl-view-site-cert)
45       (test . (fboundp 'ssl-view-site-cert))
46       (type . "application/x-x509-ca-cert"))
47      ("x-x509-user-cert"
48       (viewer . ssl-view-user-cert)
49       (test . (fboundp 'ssl-view-user-cert))
50       (type . "application/x-x509-user-cert"))
51      ("octet-stream"
52       (viewer . mailcap-save-binary-file)
53       (non-viewer . t)
54       (type ."application/octet-stream"))
55      ("dvi"
56       (viewer . "open %s")
57       (type   . "application/dvi")
58       (test   . (eq (mm-device-type) 'ns)))
59      ("dvi"
60       (viewer . "xdvi %s")
61       (test   . (eq (mm-device-type) 'x))
62       ("needsx11")
63       (type   . "application/dvi"))
64      ("dvi"
65       (viewer . "dvitty %s")
66       (test   . (not (getenv "DISPLAY")))
67       (type   . "application/dvi"))
68      ("emacs-lisp"
69       (viewer . mailcap-maybe-eval)
70       (type   . "application/emacs-lisp"))
71      ("x-tar"
72       (viewer . mailcap-save-binary-file)
73       (non-viewer . t)
74       (type   . "application/x-tar"))
75      ("x-latex"
76       (viewer . tex-mode)
77       (test   . (fboundp 'tex-mode))
78       (type   . "application/x-latex"))
79      ("x-tex"
80       (viewer . tex-mode)
81       (test   . (fboundp 'tex-mode))
82       (type   . "application/x-tex"))
83      ("latex"
84       (viewer . tex-mode)
85       (test   . (fboundp 'tex-mode))
86       (type   . "application/latex"))
87      ("tex"
88       (viewer . tex-mode)
89       (test   . (fboundp 'tex-mode))
90       (type   . "application/tex"))
91      ("texinfo"
92       (viewer . texinfo-mode)
93       (test   . (fboundp 'texinfo-mode))
94       (type   . "application/tex"))
95      ("zip"
96       (viewer . mailcap-save-binary-file)
97       (non-viewer . t)
98       (type   . "application/zip")
99       ("copiousoutput"))
100      ("pdf"
101       (viewer . "acroread %s")
102       (type   . "application/pdf"))
103      ("postscript"
104       (viewer . "open %s")
105       (type   . "application/postscript")
106       (test   . (eq (mm-device-type) 'ns)))
107      ("postscript"
108       (viewer . "ghostview -dSAFER %s")
109       (type . "application/postscript")
110       (test   . (eq (mm-device-type) 'x))
111       ("needsx11"))
112      ("postscript"
113       (viewer . "ps2ascii %s")
114       (type . "application/postscript")
115       (test . (not (getenv "DISPLAY")))
116       ("copiousoutput")))
117     ("audio"
118      ("x-mpeg"
119       (viewer . "maplay %s")
120       (type   . "audio/x-mpeg"))
121      (".*"
122       (viewer . mailcap-save-binary-file)
123       (non-viewer . t)
124       (test   . (or (featurep 'nas-sound)
125                       (featurep 'native-sound)))
126       (type   . "audio/*"))
127      (".*"
128       (viewer . "showaudio")
129       (type   . "audio/*")))
130     ("message"
131      ("rfc-*822"
132       (viewer . mm-view-message)
133       (test   . (and (featurep 'gnus)
134                      (gnus-alive-p)))
135       (type   . "message/rfc822"))
136      ("rfc-*822"
137       (viewer . vm-mode)
138       (test   . (fboundp 'vm-mode))
139       (type   . "message/rfc822"))
140      ("rfc-*822"
141       (viewer . w3-mode)
142       (test   . (fboundp 'w3-mode))
143       (type   . "message/rfc822"))
144      ("rfc-*822"
145       (viewer . view-mode)
146       (test   . (fboundp 'view-mode))
147       (type   . "message/rfc822"))
148      ("rfc-*822"
149       (viewer . fundamental-mode)
150       (type   . "message/rfc822")))
151     ("image"
152      ("x-xwd"
153       (viewer  . "xwud -in %s")
154       (type    . "image/x-xwd")
155       ("compose" . "xwd -frame > %s")
156       (test    . (eq (mm-device-type) 'x))
157       ("needsx11"))
158      ("x11-dump"
159       (viewer . "xwud -in %s")
160       (type . "image/x-xwd")
161       ("compose" . "xwd -frame > %s")
162       (test   . (eq (mm-device-type) 'x))
163       ("needsx11"))
164      ("windowdump"
165       (viewer . "xwud -in %s")
166       (type . "image/x-xwd")
167       ("compose" . "xwd -frame > %s")
168       (test   . (eq (mm-device-type) 'x))
169       ("needsx11"))
170      (".*"
171       (viewer . "aopen %s")
172       (type   . "image/*")
173       (test   . (eq (mm-device-type) 'ns)))
174      (".*"
175       (viewer . "display %s")
176       (type . "image/*")
177       (test   . (eq (mm-device-type) 'x))
178       ("needsx11"))
179      (".*"
180       (viewer . "ee %s")
181       (type . "image/*")
182       (test   . (eq (mm-device-type) 'x))
183       ("needsx11")))
184     ("text"
185      ("plain"
186       (viewer  . w3-mode)
187       (test    . (fboundp 'w3-mode))
188       (type    . "text/plain"))
189      ("plain"
190       (viewer  . view-mode)
191       (test    . (fboundp 'view-mode))
192       (type    . "text/plain"))
193      ("plain"
194       (viewer  . fundamental-mode)
195       (type    . "text/plain"))
196      ("enriched"
197       (viewer . enriched-decode-region)
198       (test   . (fboundp 'enriched-decode))
199       (type   . "text/enriched"))
200      ("html"
201       (viewer . mm-w3-prepare-buffer)
202       (test   . (fboundp 'w3-prepare-buffer))
203       (type   . "text/html")))
204     ("video"
205      ("mpeg"
206       (viewer . "mpeg_play %s")
207       (type   . "video/mpeg")
208       (test   . (eq (mm-device-type) 'x))
209       ("needsx11")))
210     ("x-world"
211      ("x-vrml"
212       (viewer  . "webspace -remote %s -URL %u")
213       (type    . "x-world/x-vrml")
214       ("description"
215        "VRML document")))
216     ("archive"
217      ("tar"
218       (viewer . tar-mode)
219       (type . "archive/tar")
220       (test . (fboundp 'tar-mode)))))
221      "The mailcap structure is an assoc list of assoc lists.
222 1st assoc list is keyed on the major content-type
223 2nd assoc list is keyed on the minor content-type (which can be a regexp)
224
225 Which looks like:
226 -----------------
227  ((\"application\"
228    (\"postscript\" . <info>))
229   (\"text\"
230    (\"plain\" . <info>)))
231
232 Where <info> is another assoc list of the various information
233 related to the mailcap RFC.  This is keyed on the lowercase
234 attribute name (viewer, test, etc).  This looks like:
235  ((viewer . viewerinfo)
236   (test   . testinfo)
237   (xxxx   . \"string\"))
238
239 Where viewerinfo specifies how the content-type is viewed.  Can be
240 a string, in which case it is run through a shell, with
241 appropriate parameters, or a symbol, in which case the symbol is
242 funcall'd, with the buffer as an argument.
243
244 testinfo is a list of strings, or nil.  If nil, it means the
245 viewer specified is always valid.  If it is a list of strings,
246 these are used to determine whether a viewer passes the 'test' or
247 not.")
248
249 (defvar mailcap-download-directory nil
250   "*Where downloaded files should go by default.")
251
252 (defvar mailcap-temporary-directory
253   (cond ((fboundp 'temp-directory) (temp-directory))
254         ((boundp 'temporary-file-directory) temporary-file-directory)
255         ("/tmp/"))
256   "*Where temporary files go.")
257
258 ;;;
259 ;;; Utility functions
260 ;;;
261
262 (defun mailcap-generate-unique-filename (&optional fmt)
263   "Generate a unique filename in mailcap-temporary-directory"
264   (if (not fmt)
265       (let ((base (format "mailcap-tmp.%d" (user-real-uid)))
266             (fname "")
267             (x 0))
268         (setq fname (format "%s%d" base x))
269         (while (file-exists-p
270                 (expand-file-name fname mailcap-temporary-directory))
271           (setq x (1+ x)
272                 fname (concat base (int-to-string x))))
273         (expand-file-name fname mailcap-temporary-directory))
274     (let ((base (concat "mm" (int-to-string (user-real-uid))))
275           (fname "")
276           (x 0))
277       (setq fname (format fmt (concat base (int-to-string x))))
278       (while (file-exists-p
279               (expand-file-name fname mailcap-temporary-directory))
280         (setq x (1+ x)
281               fname (format fmt (concat base (int-to-string x)))))
282       (expand-file-name fname mailcap-temporary-directory))))
283
284 (defun mailcap-save-binary-file ()
285   (goto-char (point-min))
286   (unwind-protect
287       (let ((file (read-file-name
288                    "Filename to save as: "
289                    (or mailcap-download-directory "~/")))
290             (require-final-newline nil))
291         (write-region (point-min) (point-max) file))
292     (kill-buffer (current-buffer))))
293
294 (defun mailcap-maybe-eval ()
295   "Maybe evaluate a buffer of emacs lisp code"
296   (if (yes-or-no-p "This is emacs-lisp code, evaluate it? ")
297       (eval-buffer (current-buffer))
298     (emacs-lisp-mode)))
299
300 ;;;
301 ;;; The mailcap parser
302 ;;;
303
304 (defun mailcap-replace-regexp (regexp to-string)
305   ;; Quiet replace-regexp.
306   (goto-char (point-min))
307   (while (re-search-forward regexp nil t)
308     (replace-match to-string t nil)))
309
310 (defvar mailcap-parsed-p nil)
311
312 (defun mailcap-parse-mailcaps (&optional path force)
313   "Parse out all the mailcaps specified in a unix-style path string PATH.
314 If FORCE, re-parse even if already parsed."
315   (interactive (list nil t))
316   (when (or (not mailcap-parsed-p)
317             force)
318     (cond
319      (path nil)
320      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
321      ((memq system-type '(ms-dos ms-windows windows-nt))
322       (setq path (mapconcat 'expand-file-name
323                             '("~/mail.cap" "~/etc/mail.cap" "~/.mailcap")
324                             ";")))
325      (t (setq path (mapconcat 'expand-file-name
326                               '("~/.mailcap"
327                                 "/etc/mailcap:/usr/etc/mailcap"
328                                 "/usr/local/etc/mailcap") ":"))))
329     (let ((fnames (reverse
330                    (split-string
331                     path (if (memq system-type
332                                    '(ms-dos ms-windows windows-nt))
333                              ";"
334                            ":"))))
335           fname)
336       (while fnames
337         (setq fname (car fnames))
338        (if (and (file-exists-p fname) (file-readable-p fname)
339                 (file-regular-p fname))
340             (mailcap-parse-mailcap (car fnames)))
341         (setq fnames (cdr fnames))))
342     (setq mailcap-parsed-p t)))
343
344 (defun mailcap-parse-mailcap (fname)
345   ;; Parse out the mailcap file specified by FNAME
346   (let (major                           ; The major mime type (image/audio/etc)
347         minor                           ; The minor mime type (gif, basic, etc)
348         save-pos                        ; Misc saved positions used in parsing
349         viewer                          ; How to view this mime type
350         info                            ; Misc info about this mime type
351         )
352     (with-temp-buffer
353       (insert-file-contents fname)
354       (set-syntax-table mailcap-parse-args-syntax-table)
355       (mailcap-replace-regexp "#.*" "") ; Remove all comments
356       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
357       (mailcap-replace-regexp "\\\\[ \t\n]+" " ") ; And collapse spaces
358       (mailcap-replace-regexp (concat (regexp-quote "\\") "[ \t]*\n") "")
359       (goto-char (point-max))
360       (skip-chars-backward " \t\n")
361       (delete-region (point) (point-max))
362       (goto-char (point-min))
363       (while (not (eobp))
364         (skip-chars-forward " \t\n")
365         (setq save-pos (point)
366               info nil)
367         (skip-chars-forward "^/; \t\n")
368         (downcase-region save-pos (point))
369         (setq major (buffer-substring save-pos (point)))
370         (skip-chars-forward " \t\n")
371         (setq minor "")
372         (when (eq (char-after) ?/)
373           (forward-char)
374           (skip-chars-forward " \t\n")
375           (setq save-pos (point))
376           (skip-chars-forward "^; \t\n")
377           (downcase-region save-pos (point))
378           (setq minor
379                 (cond
380                  ((eq ?* (or (char-after save-pos) 0)) ".*")
381                  ((= (point) save-pos) ".*")
382                  (t (regexp-quote (buffer-substring save-pos (point)))))))
383         (skip-chars-forward " \t\n")
384         ;;; Got the major/minor chunks, now for the viewers/etc
385         ;;; The first item _must_ be a viewer, according to the
386         ;;; RFC for mailcap files (#1343)
387         (setq viewer "")
388         (when (eq (char-after) ?\;) 
389           (forward-char)
390           (skip-chars-forward " \t\n")
391           (setq save-pos (point))
392           (skip-chars-forward "^;\n")
393           ;; skip \;
394           (while (eq (char-before) ?\\)
395             (backward-delete-char 1)
396             (forward-char)
397             (skip-chars-forward "^;\n"))
398           (if (eq (or (char-after save-pos) 0) ?')
399               (setq viewer (progn
400                              (narrow-to-region (1+ save-pos) (point))
401                              (goto-char (point-min))
402                              (prog1
403                                  (read (current-buffer))
404                                (goto-char (point-max))
405                                (widen))))
406             (setq viewer (buffer-substring save-pos (point)))))
407         (setq save-pos (point))
408         (end-of-line)
409         (unless (equal viewer "") 
410           (setq info (nconc (list (cons 'viewer viewer)
411                                   (cons 'type (concat major "/"
412                                                       (if (string= minor ".*")
413                                                           "*" minor))))
414                             (mailcap-parse-mailcap-extras save-pos (point))))
415           (mailcap-mailcap-entry-passes-test info)
416           (mailcap-add-mailcap-entry major minor info))))))
417
418 (defun mailcap-parse-mailcap-extras (st nd)
419   ;; Grab all the extra stuff from a mailcap entry
420   (let (
421         name                            ; From name=
422         value                           ; its value
423         results                         ; Assoc list of results
424         name-pos                        ; Start of XXXX= position
425         val-pos                         ; Start of value position
426         done                            ; Found end of \'d ;s?
427         )
428     (save-restriction
429       (narrow-to-region st nd)
430       (goto-char (point-min))
431       (skip-chars-forward " \n\t;")
432       (while (not (eobp))
433         (setq done nil)
434         (setq name-pos (point))
435         (skip-chars-forward "^ \n\t=;")
436         (downcase-region name-pos (point))
437         (setq name (buffer-substring name-pos (point)))
438         (skip-chars-forward " \t\n")
439         (if (not (eq (char-after (point)) ?=)) ; There is no value
440             (setq value t)
441           (skip-chars-forward " \t\n=")
442           (setq val-pos (point))
443           (if (memq (char-after val-pos) '(?\" ?'))
444               (progn
445                 (setq val-pos (1+ val-pos))
446                 (condition-case nil
447                     (progn
448                       (forward-sexp 1)
449                       (backward-char 1))
450                   (error (goto-char (point-max)))))
451             (while (not done)
452               (skip-chars-forward "^;")
453               (if (eq (char-after (1- (point))) ?\\ )
454                   (progn
455                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
456                     (skip-chars-forward ";"))
457                 (setq done t))))
458           (setq value (buffer-substring val-pos (point))))
459         (setq results (cons (cons name value) results))
460         (skip-chars-forward " \";\n\t"))
461       results)))
462
463 (defun mailcap-mailcap-entry-passes-test (info)
464   ;; Return t iff a mailcap entry passes its test clause or no test
465   ;; clause is present.
466   (let (status                          ; Call-process-regions return value
467         (test (assq 'test info))        ; The test clause
468         )
469     (setq status (and test (split-string (cdr test) " ")))
470     (if (and (or (assoc "needsterm" info)
471                  (assoc "needsterminal" info)
472                  (assoc "needsx11" info))
473              (not (getenv "DISPLAY")))
474         (setq status nil)
475       (cond
476        ((and (equal (nth 0 status) "test")
477              (equal (nth 1 status) "-n")
478              (or (equal (nth 2 status) "$DISPLAY")
479                  (equal (nth 2 status) "\"$DISPLAY\"")))
480         (setq status (if (getenv "DISPLAY") t nil)))
481        ((and (equal (nth 0 status) "test")
482              (equal (nth 1 status) "-z")
483              (or (equal (nth 2 status) "$DISPLAY")
484                  (equal (nth 2 status) "\"$DISPLAY\"")))
485         (setq status (if (getenv "DISPLAY") nil t)))
486        (test nil)
487        (t nil)))
488     (and test (listp test) (setcdr test status))))
489
490 ;;;
491 ;;; The action routines.
492 ;;;
493
494 (defun mailcap-possible-viewers (major minor)
495   ;; Return a list of possible viewers from MAJOR for minor type MINOR
496   (let ((exact '())
497         (wildcard '()))
498     (while major
499       (cond
500        ((equal (car (car major)) minor)
501         (setq exact (cons (cdr (car major)) exact)))
502        ((and minor (string-match (car (car major)) minor))
503         (setq wildcard (cons (cdr (car major)) wildcard))))
504       (setq major (cdr major)))
505     (nconc (nreverse exact) (nreverse wildcard))))
506
507 (defun mailcap-unescape-mime-test (test type-info)
508   (let (save-pos save-chr subst)
509     (cond
510      ((symbolp test) test)
511      ((and (listp test) (symbolp (car test))) test)
512      ((or (stringp test)
513           (and (listp test) (stringp (car test))
514                (setq test (mapconcat 'identity test " "))))
515       (with-temp-buffer
516         (insert test)
517         (goto-char (point-min))
518         (while (not (eobp))
519           (skip-chars-forward "^%")
520           (if (/= (- (point)
521                      (progn (skip-chars-backward "\\\\")
522                             (point)))
523                   0)                    ; It is an escaped %
524               (progn
525                 (delete-char 1)
526                 (skip-chars-forward "%."))
527             (setq save-pos (point))
528             (skip-chars-forward "%")
529             (setq save-chr (char-after (point)))
530             (cond
531              ((null save-chr) nil)
532              ((= save-chr ?t)
533               (delete-region save-pos (progn (forward-char 1) (point)))
534               (insert (or (cdr (assq 'type type-info)) "\"\"")))
535              ((= save-chr ?M)
536               (delete-region save-pos (progn (forward-char 1) (point)))
537               (insert "\"\""))
538              ((= save-chr ?n)
539               (delete-region save-pos (progn (forward-char 1) (point)))
540               (insert "\"\""))
541              ((= save-chr ?F)
542               (delete-region save-pos (progn (forward-char 1) (point)))
543               (insert "\"\""))
544              ((= save-chr ?{)
545               (forward-char 1)
546               (skip-chars-forward "^}")
547               (downcase-region (+ 2 save-pos) (point))
548               (setq subst (buffer-substring (+ 2 save-pos) (point)))
549               (delete-region save-pos (1+ (point)))
550               (insert (or (cdr (assoc subst type-info)) "\"\"")))
551              (t nil))))
552         (buffer-string)))
553      (t (error "Bad value to mailcap-unescape-mime-test. %s" test)))))
554
555 (defvar mailcap-viewer-test-cache nil)
556
557 (defun mailcap-viewer-passes-test (viewer-info type-info)
558   ;; Return non-nil iff the viewer specified by VIEWER-INFO passes its
559   ;; test clause (if any).
560   (let* ((test-info (assq 'test viewer-info))
561          (test (cdr test-info))
562          (otest test)
563          (viewer (cdr (assoc 'viewer viewer-info)))
564          (default-directory (expand-file-name "~/"))
565          status parsed-test cache result)
566     (if (setq cache (assoc test mailcap-viewer-test-cache))
567         (cadr cache)
568       (setq
569        result
570        (cond
571         ((not test-info) t)             ; No test clause
572         ((not test) nil)                ; Already failed test
573         ((eq test t) t)                 ; Already passed test
574         ((and (symbolp test)            ; Lisp function as test
575               (fboundp test))
576          (funcall test type-info))
577         ((and (symbolp test)            ; Lisp variable as test
578               (boundp test))
579          (symbol-value test))
580         ((and (listp test)              ; List to be eval'd
581               (symbolp (car test)))
582          (eval test))
583         (t
584          (setq test (mailcap-unescape-mime-test test type-info)
585                test (list shell-file-name nil nil nil
586                           shell-command-switch test)
587                status (apply 'call-process test))
588          (= 0 status))))
589       (push (list otest result) mailcap-viewer-test-cache)
590       result)))
591
592 (defun mailcap-add-mailcap-entry (major minor info)
593   (let ((old-major (assoc major mailcap-mime-data)))
594     (if (null old-major)                ; New major area
595         (setq mailcap-mime-data
596               (cons (cons major (list (cons minor info)))
597                     mailcap-mime-data))
598       (let ((cur-minor (assoc minor old-major)))
599         (cond
600          ((or (null cur-minor)          ; New minor area, or
601               (assq 'test info))        ; Has a test, insert at beginning
602           (setcdr old-major (cons (cons minor info) (cdr old-major))))
603          ((and (not (assq 'test info)) ; No test info, replace completely
604                (not (assq 'test cur-minor)))
605           (setcdr cur-minor info))
606          (t
607           (setcdr old-major (cons (cons minor info) (cdr old-major)))))))))
608
609 (defun mailcap-add (type viewer &optional test)
610   "Add VIEWER as a handler for TYPE.
611 If TEST is not given, it defaults to t."
612   (let ((tl (split-string type "/")))
613     (when (or (not (car tl))
614               (not (cadr tl)))
615       (error "%s is not a valid MIME type" type))
616     (mailcap-add-mailcap-entry
617      (car tl) (cadr tl)
618      `((viewer . ,viewer)
619        (test . ,(if test test t))
620        (type . ,type)))))
621
622 ;;;
623 ;;; The main whabbo
624 ;;;
625
626 (defun mailcap-viewer-lessp (x y)
627   ;; Return t iff viewer X is more desirable than viewer Y
628   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
629         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
630         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
631         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
632     (cond
633      ((and x-wild (not y-wild))
634       nil)
635      ((and (not x-wild) y-wild)
636       t)
637      ((and (not y-lisp) x-lisp)
638       t)
639      (t nil))))
640
641 (defun mailcap-mime-info (string &optional request)
642   "Get the MIME viewer command for STRING, return nil if none found.
643 Expects a complete content-type header line as its argument.
644
645 Second argument REQUEST specifies what information to return.  If it is
646 nil or the empty string, the viewer (second field of the mailcap
647 entry) will be returned.  If it is a string, then the mailcap field
648 corresponding to that string will be returned (print, description,
649 whatever).  If a number, then all the information for this specific
650 viewer is returned.  If `all', then all possible viewers for
651 this type is returned."
652   (let (
653         major                           ; Major encoding (text, etc)
654         minor                           ; Minor encoding (html, etc)
655         info                            ; Other info
656         save-pos                        ; Misc. position during parse
657         major-info                      ; (assoc major mailcap-mime-data)
658         minor-info                      ; (assoc minor major-info)
659         test                            ; current test proc.
660         viewers                         ; Possible viewers
661         passed                          ; Viewers that passed the test
662         viewer                          ; The one and only viewer
663         ctl)
664     (save-excursion
665       (setq ctl (mail-header-parse-content-type (or string "text/plain")))
666       (setq major (split-string (car ctl) "/"))
667       (setq minor (cadr major)
668             major (car major))
669       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
670         (when (setq viewers (mailcap-possible-viewers major-info minor))
671           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
672                                                (cdr a)))
673                              (cdr ctl)))
674           (while viewers
675             (if (mailcap-viewer-passes-test (car viewers) info)
676                 (setq passed (cons (car viewers) passed)))
677             (setq viewers (cdr viewers)))
678           (setq passed (sort (nreverse passed) 'mailcap-viewer-lessp))
679           (setq viewer (car passed))))
680       (when (and (stringp (cdr (assq 'viewer viewer)))
681                  passed)
682         (setq viewer (car passed)))
683       (cond
684        ((and (null viewer) (not (equal major "default")) request)
685         (mailcap-mime-info "default" request))
686        ((or (null request) (equal request ""))
687         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
688        ((stringp request)
689         (if (or (eq request 'test) (eq request 'viewer))
690             (mailcap-unescape-mime-test
691              (cdr-safe (assoc request viewer)) info)))
692        ((eq request 'all)
693         passed)
694        (t
695         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
696         (setq viewer (copy-sequence viewer))
697         (let ((view (assq 'viewer viewer))
698               (test (assq 'test viewer)))
699           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
700           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
701         viewer)))))
702
703 ;;;
704 ;;; Experimental MIME-types parsing
705 ;;;
706
707 (defvar mailcap-mime-extensions
708   '((""          . "text/plain")
709     (".abs"      . "audio/x-mpeg")
710     (".aif"      . "audio/aiff")
711     (".aifc"     . "audio/aiff")
712     (".aiff"     . "audio/aiff")
713     (".ano"      . "application/x-annotator")
714     (".au"       . "audio/ulaw")
715     (".avi"      . "video/x-msvideo")
716     (".bcpio"    . "application/x-bcpio")
717     (".bin"      . "application/octet-stream")
718     (".cdf"      . "application/x-netcdr")
719     (".cpio"     . "application/x-cpio")
720     (".csh"      . "application/x-csh")
721     (".dvi"      . "application/x-dvi")
722     (".el"       . "application/emacs-lisp")
723     (".eps"      . "application/postscript")
724     (".etx"      . "text/x-setext")
725     (".exe"      . "application/octet-stream")
726     (".fax"      . "image/x-fax")
727     (".gif"      . "image/gif")
728     (".hdf"      . "application/x-hdf")
729     (".hqx"      . "application/mac-binhex40")
730     (".htm"      . "text/html")
731     (".html"     . "text/html")
732     (".icon"     . "image/x-icon")
733     (".ief"      . "image/ief")
734     (".jpg"      . "image/jpeg")
735     (".macp"     . "image/x-macpaint")
736     (".man"      . "application/x-troff-man")
737     (".me"       . "application/x-troff-me")
738     (".mif"      . "application/mif")
739     (".mov"      . "video/quicktime")
740     (".movie"    . "video/x-sgi-movie")
741     (".mp2"      . "audio/x-mpeg")
742     (".mp3"      . "audio/x-mpeg")
743     (".mp2a"     . "audio/x-mpeg2")
744     (".mpa"      . "audio/x-mpeg")
745     (".mpa2"     . "audio/x-mpeg2")
746     (".mpe"      . "video/mpeg")
747     (".mpeg"     . "video/mpeg")
748     (".mpega"    . "audio/x-mpeg")
749     (".mpegv"    . "video/mpeg")
750     (".mpg"      . "video/mpeg")
751     (".mpv"      . "video/mpeg")
752     (".ms"       . "application/x-troff-ms")
753     (".nc"       . "application/x-netcdf")
754     (".nc"       . "application/x-netcdf")
755     (".oda"      . "application/oda")
756     (".patch"    . "text/x-patch")
757     (".pbm"      . "image/x-portable-bitmap")
758     (".pdf"      . "application/pdf")
759     (".pgm"      . "image/portable-graymap")
760     (".pict"     . "image/pict")
761     (".png"      . "image/png")
762     (".pnm"      . "image/x-portable-anymap")
763     (".ppm"      . "image/portable-pixmap")
764     (".ps"       . "application/postscript")
765     (".qt"       . "video/quicktime")
766     (".ras"      . "image/x-raster")
767     (".rgb"      . "image/x-rgb")
768     (".rtf"      . "application/rtf")
769     (".rtx"      . "text/richtext")
770     (".sh"       . "application/x-sh")
771     (".sit"      . "application/x-stuffit")
772     (".snd"      . "audio/basic")
773     (".src"      . "application/x-wais-source")
774     (".tar"      . "archive/tar")
775     (".tcl"      . "application/x-tcl")
776     (".tcl"      . "application/x-tcl")
777     (".tex"      . "application/x-tex")
778     (".texi"     . "application/texinfo")
779     (".tga"      . "image/x-targa")
780     (".tif"      . "image/tiff")
781     (".tiff"     . "image/tiff")
782     (".tr"       . "application/x-troff")
783     (".troff"    . "application/x-troff")
784     (".tsv"      . "text/tab-separated-values")
785     (".txt"      . "text/plain")
786     (".vbs"      . "video/mpeg")
787     (".vox"      . "audio/basic")
788     (".vrml"     . "x-world/x-vrml")
789     (".wav"      . "audio/x-wav")
790     (".wrl"      . "x-world/x-vrml")
791     (".xbm"      . "image/xbm")
792     (".xpm"      . "image/xpm")
793     (".xwd"      . "image/windowdump")
794     (".zip"      . "application/zip")
795     (".ai"       . "application/postscript")
796     (".jpe"      . "image/jpeg")
797     (".jpeg"     . "image/jpeg"))
798   "An assoc list of file extensions and corresponding MIME content-types.")
799
800 (defun mailcap-parse-mimetypes (&optional path)
801   ;; Parse out all the mimetypes specified in a unix-style path string PATH
802   (cond
803    (path nil)
804    ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
805    ((memq system-type '(ms-dos ms-windows windows-nt))
806     (setq path (mapconcat 'expand-file-name
807                           '("~/mime.typ" "~/etc/mime.typ") ";")))
808    (t (setq path (mapconcat 'expand-file-name
809                             '("~/.mime-types"
810                               "/etc/mime-types:/usr/etc/mime-types"
811                               "/usr/local/etc/mime-types"
812                               "/usr/local/www/conf/mime-types") ":"))))
813   (let ((fnames (reverse
814                  (split-string path
815                                (if (memq system-type
816                                          '(ms-dos ms-windows windows-nt))
817                                    ";" ":"))))
818         fname)
819     (while fnames
820       (setq fname (car fnames))
821       (if (and (file-exists-p fname) (file-readable-p fname))
822           (mailcap-parse-mimetype-file (car fnames)))
823       (setq fnames (cdr fnames)))))
824
825 (defun mailcap-parse-mimetype-file (fname)
826   ;; Parse out a mime-types file
827   (let (type                            ; The MIME type for this line
828         extns                           ; The extensions for this line
829         save-pos                        ; Misc. saved buffer positions
830         )
831     (with-temp-buffer
832       (insert-file-contents fname)
833       (mailcap-replace-regexp "#.*" "")
834       (mailcap-replace-regexp "\n+" "\n")
835       (mailcap-replace-regexp "[ \t]+$" "")
836       (goto-char (point-max))
837       (skip-chars-backward " \t\n")
838       (delete-region (point) (point-max))
839       (goto-char (point-min))
840       (while (not (eobp))
841         (skip-chars-forward " \t\n")
842         (setq save-pos (point))
843         (skip-chars-forward "^ \t")
844         (downcase-region save-pos (point))
845         (setq type (buffer-substring save-pos (point)))
846         (while (not (eolp))
847           (skip-chars-forward " \t")
848           (setq save-pos (point))
849           (skip-chars-forward "^ \t\n")
850           (setq extns (cons (buffer-substring save-pos (point)) extns)))
851         (while extns
852           (setq mailcap-mime-extensions
853                 (cons
854                  (cons (if (= (string-to-char (car extns)) ?.)
855                            (car extns)
856                          (concat "." (car extns))) type)
857                  mailcap-mime-extensions)
858                 extns (cdr extns)))))))
859
860 (defun mailcap-extension-to-mime (extn)
861   "Return the MIME content type of the file extensions EXTN."
862   (if (and (stringp extn)
863            (not (eq (string-to-char extn) ?.)))
864       (setq extn (concat "." extn)))
865   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
866
867 (defvar mailcap-binary-suffixes
868   (if (memq system-type '(ms-dos windows-nt))
869       '(".exe" ".com" ".bat" ".cmd" ".btm" "")
870     '("")))
871
872 (defun mailcap-command-p (command)
873   "Say whether COMMAND is in the exec path.
874 The path of COMMAND will be returned iff COMMAND is a command."
875   (let ((path (if (file-name-absolute-p command) '(nil) exec-path))
876         file dir)
877     (catch 'found
878       (while (setq dir (pop path))
879         (let ((suffixes mailcap-binary-suffixes))
880           (while suffixes
881             (when (and (file-executable-p
882                         (setq file (expand-file-name
883                                     (concat command (pop suffixes))
884                                     dir)))
885                        (not (file-directory-p file)))
886               (throw 'found file))))))))
887
888 (defun mailcap-mime-types ()
889   "Return a list of MIME media types."
890   (delete-duplicates (mapcar 'cdr mailcap-mime-extensions)))
891
892 (provide 'mailcap)
893
894 ;;; mailcap.el ends here