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