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