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