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