Importing Oort Gnus v0.03.
[elisp/gnus.git-] / 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 ;;;
291 ;;; Utility functions
292 ;;;
293
294 (defun mailcap-save-binary-file ()
295   (goto-char (point-min))
296   (unwind-protect
297       (let ((file (read-file-name
298                    "Filename to save as: "
299                    (or mailcap-download-directory "~/")))
300             (require-final-newline nil))
301         (write-region (point-min) (point-max) file))
302     (kill-buffer (current-buffer))))
303
304 (defvar mailcap-maybe-eval-warning
305   "*** WARNING ***
306
307 This MIME part contains untrusted and possibly harmful content.
308 If you evaluate the Emacs Lisp code contained in it, a lot of nasty
309 things can happen.  Please examine the code very carefully before you
310 instruct Emacs to evaluate it.  You can browse the buffer containing
311 the code using \\[scroll-other-window].
312
313 If you are unsure what to do, please answer \"no\"."
314   "Text of warning message displayed by `mailcap-maybe-eval'.
315 Make sure that this text consists only of few text lines.  Otherwise,
316 Gnus might fail to display all of it.")
317  
318 (defun mailcap-maybe-eval ()
319   "Maybe evaluate a buffer of Emacs Lisp code."
320   (let ((lisp-buffer (current-buffer)))
321     (goto-char (point-min))
322     (when
323         (save-window-excursion
324           (delete-other-windows)
325           (let ((buffer (get-buffer-create (generate-new-buffer-name
326                                             "*Warning*"))))
327             (unwind-protect
328                 (with-current-buffer buffer
329                   (insert (substitute-command-keys
330                            mailcap-maybe-eval-warning))
331                   (goto-char (point-min))
332                   (display-buffer buffer)
333                   (yes-or-no-p "This is potentially dangerous emacs-lisp code, evaluate it? "))
334               (kill-buffer buffer))))
335       (eval-buffer (current-buffer)))
336     (when (buffer-live-p lisp-buffer)
337       (with-current-buffer lisp-buffer
338         (emacs-lisp-mode)))))
339
340
341 ;;;
342 ;;; The mailcap parser
343 ;;;
344
345 (defun mailcap-replace-regexp (regexp to-string)
346   ;; Quiet replace-regexp.
347   (goto-char (point-min))
348   (while (re-search-forward regexp nil t)
349     (replace-match to-string t nil)))
350
351 (defvar mailcap-parsed-p nil)
352
353 (defun mailcap-parse-mailcaps (&optional path force)
354   "Parse out all the mailcaps specified in a path string PATH.
355 Components of PATH are separated by the `path-separator' character
356 appropriate for this system.  If FORCE, re-parse even if already
357 parsed.  If PATH is omitted, use the value of environment variable
358 MAILCAPS if set; otherwise (on Unix) use the path from RFC 1524, plus
359 /usr/local/etc/mailcap."
360   (interactive (list nil t))
361   (when (or (not mailcap-parsed-p)
362             force)
363     (cond
364      (path nil)
365      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
366      ((memq system-type '(ms-dos ms-windows windows-nt))
367       (setq path '("~/.mailcap" "~/mail.cap" "~/etc/mail.cap")))
368      (t (setq path
369               ;; This is per RFC 1524, specifically
370               ;; with /usr before /usr/local.
371               '("~/.mailcap" "/etc/mailcap" "/usr/etc/mailcap"
372                 "/usr/local/etc/mailcap"))))
373     (let ((fnames (reverse
374                    (if (stringp path)
375                        (delete "" (split-string path path-separator))
376                      path)))
377           fname)
378       (while fnames
379         (setq fname (car fnames))
380         (if (and (file-readable-p fname)
381                  (file-regular-p fname))
382             (mailcap-parse-mailcap fname))
383         (setq fnames (cdr fnames))))
384       (setq mailcap-parsed-p t)))
385
386 (defun mailcap-parse-mailcap (fname)
387   "Parse out the mailcap file specified by FNAME."
388   (let (major                           ; The major mime type (image/audio/etc)
389         minor                           ; The minor mime type (gif, basic, etc)
390         save-pos                        ; Misc saved positions used in parsing
391         viewer                          ; How to view this mime type
392         info                            ; Misc info about this mime type
393         )
394     (with-temp-buffer
395       (insert-file-contents fname)
396       (set-syntax-table mailcap-parse-args-syntax-table)
397       (mailcap-replace-regexp "#.*" "") ; Remove all comments
398       (mailcap-replace-regexp "\\\\[ \t]*\n" " ") ; And collapse spaces
399       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
400       (goto-char (point-max))
401       (skip-chars-backward " \t\n")
402       (delete-region (point) (point-max))
403       (while (not (bobp))
404         (skip-chars-backward " \t\n")
405         (beginning-of-line)
406         (setq save-pos (point)
407               info nil)
408         (skip-chars-forward "^/; \t\n")
409         (downcase-region save-pos (point))
410         (setq major (buffer-substring save-pos (point)))
411         (skip-chars-forward " \t")
412         (setq minor "")
413         (when (eq (char-after) ?/)
414           (forward-char)
415           (skip-chars-forward " \t")
416           (setq save-pos (point))
417           (skip-chars-forward "^; \t\n")
418           (downcase-region save-pos (point))
419           (setq minor
420                 (cond
421                  ((eq ?* (or (char-after save-pos) 0)) ".*")
422                  ((= (point) save-pos) ".*")
423                  (t (regexp-quote (buffer-substring save-pos (point)))))))
424         (skip-chars-forward " \t")
425         ;;; Got the major/minor chunks, now for the viewers/etc
426         ;;; The first item _must_ be a viewer, according to the
427         ;;; RFC for mailcap files (#1524)
428         (setq viewer "")
429         (when (eq (char-after) ?\;)
430           (forward-char)
431           (skip-chars-forward " \t")
432           (setq save-pos (point))
433           (skip-chars-forward "^;\n")
434           ;; skip \;
435           (while (eq (char-before) ?\\)
436             (backward-delete-char 1)
437             (forward-char)
438             (skip-chars-forward "^;\n"))
439           (if (eq (or (char-after save-pos) 0) ?')
440               (setq viewer (progn
441                              (narrow-to-region (1+ save-pos) (point))
442                              (goto-char (point-min))
443                              (prog1
444                                  (read (current-buffer))
445                                (goto-char (point-max))
446                                (widen))))
447             (setq viewer (buffer-substring save-pos (point)))))
448         (setq save-pos (point))
449         (end-of-line)
450         (unless (equal viewer "")
451           (setq info (nconc (list (cons 'viewer viewer)
452                                   (cons 'type (concat major "/"
453                                                       (if (string= minor ".*")
454                                                           "*" minor))))
455                             (mailcap-parse-mailcap-extras save-pos (point))))
456           (mailcap-mailcap-entry-passes-test info)
457           (mailcap-add-mailcap-entry major minor info))
458         (beginning-of-line)))))
459
460 (defun mailcap-parse-mailcap-extras (st nd)
461   "Grab all the extra stuff from a mailcap entry."
462   (let (
463         name                            ; From name=
464         value                           ; its value
465         results                         ; Assoc list of results
466         name-pos                        ; Start of XXXX= position
467         val-pos                         ; Start of value position
468         done                            ; Found end of \'d ;s?
469         )
470     (save-restriction
471       (narrow-to-region st nd)
472       (goto-char (point-min))
473       (skip-chars-forward " \n\t;")
474       (while (not (eobp))
475         (setq done nil)
476         (setq name-pos (point))
477         (skip-chars-forward "^ \n\t=;")
478         (downcase-region name-pos (point))
479         (setq name (buffer-substring name-pos (point)))
480         (skip-chars-forward " \t\n")
481         (if (not (eq (char-after (point)) ?=)) ; There is no value
482             (setq value t)
483           (skip-chars-forward " \t\n=")
484           (setq val-pos (point))
485           (if (memq (char-after val-pos) '(?\" ?'))
486               (progn
487                 (setq val-pos (1+ val-pos))
488                 (condition-case nil
489                     (progn
490                       (forward-sexp 1)
491                       (backward-char 1))
492                   (error (goto-char (point-max)))))
493             (while (not done)
494               (skip-chars-forward "^;")
495               (if (eq (char-after (1- (point))) ?\\ )
496                   (progn
497                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
498                     (skip-chars-forward ";"))
499                 (setq done t))))
500           (setq value (buffer-substring val-pos (point))))
501         (setq results (cons (cons name value) results))
502         (skip-chars-forward " \";\n\t"))
503       results)))
504
505 (defun mailcap-mailcap-entry-passes-test (info)
506   "Return non-nil iff mailcap entry INFO passes its test clause.
507 Also return non-nil if no test clause is present."
508   (let ((test (assq 'test info))        ; The test clause
509         status)
510     (setq status (and test (split-string (cdr test) " ")))
511     (if (and (or (assoc "needsterm" info)
512                  (assoc "needsterminal" info)
513                  (assoc "needsx11" info))
514              (not (getenv "DISPLAY")))
515         (setq status nil)
516       (cond
517        ((and (equal (nth 0 status) "test")
518              (equal (nth 1 status) "-n")
519              (or (equal (nth 2 status) "$DISPLAY")
520                  (equal (nth 2 status) "\"$DISPLAY\"")))
521         (setq status (if (getenv "DISPLAY") t nil)))
522        ((and (equal (nth 0 status) "test")
523              (equal (nth 1 status) "-z")
524              (or (equal (nth 2 status) "$DISPLAY")
525                  (equal (nth 2 status) "\"$DISPLAY\"")))
526         (setq status (if (getenv "DISPLAY") nil t)))
527        (test nil)
528        (t nil)))
529     (and test (listp test) (setcdr test status))))
530
531 ;;;
532 ;;; The action routines.
533 ;;;
534
535 (defun mailcap-possible-viewers (major minor)
536   "Return a list of possible viewers from MAJOR for minor type MINOR."
537   (let ((exact '())
538         (wildcard '()))
539     (while major
540       (cond
541        ((equal (car (car major)) minor)
542         (setq exact (cons (cdr (car major)) exact)))
543        ((and minor (string-match (concat "^" (car (car major)) "$") minor))
544         (setq wildcard (cons (cdr (car major)) wildcard))))
545       (setq major (cdr major)))
546     (nconc exact wildcard)))
547
548 (defun mailcap-unescape-mime-test (test type-info)
549   (let (save-pos save-chr subst)
550     (cond
551      ((symbolp test) test)
552      ((and (listp test) (symbolp (car test))) test)
553      ((or (stringp test)
554           (and (listp test) (stringp (car test))
555                (setq test (mapconcat 'identity test " "))))
556       (with-temp-buffer
557         (insert test)
558         (goto-char (point-min))
559         (while (not (eobp))
560           (skip-chars-forward "^%")
561           (if (/= (- (point)
562                      (progn (skip-chars-backward "\\\\")
563                             (point)))
564                   0)                    ; It is an escaped %
565               (progn
566                 (delete-char 1)
567                 (skip-chars-forward "%."))
568             (setq save-pos (point))
569             (skip-chars-forward "%")
570             (setq save-chr (char-after (point)))
571             ;; Escapes:
572             ;; %s: name of a file for the body data
573             ;; %t: content-type
574             ;; %{<parameter name}: value of parameter in mailcap entry
575             ;; %n: number of sub-parts for multipart content-type
576             ;; %F: a set of content-type/filename pairs for multiparts
577             (cond
578              ((null save-chr) nil)
579              ((= save-chr ?t)
580               (delete-region save-pos (progn (forward-char 1) (point)))
581               (insert (or (cdr (assq 'type type-info)) "\"\"")))
582              ((memq save-chr '(?M ?n ?F))
583               (delete-region save-pos (progn (forward-char 1) (point)))
584               (insert "\"\""))
585              ((= save-chr ?{)
586               (forward-char 1)
587               (skip-chars-forward "^}")
588               (downcase-region (+ 2 save-pos) (point))
589               (setq subst (buffer-substring (+ 2 save-pos) (point)))
590               (delete-region save-pos (1+ (point)))
591               (insert (or (cdr (assoc subst type-info)) "\"\"")))
592              (t nil))))
593         (buffer-string)))
594      (t (error "Bad value to mailcap-unescape-mime-test: %s" test)))))
595
596 (defvar mailcap-viewer-test-cache nil)
597
598 (defun mailcap-viewer-passes-test (viewer-info type-info)
599   "Return non-nil iff viewer specified by VIEWER-INFO passes its test clause.
600 Also retun non-nil if it has no test clause.  TYPE-INFO is an argument
601 to supply to the test."
602   (let* ((test-info (assq 'test viewer-info))
603          (test (cdr test-info))
604          (otest test)
605          (viewer (cdr (assoc 'viewer viewer-info)))
606          (default-directory (expand-file-name "~/"))
607          status parsed-test cache result)
608     (if (setq cache (assoc test mailcap-viewer-test-cache))
609         (cadr cache)
610       (setq
611        result
612        (cond
613         ((not test-info) t)             ; No test clause
614         ((not test) nil)                ; Already failed test
615         ((eq test t) t)                 ; Already passed test
616         ((functionp test)               ; Lisp function as test
617          (funcall test type-info))
618         ((and (symbolp test)            ; Lisp variable as test
619               (boundp test))
620          (symbol-value test))
621         ((and (listp test)              ; List to be eval'd
622               (symbolp (car test)))
623          (eval test))
624         (t
625          (setq test (mailcap-unescape-mime-test test type-info)
626                test (list shell-file-name nil nil nil
627                           shell-command-switch test)
628                status (apply 'call-process test))
629          (= 0 status))))
630       (push (list otest result) mailcap-viewer-test-cache)
631       result)))
632
633 (defun mailcap-add-mailcap-entry (major minor info)
634   (let ((old-major (assoc major mailcap-mime-data)))
635     (if (null old-major)                ; New major area
636         (setq mailcap-mime-data
637               (cons (cons major (list (cons minor info)))
638                     mailcap-mime-data))
639        (let ((cur-minor (assoc minor old-major)))
640         (cond
641          ((or (null cur-minor)          ; New minor area, or
642               (assq 'test info))        ; Has a test, insert at beginning
643           (setcdr old-major (cons (cons minor info) (cdr old-major))))
644          ((and (not (assq 'test info))  ; No test info, replace completely
645                (not (assq 'test cur-minor))
646                (equal (assq 'viewer info)  ; Keep alternative viewer
647                       (assq 'viewer cur-minor)))
648           (setcdr cur-minor info))
649          (t
650           (setcdr old-major (cons (cons minor info) (cdr old-major))))))
651       )))
652
653 (defun mailcap-add (type viewer &optional test)
654   "Add VIEWER as a handler for TYPE.
655 If TEST is not given, it defaults to t."
656   (let ((tl (split-string type "/")))
657     (when (or (not (car tl))
658               (not (cadr tl)))
659       (error "%s is not a valid MIME type" type))
660     (mailcap-add-mailcap-entry
661      (car tl) (cadr tl)
662      `((viewer . ,viewer)
663        (test . ,(if test test t))
664        (type . ,type)))))
665
666 ;;;
667 ;;; The main whabbo
668 ;;;
669
670 (defun mailcap-viewer-lessp (x y)
671   "Return t iff viewer X is more desirable than viewer Y."
672   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
673         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
674         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
675         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
676     (cond
677      ((and x-wild (not y-wild))
678       nil)
679      ((and (not x-wild) y-wild)
680       t)
681      ((and (not y-lisp) x-lisp)
682       t)
683      (t nil))))
684
685 (defun mailcap-mime-info (string &optional request)
686   "Get the MIME viewer command for STRING, return nil if none found.
687 Expects a complete content-type header line as its argument.
688
689 Second argument REQUEST specifies what information to return.  If it is
690 nil or the empty string, the viewer (second field of the mailcap
691 entry) will be returned.  If it is a string, then the mailcap field
692 corresponding to that string will be returned (print, description,
693 whatever).  If a number, then all the information for this specific
694 viewer is returned.  If `all', then all possible viewers for
695 this type is returned."
696   (let (
697         major                           ; Major encoding (text, etc)
698         minor                           ; Minor encoding (html, etc)
699         info                            ; Other info
700         save-pos                        ; Misc. position during parse
701         major-info                      ; (assoc major mailcap-mime-data)
702         minor-info                      ; (assoc minor major-info)
703         test                            ; current test proc.
704         viewers                         ; Possible viewers
705         passed                          ; Viewers that passed the test
706         viewer                          ; The one and only viewer
707         ctl)
708     (save-excursion
709       (setq ctl (mail-header-parse-content-type (or string "text/plain")))
710       (setq major (split-string (car ctl) "/"))
711       (setq minor (cadr major)
712             major (car major))
713       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
714         (when (setq viewers (mailcap-possible-viewers major-info minor))
715           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
716                                                (cdr a)))
717                              (cdr ctl)))
718           (while viewers
719             (if (mailcap-viewer-passes-test (car viewers) info)
720                 (setq passed (cons (car viewers) passed)))
721             (setq viewers (cdr viewers)))
722           (setq passed (sort passed 'mailcap-viewer-lessp))
723           (setq viewer (car passed))))
724       (when (and (stringp (cdr (assq 'viewer viewer)))
725                  passed)
726         (setq viewer (car passed)))
727       (cond
728        ((and (null viewer) (not (equal major "default")) request)
729         (mailcap-mime-info "default" request))
730        ((or (null request) (equal request ""))
731         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
732        ((stringp request)
733         (if (or (eq request 'test) (eq request 'viewer))
734             (mailcap-unescape-mime-test
735              (cdr-safe (assoc request viewer)) info)))
736        ((eq request 'all)
737         passed)
738        (t
739         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
740         (setq viewer (copy-sequence viewer))
741         (let ((view (assq 'viewer viewer))
742               (test (assq 'test viewer)))
743           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
744           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
745         viewer)))))
746
747 ;;;
748 ;;; Experimental MIME-types parsing
749 ;;;
750
751 (defvar mailcap-mime-extensions
752   '((""        . "text/plain")
753     (".abs"   . "audio/x-mpeg")
754     (".aif"   . "audio/aiff")
755     (".aifc"  . "audio/aiff")
756     (".aiff"  . "audio/aiff")
757     (".ano"   . "application/x-annotator")
758     (".au"    . "audio/ulaw")
759     (".avi"   . "video/x-msvideo")
760     (".bcpio" . "application/x-bcpio")
761     (".bin"   . "application/octet-stream")
762     (".cdf"   . "application/x-netcdr")
763     (".cpio"  . "application/x-cpio")
764     (".csh"   . "application/x-csh")
765     (".css"   . "text/css")
766     (".dvi"   . "application/x-dvi")
767     (".diff"  . "text/x-patch")
768     (".el"    . "application/emacs-lisp")
769     (".eps"   . "application/postscript")
770     (".etx"   . "text/x-setext")
771     (".exe"   . "application/octet-stream")
772     (".fax"   . "image/x-fax")
773     (".gif"   . "image/gif")
774     (".hdf"   . "application/x-hdf")
775     (".hqx"   . "application/mac-binhex40")
776     (".htm"   . "text/html")
777     (".html"  . "text/html")
778     (".icon"  . "image/x-icon")
779     (".ief"   . "image/ief")
780     (".jpg"   . "image/jpeg")
781     (".macp"  . "image/x-macpaint")
782     (".man"   . "application/x-troff-man")
783     (".me"    . "application/x-troff-me")
784     (".mif"   . "application/mif")
785     (".mov"   . "video/quicktime")
786     (".movie" . "video/x-sgi-movie")
787     (".mp2"   . "audio/x-mpeg")
788     (".mp3"   . "audio/x-mpeg")
789     (".mp2a"  . "audio/x-mpeg2")
790     (".mpa"   . "audio/x-mpeg")
791     (".mpa2"  . "audio/x-mpeg2")
792     (".mpe"   . "video/mpeg")
793     (".mpeg"  . "video/mpeg")
794     (".mpega" . "audio/x-mpeg")
795     (".mpegv" . "video/mpeg")
796     (".mpg"   . "video/mpeg")
797     (".mpv"   . "video/mpeg")
798     (".ms"    . "application/x-troff-ms")
799     (".nc"    . "application/x-netcdf")
800     (".nc"    . "application/x-netcdf")
801     (".oda"   . "application/oda")
802     (".patch" . "text/x-patch")
803     (".pbm"   . "image/x-portable-bitmap")
804     (".pdf"   . "application/pdf")
805     (".pgm"   . "image/portable-graymap")
806     (".pict"  . "image/pict")
807     (".png"   . "image/png")
808     (".pnm"   . "image/x-portable-anymap")
809     (".ppm"   . "image/portable-pixmap")
810     (".ps"    . "application/postscript")
811     (".qt"    . "video/quicktime")
812     (".ras"   . "image/x-raster")
813     (".rgb"   . "image/x-rgb")
814     (".rtf"   . "application/rtf")
815     (".rtx"   . "text/richtext")
816     (".sh"    . "application/x-sh")
817     (".sit"   . "application/x-stuffit")
818     (".siv"   . "application/sieve")
819     (".snd"   . "audio/basic")
820     (".src"   . "application/x-wais-source")
821     (".tar"   . "archive/tar")
822     (".tcl"   . "application/x-tcl")
823     (".tex"   . "application/x-tex")
824     (".texi"  . "application/texinfo")
825     (".tga"   . "image/x-targa")
826     (".tif"   . "image/tiff")
827     (".tiff"  . "image/tiff")
828     (".tr"    . "application/x-troff")
829     (".troff" . "application/x-troff")
830     (".tsv"   . "text/tab-separated-values")
831     (".txt"   . "text/plain")
832     (".vbs"   . "video/mpeg")
833     (".vox"   . "audio/basic")
834     (".vrml"  . "x-world/x-vrml")
835     (".wav"   . "audio/x-wav")
836     (".xls"   . "application/vnd.ms-excel")
837     (".wrl"   . "x-world/x-vrml")
838     (".xbm"   . "image/xbm")
839     (".xpm"   . "image/xpm")
840     (".xwd"   . "image/windowdump")
841     (".zip"   . "application/zip")
842     (".ai"    . "application/postscript")
843     (".jpe"   . "image/jpeg")
844     (".jpeg"  . "image/jpeg"))
845   "An alist of file extensions and corresponding MIME content-types.
846 This exists for you to customize the information in Lisp.  It is
847 merged with values from mailcap files by `mailcap-parse-mimetypes'.")
848
849 (defvar mailcap-mimetypes-parsed-p nil)
850
851 (defun mailcap-parse-mimetypes (&optional path force)
852   "Parse out all the mimetypes specified in a Unix-style path string PATH.
853 Components of PATH are separated by the `path-separator' character
854 appropriate for this system.  If PATH is omitted, use the value of
855 environment variable MIMETYPES if set; otherwise use a default path.
856 If FORCE, re-parse even if already parsed."
857   (interactive (list nil t))
858   (when (or (not mailcap-mimetypes-parsed-p)
859             force)
860     (cond
861      (path nil)
862      ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
863      ((memq system-type '(ms-dos ms-windows windows-nt))
864       (setq path '("~/mime.typ" "~/etc/mime.typ")))
865      (t (setq path
866               ;; mime.types seems to be the normal name, definitely so
867               ;; on current GNUish systems.  The search order follows
868               ;; that for mailcap.
869               '("~/.mime.types"
870                 "/etc/mime.types"
871                 "/usr/etc/mime.types"
872                 "/usr/local/etc/mime.types"
873                 "/usr/local/www/conf/mime.types"
874                 "~/.mime-types"
875                 "/etc/mime-types"
876                 "/usr/etc/mime-types"
877                 "/usr/local/etc/mime-types"
878                 "/usr/local/www/conf/mime-types"))))
879     (let ((fnames (reverse (if (stringp path)
880                                (delete "" (split-string path path-separator))
881                              path)))
882           fname)
883       (while fnames
884         (setq fname (car fnames))
885         (if (and (file-readable-p fname))
886             (mailcap-parse-mimetype-file fname))
887         (setq fnames (cdr fnames))))
888     (setq mailcap-mimetypes-parsed-p t)))
889
890 (defun mailcap-parse-mimetype-file (fname)
891   "Parse out a mime-types file FNAME."
892   (let (type                            ; The MIME type for this line
893         extns                           ; The extensions for this line
894         save-pos                        ; Misc. saved buffer positions
895         )
896     (with-temp-buffer
897       (insert-file-contents fname)
898       (mailcap-replace-regexp "#.*" "")
899       (mailcap-replace-regexp "\n+" "\n")
900       (mailcap-replace-regexp "[ \t]+$" "")
901       (goto-char (point-max))
902       (skip-chars-backward " \t\n")
903       (delete-region (point) (point-max))
904       (goto-char (point-min))
905       (while (not (eobp))
906         (skip-chars-forward " \t\n")
907         (setq save-pos (point))
908         (skip-chars-forward "^ \t\n")
909         (downcase-region save-pos (point))
910         (setq type (buffer-substring save-pos (point)))
911         (while (not (eolp))
912           (skip-chars-forward " \t")
913           (setq save-pos (point))
914           (skip-chars-forward "^ \t\n")
915           (setq extns (cons (buffer-substring save-pos (point)) extns)))
916         (while extns
917           (setq mailcap-mime-extensions
918                 (cons
919                  (cons (if (= (string-to-char (car extns)) ?.)
920                            (car extns)
921                          (concat "." (car extns))) type)
922                  mailcap-mime-extensions)
923                 extns (cdr extns)))))))
924
925 (defun mailcap-extension-to-mime (extn)
926   "Return the MIME content type of the file extensions EXTN."
927   (mailcap-parse-mimetypes)
928   (if (and (stringp extn)
929            (not (eq (string-to-char extn) ?.)))
930       (setq extn (concat "." extn)))
931   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
932
933 ;; Unused?
934 (defalias 'mailcap-command-p 'executable-find)
935
936 (defun mailcap-mime-types ()
937   "Return a list of MIME media types."
938   (mailcap-parse-mimetypes)
939   (mm-delete-duplicates
940    (nconc
941     (mapcar 'cdr mailcap-mime-extensions)
942     (apply
943      'nconc
944      (mapcar
945       (lambda (l)
946         (delq nil
947               (mapcar
948                (lambda (m)
949                  (let ((type (cdr (assq 'type (cdr m)))))
950                    (if (equal (cadr (split-string type "/"))
951                               "*")
952                        nil
953                      type)))
954                (cdr l))))
955       mailcap-mime-data)))))
956
957 (provide 'mailcap)
958
959 ;;; mailcap.el ends here