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