(mailcap-parse-mimetypes): Add ...mime.types.
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- Functions for displaying MIME parts
2 ;; Copyright (C) 1998,99 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 unix-style path string PATH.
309 If FORCE, re-parse even if already parsed."
310   (interactive (list nil t))
311   (when (or (not mailcap-parsed-p)
312             force)
313     (cond
314      (path nil)
315      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
316      ((memq system-type '(ms-dos ms-windows windows-nt))
317       (setq path (mapconcat 'expand-file-name
318                             '("~/mail.cap" "~/etc/mail.cap" "~/.mailcap")
319                             ";")))
320      (t (setq path (mapconcat 'expand-file-name
321                               '("~/.mailcap"
322                                 "/etc/mailcap:/usr/etc/mailcap"
323                                 "/usr/local/etc/mailcap") ":"))))
324     (let ((fnames (reverse
325                    (split-string
326                     path (if (memq system-type
327                                    '(ms-dos ms-windows windows-nt))
328                              ";"
329                            ":"))))
330           fname)
331       (while fnames
332         (setq fname (car fnames))
333         (if (and (file-exists-p fname) (file-readable-p fname)
334                  (file-regular-p fname))
335             (mailcap-parse-mailcap (car fnames)))
336         (setq fnames (cdr fnames))))
337     (setq mailcap-parsed-p t)))
338
339 (defun mailcap-parse-mailcap (fname)
340   ;; Parse out the mailcap file specified by FNAME
341   (let (major                           ; The major mime type (image/audio/etc)
342         minor                           ; The minor mime type (gif, basic, etc)
343         save-pos                        ; Misc saved positions used in parsing
344         viewer                          ; How to view this mime type
345         info                            ; Misc info about this mime type
346         )
347     (with-temp-buffer
348       (insert-file-contents fname)
349       (set-syntax-table mailcap-parse-args-syntax-table)
350       (mailcap-replace-regexp "#.*" "") ; Remove all comments
351       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
352       (mailcap-replace-regexp "\\\\[ \t\n]+" " ") ; And collapse spaces
353       (mailcap-replace-regexp (concat (regexp-quote "\\") "[ \t]*\n") "")
354       (goto-char (point-max))
355       (skip-chars-backward " \t\n")
356       (delete-region (point) (point-max))
357       (goto-char (point-min))
358       (while (not (eobp))
359         (skip-chars-forward " \t\n")
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\n")
366         (setq minor "")
367         (when (eq (char-after) ?/)
368           (forward-char)
369           (skip-chars-forward " \t\n")
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\n")
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\n")
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
413 (defun mailcap-parse-mailcap-extras (st nd)
414   ;; Grab all the extra stuff from a mailcap entry
415   (let (
416         name                            ; From name=
417         value                           ; its value
418         results                         ; Assoc list of results
419         name-pos                        ; Start of XXXX= position
420         val-pos                         ; Start of value position
421         done                            ; Found end of \'d ;s?
422         )
423     (save-restriction
424       (narrow-to-region st nd)
425       (goto-char (point-min))
426       (skip-chars-forward " \n\t;")
427       (while (not (eobp))
428         (setq done nil)
429         (setq name-pos (point))
430         (skip-chars-forward "^ \n\t=;")
431         (downcase-region name-pos (point))
432         (setq name (buffer-substring name-pos (point)))
433         (skip-chars-forward " \t\n")
434         (if (not (eq (char-after (point)) ?=)) ; There is no value
435             (setq value t)
436           (skip-chars-forward " \t\n=")
437           (setq val-pos (point))
438           (if (memq (char-after val-pos) '(?\" ?'))
439               (progn
440                 (setq val-pos (1+ val-pos))
441                 (condition-case nil
442                     (progn
443                       (forward-sexp 1)
444                       (backward-char 1))
445                   (error (goto-char (point-max)))))
446             (while (not done)
447               (skip-chars-forward "^;")
448               (if (eq (char-after (1- (point))) ?\\ )
449                   (progn
450                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
451                     (skip-chars-forward ";"))
452                 (setq done t))))
453           (setq value (buffer-substring val-pos (point))))
454         (setq results (cons (cons name value) results))
455         (skip-chars-forward " \";\n\t"))
456       results)))
457
458 (defun mailcap-mailcap-entry-passes-test (info)
459   ;; Return t iff a mailcap entry passes its test clause or no test
460   ;; clause is present.
461   (let (status                          ; Call-process-regions return value
462         (test (assq 'test info))        ; The test clause
463         )
464     (setq status (and test (split-string (cdr test) " ")))
465     (if (and (or (assoc "needsterm" info)
466                  (assoc "needsterminal" info)
467                  (assoc "needsx11" info))
468              (not (getenv "DISPLAY")))
469         (setq status nil)
470       (cond
471        ((and (equal (nth 0 status) "test")
472              (equal (nth 1 status) "-n")
473              (or (equal (nth 2 status) "$DISPLAY")
474                  (equal (nth 2 status) "\"$DISPLAY\"")))
475         (setq status (if (getenv "DISPLAY") t nil)))
476        ((and (equal (nth 0 status) "test")
477              (equal (nth 1 status) "-z")
478              (or (equal (nth 2 status) "$DISPLAY")
479                  (equal (nth 2 status) "\"$DISPLAY\"")))
480         (setq status (if (getenv "DISPLAY") nil t)))
481        (test nil)
482        (t nil)))
483     (and test (listp test) (setcdr test status))))
484
485 ;;;
486 ;;; The action routines.
487 ;;;
488
489 (defun mailcap-possible-viewers (major minor)
490   ;; Return a list of possible viewers from MAJOR for minor type MINOR
491   (let ((exact '())
492         (wildcard '()))
493     (while major
494       (cond
495        ((equal (car (car major)) minor)
496         (setq exact (cons (cdr (car major)) exact)))
497        ((and minor (string-match (car (car major)) minor))
498         (setq wildcard (cons (cdr (car major)) wildcard))))
499       (setq major (cdr major)))
500     (nconc (nreverse exact) (nreverse wildcard))))
501
502 (defun mailcap-unescape-mime-test (test type-info)
503   (let (save-pos save-chr subst)
504     (cond
505      ((symbolp test) test)
506      ((and (listp test) (symbolp (car test))) test)
507      ((or (stringp test)
508           (and (listp test) (stringp (car test))
509                (setq test (mapconcat 'identity test " "))))
510       (with-temp-buffer
511         (insert test)
512         (goto-char (point-min))
513         (while (not (eobp))
514           (skip-chars-forward "^%")
515           (if (/= (- (point)
516                      (progn (skip-chars-backward "\\\\")
517                             (point)))
518                   0)                    ; It is an escaped %
519               (progn
520                 (delete-char 1)
521                 (skip-chars-forward "%."))
522             (setq save-pos (point))
523             (skip-chars-forward "%")
524             (setq save-chr (char-after (point)))
525             (cond
526              ((null save-chr) nil)
527              ((= save-chr ?t)
528               (delete-region save-pos (progn (forward-char 1) (point)))
529               (insert (or (cdr (assq 'type type-info)) "\"\"")))
530              ((= save-chr ?M)
531               (delete-region save-pos (progn (forward-char 1) (point)))
532               (insert "\"\""))
533              ((= save-chr ?n)
534               (delete-region save-pos (progn (forward-char 1) (point)))
535               (insert "\"\""))
536              ((= save-chr ?F)
537               (delete-region save-pos (progn (forward-char 1) (point)))
538               (insert "\"\""))
539              ((= save-chr ?{)
540               (forward-char 1)
541               (skip-chars-forward "^}")
542               (downcase-region (+ 2 save-pos) (point))
543               (setq subst (buffer-substring (+ 2 save-pos) (point)))
544               (delete-region save-pos (1+ (point)))
545               (insert (or (cdr (assoc subst type-info)) "\"\"")))
546              (t nil))))
547         (buffer-string)))
548      (t (error "Bad value to mailcap-unescape-mime-test. %s" test)))))
549
550 (defvar mailcap-viewer-test-cache nil)
551
552 (defun mailcap-viewer-passes-test (viewer-info type-info)
553   ;; Return non-nil iff the viewer specified by VIEWER-INFO passes its
554   ;; test clause (if any).
555   (let* ((test-info (assq 'test viewer-info))
556          (test (cdr test-info))
557          (otest test)
558          (viewer (cdr (assoc 'viewer viewer-info)))
559          (default-directory (expand-file-name "~/"))
560          status parsed-test cache result)
561     (if (setq cache (assoc test mailcap-viewer-test-cache))
562         (cadr cache)
563       (setq
564        result
565        (cond
566         ((not test-info) t)             ; No test clause
567         ((not test) nil)                ; Already failed test
568         ((eq test t) t)                 ; Already passed test
569         ((and (symbolp test)            ; Lisp function as test
570               (fboundp test))
571          (funcall test type-info))
572         ((and (symbolp test)            ; Lisp variable as test
573               (boundp test))
574          (symbol-value test))
575         ((and (listp test)              ; List to be eval'd
576               (symbolp (car test)))
577          (eval test))
578         (t
579          (setq test (mailcap-unescape-mime-test test type-info)
580                test (list shell-file-name nil nil nil
581                           shell-command-switch test)
582                status (apply 'call-process test))
583          (= 0 status))))
584       (push (list otest result) mailcap-viewer-test-cache)
585       result)))
586
587 (defun mailcap-add-mailcap-entry (major minor info)
588   (let ((old-major (assoc major mailcap-mime-data)))
589     (if (null old-major)                ; New major area
590         (setq mailcap-mime-data
591               (cons (cons major (list (cons minor info)))
592                     mailcap-mime-data))
593       (let ((cur-minor (assoc minor old-major)))
594         (cond
595          ((or (null cur-minor)          ; New minor area, or
596               (assq 'test info))        ; Has a test, insert at beginning
597           (setcdr old-major (cons (cons minor info) (cdr old-major))))
598          ((and (not (assq 'test info))  ; No test info, replace completely
599                (not (assq 'test cur-minor)))
600           (setcdr cur-minor info))
601          (t
602           (setcdr old-major (cons (cons minor info) (cdr old-major)))))))))
603
604 (defun mailcap-add (type viewer &optional test)
605   "Add VIEWER as a handler for TYPE.
606 If TEST is not given, it defaults to t."
607   (let ((tl (split-string type "/")))
608     (when (or (not (car tl))
609               (not (cadr tl)))
610       (error "%s is not a valid MIME type" type))
611     (mailcap-add-mailcap-entry
612      (car tl) (cadr tl)
613      `((viewer . ,viewer)
614        (test . ,(if test test t))
615        (type . ,type)))))
616
617 ;;;
618 ;;; The main whabbo
619 ;;;
620
621 (defun mailcap-viewer-lessp (x y)
622   ;; Return t iff viewer X is more desirable than viewer Y
623   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
624         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
625         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
626         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
627     (cond
628      ((and x-wild (not y-wild))
629       nil)
630      ((and (not x-wild) y-wild)
631       t)
632      ((and (not y-lisp) x-lisp)
633       t)
634      (t nil))))
635
636 (defun mailcap-mime-info (string &optional request)
637   "Get the MIME viewer command for STRING, return nil if none found.
638 Expects a complete content-type header line as its argument.
639
640 Second argument REQUEST specifies what information to return.  If it is
641 nil or the empty string, the viewer (second field of the mailcap
642 entry) will be returned.  If it is a string, then the mailcap field
643 corresponding to that string will be returned (print, description,
644 whatever).  If a number, then all the information for this specific
645 viewer is returned.  If `all', then all possible viewers for
646 this type is returned."
647   (let (
648         major                           ; Major encoding (text, etc)
649         minor                           ; Minor encoding (html, etc)
650         info                            ; Other info
651         save-pos                        ; Misc. position during parse
652         major-info                      ; (assoc major mailcap-mime-data)
653         minor-info                      ; (assoc minor major-info)
654         test                            ; current test proc.
655         viewers                         ; Possible viewers
656         passed                          ; Viewers that passed the test
657         viewer                          ; The one and only viewer
658         ctl)
659     (save-excursion
660       (setq ctl (mail-header-parse-content-type (or string "text/plain")))
661       (setq major (split-string (car ctl) "/"))
662       (setq minor (cadr major)
663             major (car major))
664       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
665         (when (setq viewers (mailcap-possible-viewers major-info minor))
666           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
667                                                (cdr a)))
668                              (cdr ctl)))
669           (while viewers
670             (if (mailcap-viewer-passes-test (car viewers) info)
671                 (setq passed (cons (car viewers) passed)))
672             (setq viewers (cdr viewers)))
673           (setq passed (sort (nreverse passed) 'mailcap-viewer-lessp))
674           (setq viewer (car passed))))
675       (when (and (stringp (cdr (assq 'viewer viewer)))
676                  passed)
677         (setq viewer (car passed)))
678       (cond
679        ((and (null viewer) (not (equal major "default")) request)
680         (mailcap-mime-info "default" request))
681        ((or (null request) (equal request ""))
682         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
683        ((stringp request)
684         (if (or (eq request 'test) (eq request 'viewer))
685             (mailcap-unescape-mime-test
686              (cdr-safe (assoc request viewer)) info)))
687        ((eq request 'all)
688         passed)
689        (t
690         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
691         (setq viewer (copy-sequence viewer))
692         (let ((view (assq 'viewer viewer))
693               (test (assq 'test viewer)))
694           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
695           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
696         viewer)))))
697
698 ;;;
699 ;;; Experimental MIME-types parsing
700 ;;;
701
702 (defvar mailcap-mime-extensions
703   '((""          . "text/plain")
704     (".abs"      . "audio/x-mpeg")
705     (".aif"      . "audio/aiff")
706     (".aifc"     . "audio/aiff")
707     (".aiff"     . "audio/aiff")
708     (".ano"      . "application/x-annotator")
709     (".au"       . "audio/ulaw")
710     (".avi"      . "video/x-msvideo")
711     (".bcpio"    . "application/x-bcpio")
712     (".bin"      . "application/octet-stream")
713     (".cdf"      . "application/x-netcdr")
714     (".cpio"     . "application/x-cpio")
715     (".csh"      . "application/x-csh")
716     (".dvi"      . "application/x-dvi")
717     (".diff"     . "text/x-patch")
718     (".el"       . "application/emacs-lisp")
719     (".eps"      . "application/postscript")
720     (".etx"      . "text/x-setext")
721     (".exe"      . "application/octet-stream")
722     (".fax"      . "image/x-fax")
723     (".gif"      . "image/gif")
724     (".hdf"      . "application/x-hdf")
725     (".hqx"      . "application/mac-binhex40")
726     (".htm"      . "text/html")
727     (".html"     . "text/html")
728     (".icon"     . "image/x-icon")
729     (".ief"      . "image/ief")
730     (".jpg"      . "image/jpeg")
731     (".macp"     . "image/x-macpaint")
732     (".man"      . "application/x-troff-man")
733     (".me"       . "application/x-troff-me")
734     (".mif"      . "application/mif")
735     (".mov"      . "video/quicktime")
736     (".movie"    . "video/x-sgi-movie")
737     (".mp2"      . "audio/x-mpeg")
738     (".mp3"      . "audio/x-mpeg")
739     (".mp2a"     . "audio/x-mpeg2")
740     (".mpa"      . "audio/x-mpeg")
741     (".mpa2"     . "audio/x-mpeg2")
742     (".mpe"      . "video/mpeg")
743     (".mpeg"     . "video/mpeg")
744     (".mpega"    . "audio/x-mpeg")
745     (".mpegv"    . "video/mpeg")
746     (".mpg"      . "video/mpeg")
747     (".mpv"      . "video/mpeg")
748     (".ms"       . "application/x-troff-ms")
749     (".nc"       . "application/x-netcdf")
750     (".nc"       . "application/x-netcdf")
751     (".oda"      . "application/oda")
752     (".patch"    . "text/x-patch")
753     (".pbm"      . "image/x-portable-bitmap")
754     (".pdf"      . "application/pdf")
755     (".pgm"      . "image/portable-graymap")
756     (".pict"     . "image/pict")
757     (".png"      . "image/png")
758     (".pnm"      . "image/x-portable-anymap")
759     (".ppm"      . "image/portable-pixmap")
760     (".ps"       . "application/postscript")
761     (".qt"       . "video/quicktime")
762     (".ras"      . "image/x-raster")
763     (".rgb"      . "image/x-rgb")
764     (".rtf"      . "application/rtf")
765     (".rtx"      . "text/richtext")
766     (".sh"       . "application/x-sh")
767     (".sit"      . "application/x-stuffit")
768     (".snd"      . "audio/basic")
769     (".src"      . "application/x-wais-source")
770     (".tar"      . "archive/tar")
771     (".tcl"      . "application/x-tcl")
772     (".tcl"      . "application/x-tcl")
773     (".tex"      . "application/x-tex")
774     (".texi"     . "application/texinfo")
775     (".tga"      . "image/x-targa")
776     (".tif"      . "image/tiff")
777     (".tiff"     . "image/tiff")
778     (".tr"       . "application/x-troff")
779     (".troff"    . "application/x-troff")
780     (".tsv"      . "text/tab-separated-values")
781     (".txt"      . "text/plain")
782     (".vbs"      . "video/mpeg")
783     (".vox"      . "audio/basic")
784     (".vrml"     . "x-world/x-vrml")
785     (".wav"      . "audio/x-wav")
786     (".wrl"      . "x-world/x-vrml")
787     (".xbm"      . "image/xbm")
788     (".xpm"      . "image/xpm")
789     (".xwd"      . "image/windowdump")
790     (".zip"      . "application/zip")
791     (".ai"       . "application/postscript")
792     (".jpe"      . "image/jpeg")
793     (".jpeg"     . "image/jpeg"))
794   "An assoc list of file extensions and corresponding MIME content-types.")
795
796 (defun mailcap-parse-mimetypes (&optional path)
797   ;; Parse out all the mimetypes specified in a unix-style path string PATH
798   (cond
799    (path nil)
800    ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
801    ((memq system-type '(ms-dos ms-windows windows-nt))
802     (setq path (mapconcat 'expand-file-name
803                           '("~/mime.typ" "~/etc/mime.typ") ";")))
804    (t (setq path (mapconcat
805                   'expand-file-name
806                   ;; mime.types seems to be the normal name,
807                   ;; definitely so on current GNUish systems.  The
808                   ;; ordering follows that for mailcap.
809                   '("~/.mime.types"
810                     "/etc/mime.types"
811                     "/usr/etc/mime.types"
812                     "/usr/local/etc/mime.types"
813                     "/usr/local/www/conf/mime.types"
814                     "~/.mime-types"
815                     "/etc/mime-types"
816                     "/usr/etc/mime-types"
817                     "/usr/local/etc/mime-types"
818                     "/usr/local/www/conf/mime-types") ":"))))
819   (let ((fnames (reverse
820                  (split-string path
821                                (if (memq system-type
822                                          '(ms-dos ms-windows windows-nt))
823                                    ";" ":"))))
824         fname)
825     (while fnames
826       (setq fname (car fnames))
827       (if (and (file-exists-p fname) (file-readable-p fname))
828           (mailcap-parse-mimetype-file (car fnames)))
829       (setq fnames (cdr fnames)))))
830
831 (defun mailcap-parse-mimetype-file (fname)
832   ;; Parse out a mime-types file
833   (let (type                            ; The MIME type for this line
834         extns                           ; The extensions for this line
835         save-pos                        ; Misc. saved buffer positions
836         )
837     (with-temp-buffer
838       (insert-file-contents fname)
839       (mailcap-replace-regexp "#.*" "")
840       (mailcap-replace-regexp "\n+" "\n")
841       (mailcap-replace-regexp "[ \t]+$" "")
842       (goto-char (point-max))
843       (skip-chars-backward " \t\n")
844       (delete-region (point) (point-max))
845       (goto-char (point-min))
846       (while (not (eobp))
847         (skip-chars-forward " \t\n")
848         (setq save-pos (point))
849         (skip-chars-forward "^ \t")
850         (downcase-region save-pos (point))
851         (setq type (buffer-substring save-pos (point)))
852         (while (not (eolp))
853           (skip-chars-forward " \t")
854           (setq save-pos (point))
855           (skip-chars-forward "^ \t\n")
856           (setq extns (cons (buffer-substring save-pos (point)) extns)))
857         (while extns
858           (setq mailcap-mime-extensions
859                 (cons
860                  (cons (if (= (string-to-char (car extns)) ?.)
861                            (car extns)
862                          (concat "." (car extns))) type)
863                  mailcap-mime-extensions)
864                 extns (cdr extns)))))))
865
866 (defun mailcap-extension-to-mime (extn)
867   "Return the MIME content type of the file extensions EXTN."
868   (if (and (stringp extn)
869            (not (eq (string-to-char extn) ?.)))
870       (setq extn (concat "." extn)))
871   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
872
873 (defvar mailcap-binary-suffixes
874   (if (memq system-type '(ms-dos windows-nt))
875       '(".exe" ".com" ".bat" ".cmd" ".btm" "")
876     '("")))
877
878 (defun mailcap-command-p (command)
879   "Say whether COMMAND is in the exec path.
880 The path of COMMAND will be returned iff COMMAND is a command."
881   (let ((path (if (file-name-absolute-p command) '(nil) exec-path))
882         file dir)
883     (catch 'found
884       (while (setq dir (pop path))
885         (let ((suffixes mailcap-binary-suffixes))
886           (while suffixes
887             (when (and (file-executable-p
888                         (setq file (expand-file-name
889                                     (concat command (pop suffixes))
890                                     dir)))
891                        (not (file-directory-p file)))
892               (throw 'found file))))))))
893
894 (defun mailcap-mime-types ()
895   "Return a list of MIME media types."
896   (mm-delete-duplicates (mapcar 'cdr mailcap-mime-extensions)))
897
898 (provide 'mailcap)
899
900 ;;; mailcap.el ends here