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