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