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