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