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