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