*** empty log message ***
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- MIME media types configuration
2 ;; Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 ;; Author: William M. Perry <wmperry@aventail.com>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail, multimedia
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 ;; Provides configuration of MIME media types from directly from Lisp
28 ;; and via the usual mailcap mechanism (RFC 1524).  Deals with
29 ;; mime.types similarly.
30
31 ;;; Code:
32
33 (eval-when-compile (require 'cl))
34 (require 'mail-parse)
35 (require 'mm-util)
36
37 (defgroup mailcap nil
38   "Definition of viewers for MIME types."
39   :version "21.1"
40   :group 'mime)
41
42 (defvar mailcap-parse-args-syntax-table
43   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
44     (modify-syntax-entry ?' "\"" table)
45     (modify-syntax-entry ?` "\"" table)
46     (modify-syntax-entry ?{ "(" table)
47     (modify-syntax-entry ?} ")" table)
48     table)
49   "A syntax table for parsing sgml attributes.")
50
51 ;; Postpone using defcustom for this as it's so big and we essentially
52 ;; have to have two copies of the data around then.  Perhaps just
53 ;; customize the Lisp viewers and rely on the normal configuration
54 ;; files for the rest?  -- fx
55 (defvar mailcap-mime-data
56   '(("application"
57      ("vnd.ms-excel"
58       (viewer . "gnumeric %s")
59       (test   . (getenv "DISPLAY"))
60       (type . "application/vnd.ms-excel"))
61      ("x-x509-ca-cert"
62       (viewer . ssl-view-site-cert)
63       (test . (fboundp 'ssl-view-site-cert))
64       (type . "application/x-x509-ca-cert"))
65      ("x-x509-user-cert"
66       (viewer . ssl-view-user-cert)
67       (test . (fboundp 'ssl-view-user-cert))
68       (type . "application/x-x509-user-cert"))
69      ("octet-stream"
70       (viewer . mailcap-save-binary-file)
71       (non-viewer . t)
72       (type . "application/octet-stream"))
73 ;;; XEmacs says `ns' device-type not implemented.
74 ;;      ("dvi"
75 ;;       (viewer . "open %s")
76 ;;       (type   . "application/dvi")
77 ;;       (test   . (eq (mm-device-type) 'ns)))
78      ("dvi"
79       (viewer . "xdvi %s")
80       (test   . (eq (mm-device-type) 'x))
81       ("needsx11")
82       (type   . "application/dvi"))
83      ("dvi"
84       (viewer . "dvitty %s")
85       (test   . (not (getenv "DISPLAY")))
86       (type   . "application/dvi"))
87      ("emacs-lisp"
88       (viewer . mailcap-maybe-eval)
89       (type   . "application/emacs-lisp"))
90      ("x-tar"
91       (viewer . mailcap-save-binary-file)
92       (non-viewer . t)
93       (type   . "application/x-tar"))
94      ("x-latex"
95       (viewer . tex-mode)
96       (test   . (fboundp 'tex-mode))
97       (type   . "application/x-latex"))
98      ("x-tex"
99       (viewer . tex-mode)
100       (test   . (fboundp 'tex-mode))
101       (type   . "application/x-tex"))
102      ("latex"
103       (viewer . tex-mode)
104       (test   . (fboundp 'tex-mode))
105       (type   . "application/latex"))
106      ("tex"
107       (viewer . tex-mode)
108       (test   . (fboundp 'tex-mode))
109       (type   . "application/tex"))
110      ("texinfo"
111       (viewer . texinfo-mode)
112       (test   . (fboundp 'texinfo-mode))
113       (type   . "application/tex"))
114      ("zip"
115       (viewer . mailcap-save-binary-file)
116       (non-viewer . t)
117       (type   . "application/zip")
118       ("copiousoutput"))
119      ;; Prefer free viewers.
120      ("pdf"
121       (viewer . "gv %s")
122       (type . "application/pdf")
123       (test . window-system))
124      ("pdf"
125       (viewer . "xpdf %s")
126       (type . "application/pdf")
127       (test . (eq (mm-device-type) 'x)))
128      ("pdf"
129       (viewer . "acroread %s")
130       (type   . "application/pdf"))
131 ;;; XEmacs says `ns' device-type not implemented.
132 ;;      ("postscript"
133 ;;       (viewer . "open %s")
134 ;;       (type   . "application/postscript")
135 ;;       (test   . (eq (mm-device-type) 'ns)))
136      ("postscript"
137       (viewer . "gv -safer %s")
138       (type . "application/postscript")
139       (test   . window-system)
140       ("needsx11"))
141      ("postscript"
142       (viewer . "ghostview -dSAFER %s")
143       (type . "application/postscript")
144       (test   . (eq (mm-device-type) 'x))
145       ("needsx11"))
146      ("postscript"
147       (viewer . "ps2ascii %s")
148       (type . "application/postscript")
149       (test . (not (getenv "DISPLAY")))
150       ("copiousoutput"))
151      ("sieve"
152       (viewer . sieve-mode)
153       (test   . (fboundp 'sieve-mode))
154       (type   . "application/sieve")))
155     ("audio"
156      ("x-mpeg"
157       (viewer . "maplay %s")
158       (type   . "audio/x-mpeg"))
159      (".*"
160       (viewer . "showaudio")
161       (type   . "audio/*")))
162     ("message"
163      ("rfc-*822"
164       (viewer . mm-view-message)
165       (test   . (and (featurep 'gnus)
166                      (gnus-alive-p)))
167       (type   . "message/rfc822"))
168      ("rfc-*822"
169       (viewer . vm-mode)
170       (test   . (fboundp 'vm-mode))
171       (type   . "message/rfc822"))
172      ("rfc-*822"
173       (viewer . w3-mode)
174       (test   . (fboundp 'w3-mode))
175       (type   . "message/rfc822"))
176      ("rfc-*822"
177       (viewer . view-mode)
178       (type   . "message/rfc822")))
179     ("image"
180      ("x-xwd"
181       (viewer  . "xwud -in %s")
182       (type    . "image/x-xwd")
183       ("compose" . "xwd -frame > %s")
184       (test    . (eq (mm-device-type) 'x))
185       ("needsx11"))
186      ("x11-dump"
187       (viewer . "xwud -in %s")
188       (type . "image/x-xwd")
189       ("compose" . "xwd -frame > %s")
190       (test   . (eq (mm-device-type) 'x))
191       ("needsx11"))
192      ("windowdump"
193       (viewer . "xwud -in %s")
194       (type . "image/x-xwd")
195       ("compose" . "xwd -frame > %s")
196       (test   . (eq (mm-device-type) 'x))
197       ("needsx11"))
198 ;;; XEmacs says `ns' device-type not implemented.
199 ;;      (".*"
200 ;;       (viewer . "aopen %s")
201 ;;       (type   . "image/*")
202 ;;       (test   . (eq (mm-device-type) 'ns)))
203      (".*"
204       (viewer . "display %s")
205       (type . "image/*")
206       (test   . (eq (mm-device-type) 'x))
207       ("needsx11"))
208      (".*"
209       (viewer . "ee %s")
210       (type . "image/*")
211       (test   . (eq (mm-device-type) 'x))
212       ("needsx11")))
213     ("text"
214      ("plain"
215       (viewer  . w3-mode)
216       (test    . (fboundp 'w3-mode))
217       (type    . "text/plain"))
218      ("plain"
219       (viewer  . view-mode)
220       (test    . (fboundp 'view-mode))
221       (type    . "text/plain"))
222      ("plain"
223       (viewer  . fundamental-mode)
224       (type    . "text/plain"))
225      ("enriched"
226       (viewer . enriched-decode-region)
227       (test   . (fboundp 'enriched-decode))
228       (type   . "text/enriched"))
229      ("html"
230       (viewer . mm-w3-prepare-buffer)
231       (test   . (fboundp 'w3-prepare-buffer))
232       (type   . "text/html")))
233     ("video"
234      ("mpeg"
235       (viewer . "mpeg_play %s")
236       (type   . "video/mpeg")
237       (test   . (eq (mm-device-type) 'x))
238       ("needsx11")))
239     ("x-world"
240      ("x-vrml"
241       (viewer  . "webspace -remote %s -URL %u")
242       (type    . "x-world/x-vrml")
243       ("description"
244        "VRML document")))
245     ("archive"
246      ("tar"
247       (viewer . tar-mode)
248       (type . "archive/tar")
249       (test . (fboundp 'tar-mode)))))
250   "The mailcap structure is an assoc list of assoc lists.
251 1st assoc list is keyed on the major content-type
252 2nd assoc list is keyed on the minor content-type (which can be a regexp)
253
254 Which looks like:
255 -----------------
256  ((\"application\"
257    (\"postscript\" . <info>))
258   (\"text\"
259    (\"plain\" . <info>)))
260
261 Where <info> is another assoc list of the various information
262 related to the mailcap RFC 1524.  This is keyed on the lowercase
263 attribute name (viewer, test, etc).  This looks like:
264  ((viewer . VIEWERINFO)
265   (test   . TESTINFO)
266   (xxxx   . \"STRING\")
267   FLAG)
268
269 Where VIEWERINFO specifies how the content-type is viewed.  Can be
270 a string, in which case it is run through a shell, with
271 appropriate parameters, or a symbol, in which case the symbol is
272 `funcall'ed, with the buffer as an argument.
273
274 TESTINFO is a test for the viewer's applicability, or nil.  If nil, it
275 means the viewer is always valid.  If it is a Lisp function, it is
276 called with a list of items from any extra fields from the
277 Content-Type header as argument to return a boolean value for the
278 validity.  Otherwise, if it is a non-function Lisp symbol or list
279 whose car is a symbol, it is `eval'led to yield the validity.  If it
280 is a string or list of strings, it represents a shell command to run
281 to return a true or false shell value for the validity.")
282
283 (defcustom mailcap-download-directory nil
284   "*Directory to which `mailcap-save-binary-file' downloads files by default.
285 nil means your home directory."
286   :type '(choice (const :tag "Home directory" nil)
287                  directory)
288   :group 'mailcap)
289
290 (defvar mailcap-poor-system-types
291   '(ms-dos ms-windows windows-nt win32 w32 mswindows)
292   "Systems that don't have a Unix-like directory hierarchy.")
293
294 ;;;
295 ;;; Utility functions
296 ;;;
297
298 (defun mailcap-save-binary-file ()
299   (goto-char (point-min))
300   (unwind-protect
301       (let ((file (read-file-name
302                    "Filename to save as: "
303                    (or mailcap-download-directory "~/")))
304             (require-final-newline nil))
305         (write-region (point-min) (point-max) file))
306     (kill-buffer (current-buffer))))
307
308 (defvar mailcap-maybe-eval-warning
309   "*** WARNING ***
310
311 This MIME part contains untrusted and possibly harmful content.
312 If you evaluate the Emacs Lisp code contained in it, a lot of nasty
313 things can happen.  Please examine the code very carefully before you
314 instruct Emacs to evaluate it.  You can browse the buffer containing
315 the code using \\[scroll-other-window].
316
317 If you are unsure what to do, please answer \"no\"."
318   "Text of warning message displayed by `mailcap-maybe-eval'.
319 Make sure that this text consists only of few text lines.  Otherwise,
320 Gnus might fail to display all of it.")
321
322 (defun mailcap-maybe-eval ()
323   "Maybe evaluate a buffer of Emacs Lisp code."
324   (let ((lisp-buffer (current-buffer)))
325     (goto-char (point-min))
326     (when
327         (save-window-excursion
328           (delete-other-windows)
329           (let ((buffer (get-buffer-create (generate-new-buffer-name
330                                             "*Warning*"))))
331             (unwind-protect
332                 (with-current-buffer buffer
333                   (insert (substitute-command-keys
334                            mailcap-maybe-eval-warning))
335                   (goto-char (point-min))
336                   (display-buffer buffer)
337                   (yes-or-no-p "This is potentially dangerous emacs-lisp code, evaluate it? "))
338               (kill-buffer buffer))))
339       (eval-buffer (current-buffer)))
340     (when (buffer-live-p lisp-buffer)
341       (with-current-buffer lisp-buffer
342         (emacs-lisp-mode)))))
343
344
345 ;;;
346 ;;; The mailcap parser
347 ;;;
348
349 (defun mailcap-replace-regexp (regexp to-string)
350   ;; Quiet replace-regexp.
351   (goto-char (point-min))
352   (while (re-search-forward regexp nil t)
353     (replace-match to-string t nil)))
354
355 (defvar mailcap-parsed-p nil)
356
357 (defun mailcap-parse-mailcaps (&optional path force)
358   "Parse out all the mailcaps specified in a path string PATH.
359 Components of PATH are separated by the `path-separator' character
360 appropriate for this system.  If FORCE, re-parse even if already
361 parsed.  If PATH is omitted, use the value of environment variable
362 MAILCAPS if set; otherwise (on Unix) use the path from RFC 1524, plus
363 /usr/local/etc/mailcap."
364   (interactive (list nil t))
365   (when (or (not mailcap-parsed-p)
366             force)
367     (cond
368      (path nil)
369      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
370      ((memq system-type mailcap-poor-system-types)
371       (setq path '("~/.mailcap" "~/mail.cap" "~/etc/mail.cap")))
372      (t (setq path
373               ;; This is per RFC 1524, specifically
374               ;; with /usr before /usr/local.
375               '("~/.mailcap" "/etc/mailcap" "/usr/etc/mailcap"
376                 "/usr/local/etc/mailcap"))))
377     (let ((fnames (reverse
378                    (if (stringp path)
379                        (delete "" (split-string path path-separator))
380                      path)))
381           fname)
382       (while fnames
383         (setq fname (car fnames))
384         (if (and (file-readable-p fname)
385                  (file-regular-p fname))
386             (mailcap-parse-mailcap fname))
387         (setq fnames (cdr fnames))))
388       (setq mailcap-parsed-p t)))
389
390 (defun mailcap-parse-mailcap (fname)
391   "Parse out the mailcap file specified by FNAME."
392   (let (major                           ; The major mime type (image/audio/etc)
393         minor                           ; The minor mime type (gif, basic, etc)
394         save-pos                        ; Misc saved positions used in parsing
395         viewer                          ; How to view this mime type
396         info                            ; Misc info about this mime type
397         )
398     (with-temp-buffer
399       (insert-file-contents fname)
400       (set-syntax-table mailcap-parse-args-syntax-table)
401       (mailcap-replace-regexp "#.*" "") ; Remove all comments
402       (mailcap-replace-regexp "\\\\[ \t]*\n" " ") ; And collapse spaces
403       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
404       (goto-char (point-max))
405       (skip-chars-backward " \t\n")
406       (delete-region (point) (point-max))
407       (while (not (bobp))
408         (skip-chars-backward " \t\n")
409         (beginning-of-line)
410         (setq save-pos (point)
411               info nil)
412         (skip-chars-forward "^/; \t\n")
413         (downcase-region save-pos (point))
414         (setq major (buffer-substring save-pos (point)))
415         (skip-chars-forward " \t")
416         (setq minor "")
417         (when (eq (char-after) ?/)
418           (forward-char)
419           (skip-chars-forward " \t")
420           (setq save-pos (point))
421           (skip-chars-forward "^; \t\n")
422           (downcase-region save-pos (point))
423           (setq minor
424                 (cond
425                  ((eq ?* (or (char-after save-pos) 0)) ".*")
426                  ((= (point) save-pos) ".*")
427                  (t (regexp-quote (buffer-substring save-pos (point)))))))
428         (skip-chars-forward " \t")
429         ;;; Got the major/minor chunks, now for the viewers/etc
430         ;;; The first item _must_ be a viewer, according to the
431         ;;; RFC for mailcap files (#1524)
432         (setq viewer "")
433         (when (eq (char-after) ?\;)
434           (forward-char)
435           (skip-chars-forward " \t")
436           (setq save-pos (point))
437           (skip-chars-forward "^;\n")
438           ;; skip \;
439           (while (eq (char-before) ?\\)
440             (backward-delete-char 1)
441             (forward-char)
442             (skip-chars-forward "^;\n"))
443           (if (eq (or (char-after save-pos) 0) ?')
444               (setq viewer (progn
445                              (narrow-to-region (1+ save-pos) (point))
446                              (goto-char (point-min))
447                              (prog1
448                                  (read (current-buffer))
449                                (goto-char (point-max))
450                                (widen))))
451             (setq viewer (buffer-substring save-pos (point)))))
452         (setq save-pos (point))
453         (end-of-line)
454         (unless (equal viewer "")
455           (setq info (nconc (list (cons 'viewer viewer)
456                                   (cons 'type (concat major "/"
457                                                       (if (string= minor ".*")
458                                                           "*" minor))))
459                             (mailcap-parse-mailcap-extras save-pos (point))))
460           (mailcap-mailcap-entry-passes-test info)
461           (mailcap-add-mailcap-entry major minor info))
462         (beginning-of-line)))))
463
464 (defun mailcap-parse-mailcap-extras (st nd)
465   "Grab all the extra stuff from a mailcap entry."
466   (let (
467         name                            ; From name=
468         value                           ; its value
469         results                         ; Assoc list of results
470         name-pos                        ; Start of XXXX= position
471         val-pos                         ; Start of value position
472         done                            ; Found end of \'d ;s?
473         )
474     (save-restriction
475       (narrow-to-region st nd)
476       (goto-char (point-min))
477       (skip-chars-forward " \n\t;")
478       (while (not (eobp))
479         (setq done nil)
480         (setq name-pos (point))
481         (skip-chars-forward "^ \n\t=;")
482         (downcase-region name-pos (point))
483         (setq name (buffer-substring name-pos (point)))
484         (skip-chars-forward " \t\n")
485         (if (not (eq (char-after (point)) ?=)) ; There is no value
486             (setq value t)
487           (skip-chars-forward " \t\n=")
488           (setq val-pos (point))
489           (if (memq (char-after val-pos) '(?\" ?'))
490               (progn
491                 (setq val-pos (1+ val-pos))
492                 (condition-case nil
493                     (progn
494                       (forward-sexp 1)
495                       (backward-char 1))
496                   (error (goto-char (point-max)))))
497             (while (not done)
498               (skip-chars-forward "^;")
499               (if (eq (char-after (1- (point))) ?\\ )
500                   (progn
501                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
502                     (skip-chars-forward ";"))
503                 (setq done t))))
504           (setq value (buffer-substring val-pos (point))))
505         (setq results (cons (cons name value) results))
506         (skip-chars-forward " \";\n\t"))
507       results)))
508
509 (defun mailcap-mailcap-entry-passes-test (info)
510   "Return non-nil iff mailcap entry INFO passes its test clause.
511 Also return non-nil if no test clause is present."
512   (let ((test (assq 'test info))        ; The test clause
513         status)
514     (setq status (and test (split-string (cdr test) " ")))
515     (if (and (or (assoc "needsterm" info)
516                  (assoc "needsterminal" info)
517                  (assoc "needsx11" info))
518              (not (getenv "DISPLAY")))
519         (setq status nil)
520       (cond
521        ((and (equal (nth 0 status) "test")
522              (equal (nth 1 status) "-n")
523              (or (equal (nth 2 status) "$DISPLAY")
524                  (equal (nth 2 status) "\"$DISPLAY\"")))
525         (setq status (if (getenv "DISPLAY") t nil)))
526        ((and (equal (nth 0 status) "test")
527              (equal (nth 1 status) "-z")
528              (or (equal (nth 2 status) "$DISPLAY")
529                  (equal (nth 2 status) "\"$DISPLAY\"")))
530         (setq status (if (getenv "DISPLAY") nil t)))
531        (test nil)
532        (t nil)))
533     (and test (listp test) (setcdr test status))))
534
535 ;;;
536 ;;; The action routines.
537 ;;;
538
539 (defun mailcap-possible-viewers (major minor)
540   "Return a list of possible viewers from MAJOR for minor type MINOR."
541   (let ((exact '())
542         (wildcard '()))
543     (while major
544       (cond
545        ((equal (car (car major)) minor)
546         (setq exact (cons (cdr (car major)) exact)))
547        ((and minor (string-match (concat "^" (car (car major)) "$") minor))
548         (setq wildcard (cons (cdr (car major)) wildcard))))
549       (setq major (cdr major)))
550     (nconc exact wildcard)))
551
552 (defun mailcap-unescape-mime-test (test type-info)
553   (let (save-pos save-chr subst)
554     (cond
555      ((symbolp test) test)
556      ((and (listp test) (symbolp (car test))) test)
557      ((or (stringp test)
558           (and (listp test) (stringp (car test))
559                (setq test (mapconcat 'identity test " "))))
560       (with-temp-buffer
561         (insert test)
562         (goto-char (point-min))
563         (while (not (eobp))
564           (skip-chars-forward "^%")
565           (if (/= (- (point)
566                      (progn (skip-chars-backward "\\\\")
567                             (point)))
568                   0)                    ; It is an escaped %
569               (progn
570                 (delete-char 1)
571                 (skip-chars-forward "%."))
572             (setq save-pos (point))
573             (skip-chars-forward "%")
574             (setq save-chr (char-after (point)))
575             ;; Escapes:
576             ;; %s: name of a file for the body data
577             ;; %t: content-type
578             ;; %{<parameter name}: value of parameter in mailcap entry
579             ;; %n: number of sub-parts for multipart content-type
580             ;; %F: a set of content-type/filename pairs for multiparts
581             (cond
582              ((null save-chr) nil)
583              ((= save-chr ?t)
584               (delete-region save-pos (progn (forward-char 1) (point)))
585               (insert (or (cdr (assq 'type type-info)) "\"\"")))
586              ((memq save-chr '(?M ?n ?F))
587               (delete-region save-pos (progn (forward-char 1) (point)))
588               (insert "\"\""))
589              ((= save-chr ?{)
590               (forward-char 1)
591               (skip-chars-forward "^}")
592               (downcase-region (+ 2 save-pos) (point))
593               (setq subst (buffer-substring (+ 2 save-pos) (point)))
594               (delete-region save-pos (1+ (point)))
595               (insert (or (cdr (assoc subst type-info)) "\"\"")))
596              (t nil))))
597         (buffer-string)))
598      (t (error "Bad value to mailcap-unescape-mime-test: %s" test)))))
599
600 (defvar mailcap-viewer-test-cache nil)
601
602 (defun mailcap-viewer-passes-test (viewer-info type-info)
603   "Return non-nil iff viewer specified by VIEWER-INFO passes its test clause.
604 Also retun non-nil if it has no test clause.  TYPE-INFO is an argument
605 to supply to the test."
606   (let* ((test-info (assq 'test viewer-info))
607          (test (cdr test-info))
608          (otest test)
609          (viewer (cdr (assoc 'viewer viewer-info)))
610          (default-directory (expand-file-name "~/"))
611          status parsed-test cache result)
612     (if (setq cache (assoc test mailcap-viewer-test-cache))
613         (cadr cache)
614       (setq
615        result
616        (cond
617         ((not test-info) t)             ; No test clause
618         ((not test) nil)                ; Already failed test
619         ((eq test t) t)                 ; Already passed test
620         ((functionp test)               ; Lisp function as test
621          (funcall test type-info))
622         ((and (symbolp test)            ; Lisp variable as test
623               (boundp test))
624          (symbol-value test))
625         ((and (listp test)              ; List to be eval'd
626               (symbolp (car test)))
627          (eval test))
628         (t
629          (setq test (mailcap-unescape-mime-test test type-info)
630                test (list shell-file-name nil nil nil
631                           shell-command-switch test)
632                status (apply 'call-process test))
633          (= 0 status))))
634       (push (list otest result) mailcap-viewer-test-cache)
635       result)))
636
637 (defun mailcap-add-mailcap-entry (major minor info)
638   (let ((old-major (assoc major mailcap-mime-data)))
639     (if (null old-major)                ; New major area
640         (setq mailcap-mime-data
641               (cons (cons major (list (cons minor info)))
642                     mailcap-mime-data))
643        (let ((cur-minor (assoc minor old-major)))
644         (cond
645          ((or (null cur-minor)          ; New minor area, or
646               (assq 'test info))        ; Has a test, insert at beginning
647           (setcdr old-major (cons (cons minor info) (cdr old-major))))
648          ((and (not (assq 'test info))  ; No test info, replace completely
649                (not (assq 'test cur-minor))
650                (equal (assq 'viewer info)  ; Keep alternative viewer
651                       (assq 'viewer cur-minor)))
652           (setcdr cur-minor info))
653          (t
654           (setcdr old-major (cons (cons minor info) (cdr old-major))))))
655       )))
656
657 (defun mailcap-add (type viewer &optional test)
658   "Add VIEWER as a handler for TYPE.
659 If TEST is not given, it defaults to t."
660   (let ((tl (split-string type "/")))
661     (when (or (not (car tl))
662               (not (cadr tl)))
663       (error "%s is not a valid MIME type" type))
664     (mailcap-add-mailcap-entry
665      (car tl) (cadr tl)
666      `((viewer . ,viewer)
667        (test . ,(if test test t))
668        (type . ,type)))))
669
670 ;;;
671 ;;; The main whabbo
672 ;;;
673
674 (defun mailcap-viewer-lessp (x y)
675   "Return t iff viewer X is more desirable than viewer Y."
676   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
677         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
678         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
679         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
680     (cond
681      ((and x-wild (not y-wild))
682       nil)
683      ((and (not x-wild) y-wild)
684       t)
685      ((and (not y-lisp) x-lisp)
686       t)
687      (t nil))))
688
689 (defun mailcap-mime-info (string &optional request)
690   "Get the MIME viewer command for STRING, return nil if none found.
691 Expects a complete content-type header line as its argument.
692
693 Second argument REQUEST specifies what information to return.  If it is
694 nil or the empty string, the viewer (second field of the mailcap
695 entry) will be returned.  If it is a string, then the mailcap field
696 corresponding to that string will be returned (print, description,
697 whatever).  If a number, then all the information for this specific
698 viewer is returned.  If `all', then all possible viewers for
699 this type is returned."
700   (let (
701         major                           ; Major encoding (text, etc)
702         minor                           ; Minor encoding (html, etc)
703         info                            ; Other info
704         save-pos                        ; Misc. position during parse
705         major-info                      ; (assoc major mailcap-mime-data)
706         minor-info                      ; (assoc minor major-info)
707         test                            ; current test proc.
708         viewers                         ; Possible viewers
709         passed                          ; Viewers that passed the test
710         viewer                          ; The one and only viewer
711         ctl)
712     (save-excursion
713       (setq ctl (mail-header-parse-content-type (or string "text/plain")))
714       (setq major (split-string (car ctl) "/"))
715       (setq minor (cadr major)
716             major (car major))
717       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
718         (when (setq viewers (mailcap-possible-viewers major-info minor))
719           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
720                                                (cdr a)))
721                              (cdr ctl)))
722           (while viewers
723             (if (mailcap-viewer-passes-test (car viewers) info)
724                 (setq passed (cons (car viewers) passed)))
725             (setq viewers (cdr viewers)))
726           (setq passed (sort passed 'mailcap-viewer-lessp))
727           (setq viewer (car passed))))
728       (when (and (stringp (cdr (assq 'viewer viewer)))
729                  passed)
730         (setq viewer (car passed)))
731       (cond
732        ((and (null viewer) (not (equal major "default")) request)
733         (mailcap-mime-info "default" request))
734        ((or (null request) (equal request ""))
735         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
736        ((stringp request)
737         (mailcap-unescape-mime-test
738          (cdr-safe (assoc request viewer)) info))
739        ((eq request 'all)
740         passed)
741        (t
742         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
743         (setq viewer (copy-sequence viewer))
744         (let ((view (assq 'viewer viewer))
745               (test (assq 'test viewer)))
746           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
747           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
748         viewer)))))
749
750 ;;;
751 ;;; Experimental MIME-types parsing
752 ;;;
753
754 (defvar mailcap-mime-extensions
755   '((""        . "text/plain")
756     (".abs"   . "audio/x-mpeg")
757     (".aif"   . "audio/aiff")
758     (".aifc"  . "audio/aiff")
759     (".aiff"  . "audio/aiff")
760     (".ano"   . "application/x-annotator")
761     (".au"    . "audio/ulaw")
762     (".avi"   . "video/x-msvideo")
763     (".bcpio" . "application/x-bcpio")
764     (".bin"   . "application/octet-stream")
765     (".cdf"   . "application/x-netcdr")
766     (".cpio"  . "application/x-cpio")
767     (".csh"   . "application/x-csh")
768     (".css"   . "text/css")
769     (".dvi"   . "application/x-dvi")
770     (".diff"  . "text/x-patch")
771     (".el"    . "application/emacs-lisp")
772     (".eps"   . "application/postscript")
773     (".etx"   . "text/x-setext")
774     (".exe"   . "application/octet-stream")
775     (".fax"   . "image/x-fax")
776     (".gif"   . "image/gif")
777     (".hdf"   . "application/x-hdf")
778     (".hqx"   . "application/mac-binhex40")
779     (".htm"   . "text/html")
780     (".html"  . "text/html")
781     (".icon"  . "image/x-icon")
782     (".ief"   . "image/ief")
783     (".jpg"   . "image/jpeg")
784     (".macp"  . "image/x-macpaint")
785     (".man"   . "application/x-troff-man")
786     (".me"    . "application/x-troff-me")
787     (".mif"   . "application/mif")
788     (".mov"   . "video/quicktime")
789     (".movie" . "video/x-sgi-movie")
790     (".mp2"   . "audio/x-mpeg")
791     (".mp3"   . "audio/x-mpeg")
792     (".mp2a"  . "audio/x-mpeg2")
793     (".mpa"   . "audio/x-mpeg")
794     (".mpa2"  . "audio/x-mpeg2")
795     (".mpe"   . "video/mpeg")
796     (".mpeg"  . "video/mpeg")
797     (".mpega" . "audio/x-mpeg")
798     (".mpegv" . "video/mpeg")
799     (".mpg"   . "video/mpeg")
800     (".mpv"   . "video/mpeg")
801     (".ms"    . "application/x-troff-ms")
802     (".nc"    . "application/x-netcdf")
803     (".nc"    . "application/x-netcdf")
804     (".oda"   . "application/oda")
805     (".patch" . "text/x-patch")
806     (".pbm"   . "image/x-portable-bitmap")
807     (".pdf"   . "application/pdf")
808     (".pgm"   . "image/portable-graymap")
809     (".pict"  . "image/pict")
810     (".png"   . "image/png")
811     (".pnm"   . "image/x-portable-anymap")
812     (".ppm"   . "image/portable-pixmap")
813     (".ps"    . "application/postscript")
814     (".qt"    . "video/quicktime")
815     (".ras"   . "image/x-raster")
816     (".rgb"   . "image/x-rgb")
817     (".rtf"   . "application/rtf")
818     (".rtx"   . "text/richtext")
819     (".sh"    . "application/x-sh")
820     (".sit"   . "application/x-stuffit")
821     (".siv"   . "application/sieve")
822     (".snd"   . "audio/basic")
823     (".src"   . "application/x-wais-source")
824     (".tar"   . "archive/tar")
825     (".tcl"   . "application/x-tcl")
826     (".tex"   . "application/x-tex")
827     (".texi"  . "application/texinfo")
828     (".tga"   . "image/x-targa")
829     (".tif"   . "image/tiff")
830     (".tiff"  . "image/tiff")
831     (".tr"    . "application/x-troff")
832     (".troff" . "application/x-troff")
833     (".tsv"   . "text/tab-separated-values")
834     (".txt"   . "text/plain")
835     (".vbs"   . "video/mpeg")
836     (".vox"   . "audio/basic")
837     (".vrml"  . "x-world/x-vrml")
838     (".wav"   . "audio/x-wav")
839     (".xls"   . "application/vnd.ms-excel")
840     (".wrl"   . "x-world/x-vrml")
841     (".xbm"   . "image/xbm")
842     (".xpm"   . "image/xpm")
843     (".xwd"   . "image/windowdump")
844     (".zip"   . "application/zip")
845     (".ai"    . "application/postscript")
846     (".jpe"   . "image/jpeg")
847     (".jpeg"  . "image/jpeg"))
848   "An alist of file extensions and corresponding MIME content-types.
849 This exists for you to customize the information in Lisp.  It is
850 merged with values from mailcap files by `mailcap-parse-mimetypes'.")
851
852 (defvar mailcap-mimetypes-parsed-p nil)
853
854 (defun mailcap-parse-mimetypes (&optional path force)
855   "Parse out all the mimetypes specified in a Unix-style path string PATH.
856 Components of PATH are separated by the `path-separator' character
857 appropriate for this system.  If PATH is omitted, use the value of
858 environment variable MIMETYPES if set; otherwise use a default path.
859 If FORCE, re-parse even if already parsed."
860   (interactive (list nil t))
861   (when (or (not mailcap-mimetypes-parsed-p)
862             force)
863     (cond
864      (path nil)
865      ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
866      ((memq system-type mailcap-poor-system-types)
867       (setq path '("~/mime.typ" "~/etc/mime.typ")))
868      (t (setq path
869               ;; mime.types seems to be the normal name, definitely so
870               ;; on current GNUish systems.  The search order follows
871               ;; that for mailcap.
872               '("~/.mime.types"
873                 "/etc/mime.types"
874                 "/usr/etc/mime.types"
875                 "/usr/local/etc/mime.types"
876                 "/usr/local/www/conf/mime.types"
877                 "~/.mime-types"
878                 "/etc/mime-types"
879                 "/usr/etc/mime-types"
880                 "/usr/local/etc/mime-types"
881                 "/usr/local/www/conf/mime-types"))))
882     (let ((fnames (reverse (if (stringp path)
883                                (delete "" (split-string path path-separator))
884                              path)))
885           fname)
886       (while fnames
887         (setq fname (car fnames))
888         (if (and (file-readable-p fname))
889             (mailcap-parse-mimetype-file fname))
890         (setq fnames (cdr fnames))))
891     (setq mailcap-mimetypes-parsed-p t)))
892
893 (defun mailcap-parse-mimetype-file (fname)
894   "Parse out a mime-types file FNAME."
895   (let (type                            ; The MIME type for this line
896         extns                           ; The extensions for this line
897         save-pos                        ; Misc. saved buffer positions
898         )
899     (with-temp-buffer
900       (insert-file-contents fname)
901       (mailcap-replace-regexp "#.*" "")
902       (mailcap-replace-regexp "\n+" "\n")
903       (mailcap-replace-regexp "[ \t]+$" "")
904       (goto-char (point-max))
905       (skip-chars-backward " \t\n")
906       (delete-region (point) (point-max))
907       (goto-char (point-min))
908       (while (not (eobp))
909         (skip-chars-forward " \t\n")
910         (setq save-pos (point))
911         (skip-chars-forward "^ \t\n")
912         (downcase-region save-pos (point))
913         (setq type (buffer-substring save-pos (point)))
914         (while (not (eolp))
915           (skip-chars-forward " \t")
916           (setq save-pos (point))
917           (skip-chars-forward "^ \t\n")
918           (setq extns (cons (buffer-substring save-pos (point)) extns)))
919         (while extns
920           (setq mailcap-mime-extensions
921                 (cons
922                  (cons (if (= (string-to-char (car extns)) ?.)
923                            (car extns)
924                          (concat "." (car extns))) type)
925                  mailcap-mime-extensions)
926                 extns (cdr extns)))))))
927
928 (defun mailcap-extension-to-mime (extn)
929   "Return the MIME content type of the file extensions EXTN."
930   (mailcap-parse-mimetypes)
931   (if (and (stringp extn)
932            (not (eq (string-to-char extn) ?.)))
933       (setq extn (concat "." extn)))
934   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
935
936 ;; Unused?
937 (defalias 'mailcap-command-p 'executable-find)
938
939 (defun mailcap-mime-types ()
940   "Return a list of MIME media types."
941   (mailcap-parse-mimetypes)
942   (mm-delete-duplicates
943    (nconc
944     (mapcar 'cdr mailcap-mime-extensions)
945     (apply
946      'nconc
947      (mapcar
948       (lambda (l)
949         (delq nil
950               (mapcar
951                (lambda (m)
952                  (let ((type (cdr (assq 'type (cdr m)))))
953                    (if (equal (cadr (split-string type "/"))
954                               "*")
955                        nil
956                      type)))
957                (cdr l))))
958       mailcap-mime-data)))))
959
960 (provide 'mailcap)
961
962 ;;; mailcap.el ends here