ab716953a8d516a24c0c64623247a9f61cbd0788
[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   (let ((file (read-file-name
276                "Filename to save as: "
277                (or mailcap-download-directory "~/")))
278         (require-final-newline nil))
279     (write-region (point-min) (point-max) file)
280     (kill-buffer (current-buffer))))
281
282 (defun mailcap-maybe-eval ()
283   "Maybe evaluate a buffer of emacs lisp code"
284   (if (yes-or-no-p "This is emacs-lisp code, evaluate it? ")
285       (eval-buffer (current-buffer))
286     (emacs-lisp-mode)))
287
288 ;;;
289 ;;; The mailcap parser
290 ;;;
291
292 (defun mailcap-replace-regexp (regexp to-string)
293   ;; Quiet replace-regexp.
294   (goto-char (point-min))
295   (while (re-search-forward regexp nil t)
296     (replace-match to-string t nil)))
297
298 (defvar mailcap-parsed-p nil)
299
300 (defun mailcap-parse-mailcaps (&optional path force)
301   "Parse out all the mailcaps specified in a unix-style path string PATH.
302 If FORCE, re-parse even if already parsed."
303   (interactive (list nil t))
304   (when (or (not mailcap-parsed-p)
305             force)
306     (cond
307      (path nil)
308      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
309      ((memq system-type '(ms-dos ms-windows windows-nt))
310       (setq path (mapconcat 'expand-file-name '("~/mail.cap" "~/etc/mail.cap")
311                             ";")))
312      (t (setq path (mapconcat 'expand-file-name
313                               '("~/.mailcap"
314                                 "/etc/mailcap:/usr/etc/mailcap"
315                                 "/usr/local/etc/mailcap") ":"))))
316     (let ((fnames (reverse
317                    (split-string
318                     path (if (memq system-type
319                                    '(ms-dos ms-windows windows-nt))
320                              ";"
321                            ":"))))
322           fname)
323       (while fnames
324         (setq fname (car fnames))
325        (if (and (file-exists-p fname) (file-readable-p fname)
326                 (file-regular-p fname))
327             (mailcap-parse-mailcap (car fnames)))
328         (setq fnames (cdr fnames))))
329     (setq mailcap-parsed-p t)))
330
331 (defun mailcap-parse-mailcap (fname)
332   ;; Parse out the mailcap file specified by FNAME
333   (let (major                           ; The major mime type (image/audio/etc)
334         minor                           ; The minor mime type (gif, basic, etc)
335         save-pos                        ; Misc saved positions used in parsing
336         viewer                          ; How to view this mime type
337         info                            ; Misc info about this mime type
338         )
339     (with-temp-buffer
340       (insert-file-contents fname)
341       (set-syntax-table mailcap-parse-args-syntax-table)
342       (mailcap-replace-regexp "#.*" "") ; Remove all comments
343       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
344       (mailcap-replace-regexp "\\\\[ \t\n]+" " ") ; And collapse spaces
345       (mailcap-replace-regexp (concat (regexp-quote "\\") "[ \t]*\n") "")
346       (goto-char (point-max))
347       (skip-chars-backward " \t\n")
348       (delete-region (point) (point-max))
349       (goto-char (point-min))
350       (while (not (eobp))
351         (skip-chars-forward " \t\n")
352         (setq save-pos (point)
353               info nil)
354         (skip-chars-forward "^/;")
355         (downcase-region save-pos (point))
356         (setq major (buffer-substring save-pos (point)))
357         (skip-chars-forward "/ \t\n")
358         (setq save-pos (point))
359         (skip-chars-forward "^;")
360         (downcase-region save-pos (point))
361         (setq minor
362               (cond
363                ((= ?* (or (char-after save-pos) 0)) ".*")
364                ((= (point) save-pos) ".*")
365                (t (buffer-substring save-pos (point)))))
366         (skip-chars-forward "; \t\n")
367         ;;; Got the major/minor chunks, now for the viewers/etc
368         ;;; The first item _must_ be a viewer, according to the
369         ;;; RFC for mailcap files (#1343)
370         (skip-chars-forward "; \t\n")
371         (setq save-pos (point))
372         (skip-chars-forward "^;\n")
373         (if (= (or (char-after save-pos) 0) ?')
374             (setq viewer (progn
375                            (narrow-to-region (1+ save-pos) (point))
376                            (goto-char (point-min))
377                            (prog1
378                                (read (current-buffer))
379                              (goto-char (point-max))
380                              (widen))))
381           (setq viewer (buffer-substring save-pos (point))))
382         (setq save-pos (point))
383         (end-of-line)
384         (setq info (nconc (list (cons 'viewer viewer)
385                                 (cons 'type (concat major "/"
386                                                     (if (string= minor ".*")
387                                                         "*" minor))))
388                           (mailcap-parse-mailcap-extras save-pos (point))))
389         (mailcap-mailcap-entry-passes-test info)
390         (mailcap-add-mailcap-entry major minor info)))))
391
392 (defun mailcap-parse-mailcap-extras (st nd)
393   ;; Grab all the extra stuff from a mailcap entry
394   (let (
395         name                            ; From name=
396         value                           ; its value
397         results                         ; Assoc list of results
398         name-pos                        ; Start of XXXX= position
399         val-pos                         ; Start of value position
400         done                            ; Found end of \'d ;s?
401         )
402     (save-restriction
403       (narrow-to-region st nd)
404       (goto-char (point-min))
405       (skip-chars-forward " \n\t;")
406       (while (not (eobp))
407         (setq done nil)
408         (skip-chars-forward " \";\n\t")
409         (setq name-pos (point))
410         (skip-chars-forward "^ \n\t=")
411         (downcase-region name-pos (point))
412         (setq name (buffer-substring name-pos (point)))
413         (skip-chars-forward " \t\n")
414         (if (/= (or (char-after (point)) 0)  ?=) ; There is no value
415             (setq value nil)
416           (skip-chars-forward " \t\n=")
417           (setq val-pos (point))
418           (if (memq (char-after val-pos) '(?\" ?'))
419               (progn
420                 (setq val-pos (1+ val-pos))
421                 (condition-case nil
422                     (progn
423                       (forward-sexp 1)
424                       (backward-char 1))
425                   (error (goto-char (point-max)))))
426             (while (not done)
427               (skip-chars-forward "^;")
428               (if (= (or (char-after (1- (point))) 0) ?\\ )
429                   (progn
430                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
431                     (skip-chars-forward ";"))
432                 (setq done t))))
433           (setq value (buffer-substring val-pos (point))))
434         (setq results (cons (cons name value) results)))
435       results)))
436
437 (defun mailcap-mailcap-entry-passes-test (info)
438   ;; Return t iff a mailcap entry passes its test clause or no test
439   ;; clause is present.
440   (let (status                          ; Call-process-regions return value
441         (test (assq 'test info))        ; The test clause
442         )
443     (setq status (and test (split-string (cdr test) " ")))
444     (if (and (assoc "needsx11" info) (not (getenv "DISPLAY")))
445         (setq status nil)
446       (cond
447        ((and (equal (nth 0 status) "test")
448              (equal (nth 1 status) "-n")
449              (or (equal (nth 2 status) "$DISPLAY")
450                  (equal (nth 2 status) "\"$DISPLAY\"")))
451         (setq status (if (getenv "DISPLAY") t nil)))
452        ((and (equal (nth 0 status) "test")
453              (equal (nth 1 status) "-z")
454              (or (equal (nth 2 status) "$DISPLAY")
455                  (equal (nth 2 status) "\"$DISPLAY\"")))
456         (setq status (if (getenv "DISPLAY") nil t)))
457        (test nil)
458        (t nil)))
459     (and test (listp test) (setcdr test status))))
460
461 ;;;
462 ;;; The action routines.
463 ;;;
464
465 (defun mailcap-possible-viewers (major minor)
466   ;; Return a list of possible viewers from MAJOR for minor type MINOR
467   (let ((exact '())
468         (wildcard '()))
469     (while major
470       (cond
471        ((equal (car (car major)) minor)
472         (setq exact (cons (cdr (car major)) exact)))
473        ((and minor (string-match (car (car major)) minor))
474         (setq wildcard (cons (cdr (car major)) wildcard))))
475       (setq major (cdr major)))
476     (nconc (nreverse exact) (nreverse wildcard))))
477
478 (defun mailcap-unescape-mime-test (test type-info)
479   (let (save-pos save-chr subst)
480     (cond
481      ((symbolp test) test)
482      ((and (listp test) (symbolp (car test))) test)
483      ((or (stringp test)
484           (and (listp test) (stringp (car test))
485                (setq test (mapconcat 'identity test " "))))
486       (with-temp-buffer
487         (insert test)
488         (goto-char (point-min))
489         (while (not (eobp))
490           (skip-chars-forward "^%")
491           (if (/= (- (point)
492                      (progn (skip-chars-backward "\\\\")
493                             (point)))
494                   0)                    ; It is an escaped %
495               (progn
496                 (delete-char 1)
497                 (skip-chars-forward "%."))
498             (setq save-pos (point))
499             (skip-chars-forward "%")
500             (setq save-chr (char-after (point)))
501             (cond
502              ((null save-chr) nil)
503              ((= save-chr ?t)
504               (delete-region save-pos (progn (forward-char 1) (point)))
505               (insert (or (cdr (assq 'type type-info)) "\"\"")))
506              ((= save-chr ?M)
507               (delete-region save-pos (progn (forward-char 1) (point)))
508               (insert "\"\""))
509              ((= save-chr ?n)
510               (delete-region save-pos (progn (forward-char 1) (point)))
511               (insert "\"\""))
512              ((= save-chr ?F)
513               (delete-region save-pos (progn (forward-char 1) (point)))
514               (insert "\"\""))
515              ((= save-chr ?{)
516               (forward-char 1)
517               (skip-chars-forward "^}")
518               (downcase-region (+ 2 save-pos) (point))
519               (setq subst (buffer-substring (+ 2 save-pos) (point)))
520               (delete-region save-pos (1+ (point)))
521               (insert (or (cdr (assoc subst type-info)) "\"\"")))
522              (t nil))))
523         (buffer-string)))
524      (t (error "Bad value to mailcap-unescape-mime-test. %s" test)))))
525
526 (defvar mailcap-viewer-test-cache nil)
527
528 (defun mailcap-viewer-passes-test (viewer-info type-info)
529   ;; Return non-nil iff the viewer specified by VIEWER-INFO passes its
530   ;; test clause (if any).
531   (let* ((test-info (assq 'test viewer-info))
532          (test (cdr test-info))
533          (otest test)
534          (viewer (cdr (assoc 'viewer viewer-info)))
535          (default-directory (expand-file-name "~/"))
536          status parsed-test cache result)
537     (if (setq cache (assoc test mailcap-viewer-test-cache))
538         (cadr cache)
539       (setq
540        result
541        (cond
542         ((not test-info) t)             ; No test clause
543         ((not test) nil)                ; Already failed test
544         ((eq test t) t)                 ; Already passed test
545         ((and (symbolp test)            ; Lisp function as test
546               (fboundp test))
547          (funcall test type-info))
548         ((and (symbolp test)            ; Lisp variable as test
549               (boundp test))
550          (symbol-value test))
551         ((and (listp test)              ; List to be eval'd
552               (symbolp (car test)))
553          (eval test))
554         (t
555          (setq test (mailcap-unescape-mime-test test type-info)
556                test (list shell-file-name nil nil nil
557                           shell-command-switch test)
558                status (apply 'call-process test))
559          (= 0 status))))
560       (push (list otest result) mailcap-viewer-test-cache)
561       result)))
562
563 (defun mailcap-add-mailcap-entry (major minor info)
564   (let ((old-major (assoc major mailcap-mime-data)))
565     (if (null old-major)                ; New major area
566         (setq mailcap-mime-data
567               (cons (cons major (list (cons minor info)))
568                     mailcap-mime-data))
569       (let ((cur-minor (assoc minor old-major)))
570         (cond
571          ((or (null cur-minor)          ; New minor area, or
572               (assq 'test info))        ; Has a test, insert at beginning
573           (setcdr old-major (cons (cons minor info) (cdr old-major))))
574          ((and (not (assq 'test info)) ; No test info, replace completely
575                (not (assq 'test cur-minor)))
576           (setcdr cur-minor info))
577          (t
578           (setcdr old-major (cons (cons minor info) (cdr old-major)))))))))
579
580 ;;;
581 ;;; The main whabbo
582 ;;;
583
584 (defun mailcap-viewer-lessp (x y)
585   ;; Return t iff viewer X is more desirable than viewer Y
586   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
587         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
588         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
589         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
590     (cond
591      ((and x-lisp (not y-lisp))
592       t)
593      ((and (not y-lisp) x-wild (not y-wild))
594       t)
595      ((and (not x-wild) y-wild)
596       t)
597      (t nil))))
598
599 (defun mailcap-mime-info (string &optional request)
600   "Get the MIME viewer command for STRING, return nil if none found.
601 Expects a complete content-type header line as its argument.
602
603 Second argument REQUEST specifies what information to return.  If it is
604 nil or the empty string, the viewer (second field of the mailcap
605 entry) will be returned.  If it is a string, then the mailcap field
606 corresponding to that string will be returned (print, description,
607 whatever).  If a number, then all the information for this specific
608 viewer is returned.  If `all', then all possible viewers for
609 this type is returned."
610   (let (
611         major                           ; Major encoding (text, etc)
612         minor                           ; Minor encoding (html, etc)
613         info                            ; Other info
614         save-pos                        ; Misc. position during parse
615         major-info                      ; (assoc major mailcap-mime-data)
616         minor-info                      ; (assoc minor major-info)
617         test                            ; current test proc.
618         viewers                         ; Possible viewers
619         passed                          ; Viewers that passed the test
620         viewer                          ; The one and only viewer
621         ctl)
622     (save-excursion
623       (setq ctl (mail-header-parse-content-type (or string "text/plain")))
624       (setq major (split-string (car ctl) "/"))
625       (setq minor (cadr major)
626             major (car major))
627       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
628         (when (setq viewers (mailcap-possible-viewers major-info minor))
629           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
630                                                (cdr a)))
631                              (cdr ctl)))
632           (while viewers
633             (if (mailcap-viewer-passes-test (car viewers) info)
634                 (setq passed (cons (car viewers) passed)))
635             (setq viewers (cdr viewers)))
636           (setq passed (sort (nreverse passed) 'mailcap-viewer-lessp))
637           (setq viewer (car passed))))
638       (when (and (stringp (cdr (assq 'viewer viewer)))
639                  passed)
640         (setq viewer (car passed)))
641       (cond
642        ((and (null viewer) (not (equal major "default")) request)
643         (mailcap-mime-info "default" request))
644        ((or (null request) (equal request ""))
645         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
646        ((stringp request)
647         (if (or (eq request 'test) (eq request 'viewer))
648             (mailcap-unescape-mime-test
649              (cdr-safe (assoc request viewer)) info)))
650        ((eq request 'all)
651         passed)
652        (t
653         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
654         (setq viewer (copy-tree viewer))
655         (let ((view (assq 'viewer viewer))
656               (test (assq 'test viewer)))
657           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
658           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
659         viewer)))))
660
661 ;;;
662 ;;; Experimental MIME-types parsing
663 ;;;
664
665 (defvar mailcap-mime-extensions
666   '((""          . "text/plain")
667     (".abs"      . "audio/x-mpeg")
668     (".aif"      . "audio/aiff")
669     (".aifc"     . "audio/aiff")
670     (".aiff"     . "audio/aiff")
671     (".ano"      . "application/x-annotator")
672     (".au"       . "audio/ulaw")
673     (".avi"      . "video/x-msvideo")
674     (".bcpio"    . "application/x-bcpio")
675     (".bin"      . "application/octet-stream")
676     (".cdf"      . "application/x-netcdr")
677     (".cpio"     . "application/x-cpio")
678     (".csh"      . "application/x-csh")
679     (".dvi"      . "application/x-dvi")
680     (".el"       . "application/emacs-lisp")
681     (".eps"      . "application/postscript")
682     (".etx"      . "text/x-setext")
683     (".exe"      . "application/octet-stream")
684     (".fax"      . "image/x-fax")
685     (".gif"      . "image/gif")
686     (".hdf"      . "application/x-hdf")
687     (".hqx"      . "application/mac-binhex40")
688     (".htm"      . "text/html")
689     (".html"     . "text/html")
690     (".icon"     . "image/x-icon")
691     (".ief"      . "image/ief")
692     (".jpg"      . "image/jpeg")
693     (".macp"     . "image/x-macpaint")
694     (".man"      . "application/x-troff-man")
695     (".me"       . "application/x-troff-me")
696     (".mif"      . "application/mif")
697     (".mov"      . "video/quicktime")
698     (".movie"    . "video/x-sgi-movie")
699     (".mp2"      . "audio/x-mpeg")
700     (".mp3"      . "audio/x-mpeg")
701     (".mp2a"     . "audio/x-mpeg2")
702     (".mpa"      . "audio/x-mpeg")
703     (".mpa2"     . "audio/x-mpeg2")
704     (".mpe"      . "video/mpeg")
705     (".mpeg"     . "video/mpeg")
706     (".mpega"    . "audio/x-mpeg")
707     (".mpegv"    . "video/mpeg")
708     (".mpg"      . "video/mpeg")
709     (".mpv"      . "video/mpeg")
710     (".ms"       . "application/x-troff-ms")
711     (".nc"       . "application/x-netcdf")
712     (".nc"       . "application/x-netcdf")
713     (".oda"      . "application/oda")
714     (".pbm"      . "image/x-portable-bitmap")
715     (".pdf"      . "application/pdf")
716     (".pgm"      . "image/portable-graymap")
717     (".pict"     . "image/pict")
718     (".png"      . "image/png")
719     (".pnm"      . "image/x-portable-anymap")
720     (".ppm"      . "image/portable-pixmap")
721     (".ps"       . "application/postscript")
722     (".qt"       . "video/quicktime")
723     (".ras"      . "image/x-raster")
724     (".rgb"      . "image/x-rgb")
725     (".rtf"      . "application/rtf")
726     (".rtx"      . "text/richtext")
727     (".sh"       . "application/x-sh")
728     (".sit"      . "application/x-stuffit")
729     (".snd"      . "audio/basic")
730     (".src"      . "application/x-wais-source")
731     (".tar"      . "archive/tar")
732     (".tcl"      . "application/x-tcl")
733     (".tcl"      . "application/x-tcl")
734     (".tex"      . "application/x-tex")
735     (".texi"     . "application/texinfo")
736     (".tga"      . "image/x-targa")
737     (".tif"      . "image/tiff")
738     (".tiff"     . "image/tiff")
739     (".tr"       . "application/x-troff")
740     (".troff"    . "application/x-troff")
741     (".tsv"      . "text/tab-separated-values")
742     (".txt"      . "text/plain")
743     (".vbs"      . "video/mpeg")
744     (".vox"      . "audio/basic")
745     (".vrml"     . "x-world/x-vrml")
746     (".wav"      . "audio/x-wav")
747     (".wrl"      . "x-world/x-vrml")
748     (".xbm"      . "image/xbm")
749     (".xpm"      . "image/x-pixmap")
750     (".xwd"      . "image/windowdump")
751     (".zip"      . "application/zip")
752     (".ai"       . "application/postscript")
753     (".jpe"      . "image/jpeg")
754     (".jpeg"     . "image/jpeg"))
755   "*An assoc list of file extensions and the MIME content-types they
756 correspond to.")
757
758 (defun mailcap-parse-mimetypes (&optional path)
759   ;; Parse out all the mimetypes specified in a unix-style path string PATH
760   (cond
761    (path nil)
762    ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
763    ((memq system-type '(ms-dos ms-windows windows-nt))
764     (setq path (mapconcat 'expand-file-name
765                           '("~/mime.typ" "~/etc/mime.typ") ";")))
766    (t (setq path (mapconcat 'expand-file-name
767                             '("~/.mime-types"
768                               "/etc/mime-types:/usr/etc/mime-types"
769                               "/usr/local/etc/mime-types"
770                               "/usr/local/www/conf/mime-types") ":"))))
771   (let ((fnames (reverse
772                  (split-string path
773                                (if (memq system-type
774                                          '(ms-dos ms-windows windows-nt))
775                                    ";" ":"))))
776         fname)
777     (while fnames
778       (setq fname (car fnames))
779       (if (and (file-exists-p fname) (file-readable-p fname))
780           (mailcap-parse-mimetype-file (car fnames)))
781       (setq fnames (cdr fnames)))))
782
783 (defun mailcap-parse-mimetype-file (fname)
784   ;; Parse out a mime-types file
785   (let (type                            ; The MIME type for this line
786         extns                           ; The extensions for this line
787         save-pos                        ; Misc. saved buffer positions
788         )
789     (with-temp-buffer
790       (insert-file-contents fname)
791       (mailcap-replace-regexp "#.*" "")
792       (mailcap-replace-regexp "\n+" "\n")
793       (mailcap-replace-regexp "[ \t]+$" "")
794       (goto-char (point-max))
795       (skip-chars-backward " \t\n")
796       (delete-region (point) (point-max))
797       (goto-char (point-min))
798       (while (not (eobp))
799         (skip-chars-forward " \t\n")
800         (setq save-pos (point))
801         (skip-chars-forward "^ \t")
802         (downcase-region save-pos (point))
803         (setq type (buffer-substring save-pos (point)))
804         (while (not (eolp))
805           (skip-chars-forward " \t")
806           (setq save-pos (point))
807           (skip-chars-forward "^ \t\n")
808           (setq extns (cons (buffer-substring save-pos (point)) extns)))
809         (while extns
810           (setq mailcap-mime-extensions
811                 (cons
812                  (cons (if (= (string-to-char (car extns)) ?.)
813                            (car extns)
814                          (concat "." (car extns))) type)
815                  mailcap-mime-extensions)
816                 extns (cdr extns)))))))
817
818 (defun mailcap-extension-to-mime (extn)
819   "Return the MIME content type of the file extensions EXTN."
820   (if (and (stringp extn)
821            (not (eq (string-to-char extn) ?.)))
822       (setq extn (concat "." extn)))
823   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
824
825 (defvar mailcap-binary-suffixes
826   (if (memq system-type '(ms-dos windows-nt))
827       '(".exe" ".com" ".bat" ".cmd" ".btm" "")
828     '("")))
829
830 (defun mailcap-command-p (command)
831   "Say whether COMMAND is in the exec path.
832 The path of COMMAND will be returned iff COMMAND is a command."
833   (let ((path (if (file-name-absolute-p command) '(nil) exec-path))
834         file dir)
835     (catch 'found
836       (while (setq dir (pop path))
837         (let ((suffixes mailcap-binary-suffixes))
838           (while suffixes
839             (when (and (file-executable-p
840                         (setq file (expand-file-name
841                                     (concat command (pop suffixes))
842                                     dir)))
843                        (not (file-directory-p file)))
844               (throw 'found file))))))))
845
846 (provide 'mailcap)
847
848 ;;; mailcap.el ends here