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