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