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