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