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