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