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