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