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