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