Merge from emacs--devo--0, emacs--rel--22
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- MIME media types configuration
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: William M. Perry <wmperry@aventail.com>
7 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; Keywords: news, mail, multimedia
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;; Commentary:
28
29 ;; Provides configuration of MIME media types from directly from Lisp
30 ;; and via the usual mailcap mechanism (RFC 1524).  Deals with
31 ;; mime.types similarly.
32
33 ;;; Code:
34
35 (eval-when-compile (require 'cl))
36 (autoload 'mail-header-parse-content-type "mail-parse")
37
38 ;; `mm-delete-duplicates' is an alias for `delete-dups' in Emacs 22.
39 (defalias 'mailcap-delete-duplicates
40   (if (fboundp 'delete-dups)
41       'delete-dups
42     (autoload 'mm-delete-duplicates "mm-util")
43     'mm-delete-duplicates))
44
45 ;; `mailcap-replace-in-string' is an alias like `gnus-replace-in-string'.
46 (eval-and-compile
47   (cond
48    ((fboundp 'replace-regexp-in-string)
49     (defun mailcap-replace-in-string  (string regexp newtext &optional literal)
50       "Replace all matches for REGEXP with NEWTEXT in STRING.
51 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
52 string containing the replacements.
53 This is a compatibility function for different Emacsen."
54       (replace-regexp-in-string regexp newtext string nil literal)))
55    ((fboundp 'replace-in-string)
56     (defalias 'mailcap-replace-in-string 'replace-in-string))))
57
58 (defgroup mailcap nil
59   "Definition of viewers for MIME types."
60   :version "21.1"
61   :group 'mime)
62
63 (defvar mailcap-parse-args-syntax-table
64   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
65     (modify-syntax-entry ?' "\"" table)
66     (modify-syntax-entry ?` "\"" table)
67     (modify-syntax-entry ?{ "(" table)
68     (modify-syntax-entry ?} ")" table)
69     table)
70   "A syntax table for parsing SGML attributes.")
71
72 (eval-and-compile
73   (when (featurep 'xemacs)
74     (condition-case nil
75         (require 'lpr)
76       (error nil))))
77
78 (defvar mailcap-print-command
79   (mapconcat 'identity
80              (cons (if (boundp 'lpr-command)
81                        lpr-command
82                      "lpr")
83                    (when (boundp 'lpr-switches)
84                      (if (stringp lpr-switches)
85                          (list lpr-switches)
86                        lpr-switches)))
87              " ")
88   "Shell command (including switches) used to print Postscript files.")
89
90 ;; Postpone using defcustom for this as it's so big and we essentially
91 ;; have to have two copies of the data around then.  Perhaps just
92 ;; customize the Lisp viewers and rely on the normal configuration
93 ;; files for the rest?  -- fx
94 (defvar mailcap-mime-data
95   `(("application"
96      ("vnd.ms-excel"
97       (viewer . "gnumeric %s")
98       (test   . (getenv "DISPLAY"))
99       (type . "application/vnd.ms-excel"))
100      ("x-x509-ca-cert"
101       (viewer . ssl-view-site-cert)
102       (test . (fboundp 'ssl-view-site-cert))
103       (type . "application/x-x509-ca-cert"))
104      ("x-x509-user-cert"
105       (viewer . ssl-view-user-cert)
106       (test . (fboundp 'ssl-view-user-cert))
107       (type . "application/x-x509-user-cert"))
108      ("octet-stream"
109       (viewer . mailcap-save-binary-file)
110       (non-viewer . t)
111       (type . "application/octet-stream"))
112      ("dvi"
113       (viewer . "xdvi -safer %s")
114       (test   . (eq window-system 'x))
115       ("needsx11")
116       (type   . "application/dvi")
117       ("print" . "dvips -qRP %s"))
118      ("dvi"
119       (viewer . "dvitty %s")
120       (test   . (not (getenv "DISPLAY")))
121       (type   . "application/dvi")
122       ("print" . "dvips -qRP %s"))
123      ("emacs-lisp"
124       (viewer . mailcap-maybe-eval)
125       (type   . "application/emacs-lisp"))
126      ("x-emacs-lisp"
127       (viewer . mailcap-maybe-eval)
128       (type   . "application/x-emacs-lisp"))
129      ("x-tar"
130       (viewer . mailcap-save-binary-file)
131       (non-viewer . t)
132       (type   . "application/x-tar"))
133      ("x-latex"
134       (viewer . tex-mode)
135       (test   . (fboundp 'tex-mode))
136       (type   . "application/x-latex"))
137      ("x-tex"
138       (viewer . tex-mode)
139       (test   . (fboundp 'tex-mode))
140       (type   . "application/x-tex"))
141      ("latex"
142       (viewer . tex-mode)
143       (test   . (fboundp 'tex-mode))
144       (type   . "application/latex"))
145      ("tex"
146       (viewer . tex-mode)
147       (test   . (fboundp 'tex-mode))
148       (type   . "application/tex"))
149      ("texinfo"
150       (viewer . texinfo-mode)
151       (test   . (fboundp 'texinfo-mode))
152       (type   . "application/tex"))
153      ("zip"
154       (viewer . mailcap-save-binary-file)
155       (non-viewer . t)
156       (type   . "application/zip")
157       ("copiousoutput"))
158      ("pdf"
159       (viewer . "gv -safer %s")
160       (type . "application/pdf")
161       (test . window-system)
162       ("print" . ,(concat "pdf2ps %s - | " mailcap-print-command)))
163      ("pdf"
164       (viewer . "gpdf %s")
165       (type . "application/pdf")
166       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
167       (test . (eq window-system 'x)))
168      ("pdf"
169       (viewer . "xpdf %s")
170       (type . "application/pdf")
171       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
172       (test . (eq window-system 'x)))
173      ("pdf"
174       (viewer . ,(concat "pdftotext %s -"))
175       (type   . "application/pdf")
176       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
177       ("copiousoutput"))
178      ("postscript"
179       (viewer . "gv -safer %s")
180       (type . "application/postscript")
181       (test   . window-system)
182       ("print" . ,(concat mailcap-print-command " %s"))
183       ("needsx11"))
184      ("postscript"
185       (viewer . "ghostview -dSAFER %s")
186       (type . "application/postscript")
187       (test   . (eq window-system 'x))
188       ("print" . ,(concat mailcap-print-command " %s"))
189       ("needsx11"))
190      ("postscript"
191       (viewer . "ps2ascii %s")
192       (type . "application/postscript")
193       (test . (not (getenv "DISPLAY")))
194       ("print" . ,(concat mailcap-print-command " %s"))
195       ("copiousoutput"))
196      ("sieve"
197       (viewer . sieve-mode)
198       (test   . (fboundp 'sieve-mode))
199       (type   . "application/sieve"))
200      ("pgp-keys"
201       (viewer . "gpg --import --interactive --verbose")
202       (type   . "application/pgp-keys")
203       ("needsterminal")))
204     ("audio"
205      ("x-mpeg"
206       (viewer . "maplay %s")
207       (type   . "audio/x-mpeg"))
208      (".*"
209       (viewer . "showaudio")
210       (type   . "audio/*")))
211     ("message"
212      ("rfc-*822"
213       (viewer . mm-view-message)
214       (test   . (and (featurep 'gnus)
215                      (gnus-alive-p)))
216       (type   . "message/rfc822"))
217      ("rfc-*822"
218       (viewer . vm-mode)
219       (test   . (fboundp 'vm-mode))
220       (type   . "message/rfc822"))
221      ("rfc-*822"
222       (viewer . w3-mode)
223       (test   . (fboundp 'w3-mode))
224       (type   . "message/rfc822"))
225      ("rfc-*822"
226       (viewer . view-mode)
227       (type   . "message/rfc822")))
228     ("image"
229      ("x-xwd"
230       (viewer  . "xwud -in %s")
231       (type    . "image/x-xwd")
232       ("compose" . "xwd -frame > %s")
233       (test    . (eq window-system 'x))
234       ("needsx11"))
235      ("x11-dump"
236       (viewer . "xwud -in %s")
237       (type . "image/x-xwd")
238       ("compose" . "xwd -frame > %s")
239       (test   . (eq window-system 'x))
240       ("needsx11"))
241      ("windowdump"
242       (viewer . "xwud -in %s")
243       (type . "image/x-xwd")
244       ("compose" . "xwd -frame > %s")
245       (test   . (eq window-system 'x))
246       ("needsx11"))
247      (".*"
248       (viewer . "display %s")
249       (type . "image/*")
250       (test   . (eq window-system 'x))
251       ("needsx11"))
252      (".*"
253       (viewer . "ee %s")
254       (type . "image/*")
255       (test   . (eq window-system 'x))
256       ("needsx11")))
257     ("text"
258      ("plain"
259       (viewer  . w3-mode)
260       (test    . (fboundp 'w3-mode))
261       (type    . "text/plain"))
262      ("plain"
263       (viewer  . view-mode)
264       (test    . (fboundp 'view-mode))
265       (type    . "text/plain"))
266      ("plain"
267       (viewer  . fundamental-mode)
268       (type    . "text/plain"))
269      ("enriched"
270       (viewer . enriched-decode)
271       (test   . (fboundp 'enriched-decode))
272       (type   . "text/enriched"))
273      ("html"
274       (viewer . mm-w3-prepare-buffer)
275       (test   . (fboundp 'w3-prepare-buffer))
276       (type   . "text/html"))
277      ("dns"
278       (viewer . dns-mode)
279       (test   . (fboundp 'dns-mode))
280       (type   . "text/dns")))
281     ("video"
282      ("mpeg"
283       (viewer . "mpeg_play %s")
284       (type   . "video/mpeg")
285       (test   . (eq window-system 'x))
286       ("needsx11")))
287     ("x-world"
288      ("x-vrml"
289       (viewer  . "webspace -remote %s -URL %u")
290       (type    . "x-world/x-vrml")
291       ("description"
292        "VRML document")))
293     ("archive"
294      ("tar"
295       (viewer . tar-mode)
296       (type . "archive/tar")
297       (test . (fboundp 'tar-mode)))))
298   "The mailcap structure is an assoc list of assoc lists.
299 1st assoc list is keyed on the major content-type
300 2nd assoc list is keyed on the minor content-type (which can be a regexp)
301
302 Which looks like:
303 -----------------
304  ((\"application\"
305    (\"postscript\" . <info>))
306   (\"text\"
307    (\"plain\" . <info>)))
308
309 Where <info> is another assoc list of the various information
310 related to the mailcap RFC 1524.  This is keyed on the lowercase
311 attribute name (viewer, test, etc).  This looks like:
312  ((viewer . VIEWERINFO)
313   (test   . TESTINFO)
314   (xxxx   . \"STRING\")
315   FLAG)
316
317 Where VIEWERINFO specifies how the content-type is viewed.  Can be
318 a string, in which case it is run through a shell, with
319 appropriate parameters, or a symbol, in which case the symbol is
320 `funcall'ed, with the buffer as an argument.
321
322 TESTINFO is a test for the viewer's applicability, or nil.  If nil, it
323 means the viewer is always valid.  If it is a Lisp function, it is
324 called with a list of items from any extra fields from the
325 Content-Type header as argument to return a boolean value for the
326 validity.  Otherwise, if it is a non-function Lisp symbol or list
327 whose car is a symbol, it is `eval'led to yield the validity.  If it
328 is a string or list of strings, it represents a shell command to run
329 to return a true or false shell value for the validity.")
330 (put 'mailcap-mime-data 'risky-local-variable t)
331
332 (defcustom mailcap-download-directory nil
333   "*Directory to which `mailcap-save-binary-file' downloads files by default.
334 nil means your home directory."
335   :type '(choice (const :tag "Home directory" nil)
336                  directory)
337   :group 'mailcap)
338
339 (defvar mailcap-poor-system-types
340   '(ms-dos ms-windows windows-nt win32 w32 mswindows)
341   "Systems that don't have a Unix-like directory hierarchy.")
342
343 ;;;
344 ;;; Utility functions
345 ;;;
346
347 (defun mailcap-save-binary-file ()
348   (goto-char (point-min))
349   (unwind-protect
350       (let ((file (read-file-name
351                    "Filename to save as: "
352                    (or mailcap-download-directory "~/")))
353             (require-final-newline nil))
354         (write-region (point-min) (point-max) file))
355     (kill-buffer (current-buffer))))
356
357 (defvar mailcap-maybe-eval-warning
358   "*** WARNING ***
359
360 This MIME part contains untrusted and possibly harmful content.
361 If you evaluate the Emacs Lisp code contained in it, a lot of nasty
362 things can happen.  Please examine the code very carefully before you
363 instruct Emacs to evaluate it.  You can browse the buffer containing
364 the code using \\[scroll-other-window].
365
366 If you are unsure what to do, please answer \"no\"."
367   "Text of warning message displayed by `mailcap-maybe-eval'.
368 Make sure that this text consists only of few text lines.  Otherwise,
369 Gnus might fail to display all of it.")
370
371 (defun mailcap-maybe-eval ()
372   "Maybe evaluate a buffer of Emacs Lisp code."
373   (let ((lisp-buffer (current-buffer)))
374     (goto-char (point-min))
375     (when
376         (save-window-excursion
377           (delete-other-windows)
378           (let ((buffer (get-buffer-create (generate-new-buffer-name
379                                             "*Warning*"))))
380             (unwind-protect
381                 (with-current-buffer buffer
382                   (insert (substitute-command-keys
383                            mailcap-maybe-eval-warning))
384                   (goto-char (point-min))
385                   (display-buffer buffer)
386                   (yes-or-no-p "This is potentially dangerous emacs-lisp code, evaluate it? "))
387               (kill-buffer buffer))))
388       (eval-buffer (current-buffer)))
389     (when (buffer-live-p lisp-buffer)
390       (with-current-buffer lisp-buffer
391         (emacs-lisp-mode)))))
392
393
394 ;;;
395 ;;; The mailcap parser
396 ;;;
397
398 (defun mailcap-replace-regexp (regexp to-string)
399   ;; Quiet replace-regexp.
400   (goto-char (point-min))
401   (while (re-search-forward regexp nil t)
402     (replace-match to-string t nil)))
403
404 (defvar mailcap-parsed-p nil)
405
406 (defun mailcap-parse-mailcaps (&optional path force)
407   "Parse out all the mailcaps specified in a path string PATH.
408 Components of PATH are separated by the `path-separator' character
409 appropriate for this system.  If FORCE, re-parse even if already
410 parsed.  If PATH is omitted, use the value of environment variable
411 MAILCAPS if set; otherwise (on Unix) use the path from RFC 1524, plus
412 /usr/local/etc/mailcap."
413   (interactive (list nil t))
414   (when (or (not mailcap-parsed-p)
415             force)
416     (cond
417      (path nil)
418      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
419      ((memq system-type mailcap-poor-system-types)
420       (setq path '("~/.mailcap" "~/mail.cap" "~/etc/mail.cap")))
421      (t (setq path
422               ;; This is per RFC 1524, specifically
423               ;; with /usr before /usr/local.
424               '("~/.mailcap" "/etc/mailcap" "/usr/etc/mailcap"
425                 "/usr/local/etc/mailcap"))))
426     (let ((fnames (reverse
427                    (if (stringp path)
428                        (delete "" (split-string path path-separator))
429                      path)))
430           fname)
431       (while fnames
432         (setq fname (car fnames))
433         (if (and (file-readable-p fname)
434                  (file-regular-p fname))
435             (mailcap-parse-mailcap fname))
436         (setq fnames (cdr fnames))))
437       (setq mailcap-parsed-p t)))
438
439 (defun mailcap-parse-mailcap (fname)
440   "Parse out the mailcap file specified by FNAME."
441   (let (major                           ; The major mime type (image/audio/etc)
442         minor                           ; The minor mime type (gif, basic, etc)
443         save-pos                        ; Misc saved positions used in parsing
444         viewer                          ; How to view this mime type
445         info                            ; Misc info about this mime type
446         )
447     (with-temp-buffer
448       (insert-file-contents fname)
449       (set-syntax-table mailcap-parse-args-syntax-table)
450       (mailcap-replace-regexp "#.*" "") ; Remove all comments
451       (mailcap-replace-regexp "\\\\[ \t]*\n" " ") ; And collapse spaces
452       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
453       (goto-char (point-max))
454       (skip-chars-backward " \t\n")
455       (delete-region (point) (point-max))
456       (while (not (bobp))
457         (skip-chars-backward " \t\n")
458         (beginning-of-line)
459         (setq save-pos (point)
460               info nil)
461         (skip-chars-forward "^/; \t\n")
462         (downcase-region save-pos (point))
463         (setq major (buffer-substring save-pos (point)))
464         (skip-chars-forward " \t")
465         (setq minor "")
466         (when (eq (char-after) ?/)
467           (forward-char)
468           (skip-chars-forward " \t")
469           (setq save-pos (point))
470           (skip-chars-forward "^; \t\n")
471           (downcase-region save-pos (point))
472           (setq minor
473                 (cond
474                  ((eq ?* (or (char-after save-pos) 0)) ".*")
475                  ((= (point) save-pos) ".*")
476                  (t (regexp-quote (buffer-substring save-pos (point)))))))
477         (skip-chars-forward " \t")
478         ;;; Got the major/minor chunks, now for the viewers/etc
479         ;;; The first item _must_ be a viewer, according to the
480         ;;; RFC for mailcap files (#1524)
481         (setq viewer "")
482         (when (eq (char-after) ?\;)
483           (forward-char)
484           (skip-chars-forward " \t")
485           (setq save-pos (point))
486           (skip-chars-forward "^;\n")
487           ;; skip \;
488           (while (eq (char-before) ?\\)
489             (backward-delete-char 1)
490             (forward-char)
491             (skip-chars-forward "^;\n"))
492           (if (eq (or (char-after save-pos) 0) ?')
493               (setq viewer (progn
494                              (narrow-to-region (1+ save-pos) (point))
495                              (goto-char (point-min))
496                              (prog1
497                                  (read (current-buffer))
498                                (goto-char (point-max))
499                                (widen))))
500             (setq viewer (buffer-substring save-pos (point)))))
501         (setq save-pos (point))
502         (end-of-line)
503         (unless (equal viewer "")
504           (setq info (nconc (list (cons 'viewer viewer)
505                                   (cons 'type (concat major "/"
506                                                       (if (string= minor ".*")
507                                                           "*" minor))))
508                             (mailcap-parse-mailcap-extras save-pos (point))))
509           (mailcap-mailcap-entry-passes-test info)
510           (mailcap-add-mailcap-entry major minor info))
511         (beginning-of-line)))))
512
513 (defun mailcap-parse-mailcap-extras (st nd)
514   "Grab all the extra stuff from a mailcap entry."
515   (let (
516         name                            ; From name=
517         value                           ; its value
518         results                         ; Assoc list of results
519         name-pos                        ; Start of XXXX= position
520         val-pos                         ; Start of value position
521         done                            ; Found end of \'d ;s?
522         )
523     (save-restriction
524       (narrow-to-region st nd)
525       (goto-char (point-min))
526       (skip-chars-forward " \n\t;")
527       (while (not (eobp))
528         (setq done nil)
529         (setq name-pos (point))
530         (skip-chars-forward "^ \n\t=;")
531         (downcase-region name-pos (point))
532         (setq name (buffer-substring name-pos (point)))
533         (skip-chars-forward " \t\n")
534         (if (not (eq (char-after (point)) ?=)) ; There is no value
535             (setq value t)
536           (skip-chars-forward " \t\n=")
537           (setq val-pos (point))
538           (if (memq (char-after val-pos) '(?\" ?'))
539               (progn
540                 (setq val-pos (1+ val-pos))
541                 (condition-case nil
542                     (progn
543                       (forward-sexp 1)
544                       (backward-char 1))
545                   (error (goto-char (point-max)))))
546             (while (not done)
547               (skip-chars-forward "^;")
548               (if (eq (char-after (1- (point))) ?\\ )
549                   (progn
550                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
551                     (skip-chars-forward ";"))
552                 (setq done t))))
553           (setq value (buffer-substring val-pos (point))))
554         ;; `test' as symbol, others like "copiousoutput" and "needsx11" as
555         ;; strings
556         (setq results (cons (cons (if (string-equal name "test")
557                                       'test
558                                     name)
559                                   value) results))
560         (skip-chars-forward " \";\n\t"))
561       results)))
562
563 (defun mailcap-mailcap-entry-passes-test (info)
564   "Return non-nil if mailcap entry INFO passes its test clause.
565 Also return non-nil if no test clause is present."
566   (let ((test (assq 'test info))        ; The test clause
567         status)
568     (setq status (and test (split-string (cdr test) " ")))
569     (if (and (or (assoc "needsterm" info)
570                  (assoc "needsterminal" info)
571                  (assoc "needsx11" info))
572              (not (getenv "DISPLAY")))
573         (setq status nil)
574       (cond
575        ((and (equal (nth 0 status) "test")
576              (equal (nth 1 status) "-n")
577              (or (equal (nth 2 status) "$DISPLAY")
578                  (equal (nth 2 status) "\"$DISPLAY\"")))
579         (setq status (if (getenv "DISPLAY") t nil)))
580        ((and (equal (nth 0 status) "test")
581              (equal (nth 1 status) "-z")
582              (or (equal (nth 2 status) "$DISPLAY")
583                  (equal (nth 2 status) "\"$DISPLAY\"")))
584         (setq status (if (getenv "DISPLAY") nil t)))
585        (test nil)
586        (t nil)))
587     (and test (listp test) (setcdr test status))))
588
589 ;;;
590 ;;; The action routines.
591 ;;;
592
593 (defun mailcap-possible-viewers (major minor)
594   "Return a list of possible viewers from MAJOR for minor type MINOR."
595   (let ((exact '())
596         (wildcard '()))
597     (while major
598       (cond
599        ((equal (car (car major)) minor)
600         (setq exact (cons (cdr (car major)) exact)))
601        ((and minor (string-match (concat "^" (car (car major)) "$") minor))
602         (setq wildcard (cons (cdr (car major)) wildcard))))
603       (setq major (cdr major)))
604     (nconc exact wildcard)))
605
606 (defun mailcap-unescape-mime-test (test type-info)
607   (let (save-pos save-chr subst)
608     (cond
609      ((symbolp test) test)
610      ((and (listp test) (symbolp (car test))) test)
611      ((or (stringp test)
612           (and (listp test) (stringp (car test))
613                (setq test (mapconcat 'identity test " "))))
614       (with-temp-buffer
615         (insert test)
616         (goto-char (point-min))
617         (while (not (eobp))
618           (skip-chars-forward "^%")
619           (if (/= (- (point)
620                      (progn (skip-chars-backward "\\\\")
621                             (point)))
622                   0)                    ; It is an escaped %
623               (progn
624                 (delete-char 1)
625                 (skip-chars-forward "%."))
626             (setq save-pos (point))
627             (skip-chars-forward "%")
628             (setq save-chr (char-after (point)))
629             ;; Escapes:
630             ;; %s: name of a file for the body data
631             ;; %t: content-type
632             ;; %{<parameter name}: value of parameter in mailcap entry
633             ;; %n: number of sub-parts for multipart content-type
634             ;; %F: a set of content-type/filename pairs for multiparts
635             (cond
636              ((null save-chr) nil)
637              ((= save-chr ?t)
638               (delete-region save-pos (progn (forward-char 1) (point)))
639               (insert (or (cdr (assq 'type type-info)) "\"\"")))
640              ((memq save-chr '(?M ?n ?F))
641               (delete-region save-pos (progn (forward-char 1) (point)))
642               (insert "\"\""))
643              ((= save-chr ?{)
644               (forward-char 1)
645               (skip-chars-forward "^}")
646               (downcase-region (+ 2 save-pos) (point))
647               (setq subst (buffer-substring (+ 2 save-pos) (point)))
648               (delete-region save-pos (1+ (point)))
649               (insert (or (cdr (assoc subst type-info)) "\"\"")))
650              (t nil))))
651         (buffer-string)))
652      (t (error "Bad value to mailcap-unescape-mime-test: %s" test)))))
653
654 (defvar mailcap-viewer-test-cache nil)
655
656 (defun mailcap-viewer-passes-test (viewer-info type-info)
657   "Return non-nil if viewer specified by VIEWER-INFO passes its test clause.
658 Also return non-nil if it has no test clause.  TYPE-INFO is an argument
659 to supply to the test."
660   (let* ((test-info (assq 'test viewer-info))
661          (test (cdr test-info))
662          (otest test)
663          (viewer (cdr (assoc 'viewer viewer-info)))
664          (default-directory (expand-file-name "~/"))
665          status parsed-test cache result)
666     (cond ((setq cache (assoc test mailcap-viewer-test-cache))
667            (cadr cache))
668           ((not test-info) t)           ; No test clause
669           (t
670            (setq
671             result
672             (cond
673              ((not test) nil)           ; Already failed test
674              ((eq test t) t)            ; Already passed test
675              ((functionp test)          ; Lisp function as test
676               (funcall test type-info))
677              ((and (symbolp test)       ; Lisp variable as test
678                    (boundp test))
679               (symbol-value test))
680              ((and (listp test)         ; List to be eval'd
681                    (symbolp (car test)))
682               (eval test))
683              (t
684               (setq test (mailcap-unescape-mime-test test type-info)
685                     test (list shell-file-name nil nil nil
686                                shell-command-switch test)
687                     status (apply 'call-process test))
688               (eq 0 status))))
689            (push (list otest result) mailcap-viewer-test-cache)
690            result))))
691
692 (defun mailcap-add-mailcap-entry (major minor info)
693   (let ((old-major (assoc major mailcap-mime-data)))
694     (if (null old-major)                ; New major area
695         (setq mailcap-mime-data
696               (cons (cons major (list (cons minor info)))
697                     mailcap-mime-data))
698       (let ((cur-minor (assoc minor old-major)))
699         (cond
700          ((or (null cur-minor)          ; New minor area, or
701               (assq 'test info))        ; Has a test, insert at beginning
702           (setcdr old-major (cons (cons minor info) (cdr old-major))))
703          ((and (not (assq 'test info))  ; No test info, replace completely
704                (not (assq 'test cur-minor))
705                (equal (assq 'viewer info)  ; Keep alternative viewer
706                       (assq 'viewer cur-minor)))
707           (setcdr cur-minor info))
708          (t
709           (setcdr old-major (cons (cons minor info) (cdr old-major))))))
710       )))
711
712 (defun mailcap-add (type viewer &optional test)
713   "Add VIEWER as a handler for TYPE.
714 If TEST is not given, it defaults to t."
715   (let ((tl (split-string type "/")))
716     (when (or (not (car tl))
717               (not (cadr tl)))
718       (error "%s is not a valid MIME type" type))
719     (mailcap-add-mailcap-entry
720      (car tl) (cadr tl)
721      `((viewer . ,viewer)
722        (test . ,(if test test t))
723        (type . ,type)))))
724
725 ;;;
726 ;;; The main whabbo
727 ;;;
728
729 (defun mailcap-viewer-lessp (x y)
730   "Return t if viewer X is more desirable than viewer Y."
731   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
732         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
733         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
734         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
735     (cond
736      ((and x-wild (not y-wild))
737       nil)
738      ((and (not x-wild) y-wild)
739       t)
740      ((and (not y-lisp) x-lisp)
741       t)
742      (t nil))))
743
744 (defun mailcap-mime-info (string &optional request no-decode)
745   "Get the MIME viewer command for STRING, return nil if none found.
746 Expects a complete content-type header line as its argument.
747
748 Second argument REQUEST specifies what information to return.  If it is
749 nil or the empty string, the viewer (second field of the mailcap
750 entry) will be returned.  If it is a string, then the mailcap field
751 corresponding to that string will be returned (print, description,
752 whatever).  If a number, then all the information for this specific
753 viewer is returned.  If `all', then all possible viewers for
754 this type is returned.
755
756 If NO-DECODE is non-nil, don't decode STRING."
757   ;; NO-DECODE avoids calling `mail-header-parse-content-type' from
758   ;; `mail-parse.el'
759   (let (
760         major                           ; Major encoding (text, etc)
761         minor                           ; Minor encoding (html, etc)
762         info                            ; Other info
763         save-pos                        ; Misc. position during parse
764         major-info                      ; (assoc major mailcap-mime-data)
765         minor-info                      ; (assoc minor major-info)
766         test                            ; current test proc.
767         viewers                         ; Possible viewers
768         passed                          ; Viewers that passed the test
769         viewer                          ; The one and only viewer
770         ctl)
771     (save-excursion
772       (setq ctl
773             (if no-decode
774                 (list (or string "text/plain"))
775               (mail-header-parse-content-type (or string "text/plain"))))
776       (setq major (split-string (car ctl) "/"))
777       (setq minor (cadr major)
778             major (car major))
779       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
780         (when (setq viewers (mailcap-possible-viewers major-info minor))
781           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
782                                                (cdr a)))
783                              (cdr ctl)))
784           (while viewers
785             (if (mailcap-viewer-passes-test (car viewers) info)
786                 (setq passed (cons (car viewers) passed)))
787             (setq viewers (cdr viewers)))
788           (setq passed (sort passed 'mailcap-viewer-lessp))
789           (setq viewer (car passed))))
790       (when (and (stringp (cdr (assq 'viewer viewer)))
791                  passed)
792         (setq viewer (car passed)))
793       (cond
794        ((and (null viewer) (not (equal major "default")) request)
795         (mailcap-mime-info "default" request no-decode))
796        ((or (null request) (equal request ""))
797         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
798        ((stringp request)
799         (mailcap-unescape-mime-test
800          (cdr-safe (assoc request viewer)) info))
801        ((eq request 'all)
802         passed)
803        (t
804         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
805         (setq viewer (copy-sequence viewer))
806         (let ((view (assq 'viewer viewer))
807               (test (assq 'test viewer)))
808           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
809           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
810         viewer)))))
811
812 ;;;
813 ;;; Experimental MIME-types parsing
814 ;;;
815
816 (defvar mailcap-mime-extensions
817   '((""        . "text/plain")
818     (".abs"   . "audio/x-mpeg")
819     (".aif"   . "audio/aiff")
820     (".aifc"  . "audio/aiff")
821     (".aiff"  . "audio/aiff")
822     (".ano"   . "application/x-annotator")
823     (".au"    . "audio/ulaw")
824     (".avi"   . "video/x-msvideo")
825     (".bcpio" . "application/x-bcpio")
826     (".bin"   . "application/octet-stream")
827     (".cdf"   . "application/x-netcdr")
828     (".cpio"  . "application/x-cpio")
829     (".csh"   . "application/x-csh")
830     (".css"   . "text/css")
831     (".dvi"   . "application/x-dvi")
832     (".diff"  . "text/x-patch")
833     (".el"    . "application/emacs-lisp")
834     (".eps"   . "application/postscript")
835     (".etx"   . "text/x-setext")
836     (".exe"   . "application/octet-stream")
837     (".fax"   . "image/x-fax")
838     (".gif"   . "image/gif")
839     (".hdf"   . "application/x-hdf")
840     (".hqx"   . "application/mac-binhex40")
841     (".htm"   . "text/html")
842     (".html"  . "text/html")
843     (".icon"  . "image/x-icon")
844     (".ief"   . "image/ief")
845     (".jpg"   . "image/jpeg")
846     (".macp"  . "image/x-macpaint")
847     (".man"   . "application/x-troff-man")
848     (".me"    . "application/x-troff-me")
849     (".mif"   . "application/mif")
850     (".mov"   . "video/quicktime")
851     (".movie" . "video/x-sgi-movie")
852     (".mp2"   . "audio/x-mpeg")
853     (".mp3"   . "audio/x-mpeg")
854     (".mp2a"  . "audio/x-mpeg2")
855     (".mpa"   . "audio/x-mpeg")
856     (".mpa2"  . "audio/x-mpeg2")
857     (".mpe"   . "video/mpeg")
858     (".mpeg"  . "video/mpeg")
859     (".mpega" . "audio/x-mpeg")
860     (".mpegv" . "video/mpeg")
861     (".mpg"   . "video/mpeg")
862     (".mpv"   . "video/mpeg")
863     (".ms"    . "application/x-troff-ms")
864     (".nc"    . "application/x-netcdf")
865     (".nc"    . "application/x-netcdf")
866     (".oda"   . "application/oda")
867     (".patch" . "text/x-patch")
868     (".pbm"   . "image/x-portable-bitmap")
869     (".pdf"   . "application/pdf")
870     (".pgm"   . "image/portable-graymap")
871     (".pict"  . "image/pict")
872     (".png"   . "image/png")
873     (".pnm"   . "image/x-portable-anymap")
874     (".ppm"   . "image/portable-pixmap")
875     (".ps"    . "application/postscript")
876     (".qt"    . "video/quicktime")
877     (".ras"   . "image/x-raster")
878     (".rgb"   . "image/x-rgb")
879     (".rtf"   . "application/rtf")
880     (".rtx"   . "text/richtext")
881     (".sh"    . "application/x-sh")
882     (".sit"   . "application/x-stuffit")
883     (".siv"   . "application/sieve")
884     (".snd"   . "audio/basic")
885     (".soa"   . "text/dns")
886     (".src"   . "application/x-wais-source")
887     (".tar"   . "archive/tar")
888     (".tcl"   . "application/x-tcl")
889     (".tex"   . "application/x-tex")
890     (".texi"  . "application/texinfo")
891     (".tga"   . "image/x-targa")
892     (".tif"   . "image/tiff")
893     (".tiff"  . "image/tiff")
894     (".tr"    . "application/x-troff")
895     (".troff" . "application/x-troff")
896     (".tsv"   . "text/tab-separated-values")
897     (".txt"   . "text/plain")
898     (".vbs"   . "video/mpeg")
899     (".vox"   . "audio/basic")
900     (".vrml"  . "x-world/x-vrml")
901     (".wav"   . "audio/x-wav")
902     (".xls"   . "application/vnd.ms-excel")
903     (".wrl"   . "x-world/x-vrml")
904     (".xbm"   . "image/xbm")
905     (".xpm"   . "image/xpm")
906     (".xwd"   . "image/windowdump")
907     (".zip"   . "application/zip")
908     (".ai"    . "application/postscript")
909     (".jpe"   . "image/jpeg")
910     (".jpeg"  . "image/jpeg"))
911   "An alist of file extensions and corresponding MIME content-types.
912 This exists for you to customize the information in Lisp.  It is
913 merged with values from mailcap files by `mailcap-parse-mimetypes'.")
914
915 (defvar mailcap-mimetypes-parsed-p nil)
916
917 (defun mailcap-parse-mimetypes (&optional path force)
918   "Parse out all the mimetypes specified in a Unix-style path string PATH.
919 Components of PATH are separated by the `path-separator' character
920 appropriate for this system.  If PATH is omitted, use the value of
921 environment variable MIMETYPES if set; otherwise use a default path.
922 If FORCE, re-parse even if already parsed."
923   (interactive (list nil t))
924   (when (or (not mailcap-mimetypes-parsed-p)
925             force)
926     (cond
927      (path nil)
928      ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
929      ((memq system-type mailcap-poor-system-types)
930       (setq path '("~/mime.typ" "~/etc/mime.typ")))
931      (t (setq path
932               ;; mime.types seems to be the normal name, definitely so
933               ;; on current GNUish systems.  The search order follows
934               ;; that for mailcap.
935               '("~/.mime.types"
936                 "/etc/mime.types"
937                 "/usr/etc/mime.types"
938                 "/usr/local/etc/mime.types"
939                 "/usr/local/www/conf/mime.types"
940                 "~/.mime-types"
941                 "/etc/mime-types"
942                 "/usr/etc/mime-types"
943                 "/usr/local/etc/mime-types"
944                 "/usr/local/www/conf/mime-types"))))
945     (let ((fnames (reverse (if (stringp path)
946                                (delete "" (split-string path path-separator))
947                              path)))
948           fname)
949       (while fnames
950         (setq fname (car fnames))
951         (if (and (file-readable-p fname))
952             (mailcap-parse-mimetype-file fname))
953         (setq fnames (cdr fnames))))
954     (setq mailcap-mimetypes-parsed-p t)))
955
956 (defun mailcap-parse-mimetype-file (fname)
957   "Parse out a mime-types file FNAME."
958   (let (type                            ; The MIME type for this line
959         extns                           ; The extensions for this line
960         save-pos                        ; Misc. saved buffer positions
961         )
962     (with-temp-buffer
963       (insert-file-contents fname)
964       (mailcap-replace-regexp "#.*" "")
965       (mailcap-replace-regexp "\n+" "\n")
966       (mailcap-replace-regexp "[ \t]+$" "")
967       (goto-char (point-max))
968       (skip-chars-backward " \t\n")
969       (delete-region (point) (point-max))
970       (goto-char (point-min))
971       (while (not (eobp))
972         (skip-chars-forward " \t\n")
973         (setq save-pos (point))
974         (skip-chars-forward "^ \t\n")
975         (downcase-region save-pos (point))
976         (setq type (buffer-substring save-pos (point)))
977         (while (not (eolp))
978           (skip-chars-forward " \t")
979           (setq save-pos (point))
980           (skip-chars-forward "^ \t\n")
981           (setq extns (cons (buffer-substring save-pos (point)) extns)))
982         (while extns
983           (setq mailcap-mime-extensions
984                 (cons
985                  (cons (if (= (string-to-char (car extns)) ?.)
986                            (car extns)
987                          (concat "." (car extns))) type)
988                  mailcap-mime-extensions)
989                 extns (cdr extns)))))))
990
991 (defun mailcap-extension-to-mime (extn)
992   "Return the MIME content type of the file extensions EXTN."
993   (mailcap-parse-mimetypes)
994   (if (and (stringp extn)
995            (not (eq (string-to-char extn) ?.)))
996       (setq extn (concat "." extn)))
997   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
998
999 ;; Unused?
1000 (defalias 'mailcap-command-p 'executable-find)
1001
1002 (defun mailcap-mime-types ()
1003   "Return a list of MIME media types."
1004   (mailcap-parse-mimetypes)
1005   (mailcap-delete-duplicates
1006    (nconc
1007     (mapcar 'cdr mailcap-mime-extensions)
1008     (apply
1009      'nconc
1010      (mapcar
1011       (lambda (l)
1012         (delq nil
1013               (mapcar
1014                (lambda (m)
1015                  (let ((type (cdr (assq 'type (cdr m)))))
1016                    (if (equal (cadr (split-string type "/"))
1017                               "*")
1018                        nil
1019                      type)))
1020                (cdr l))))
1021       mailcap-mime-data)))))
1022
1023 ;;;
1024 ;;; Useful supplementary functions
1025 ;;;
1026
1027 (defun mailcap-file-default-commands (files)
1028   "Return a list of default commands for FILES."
1029   (mailcap-parse-mailcaps)
1030   (mailcap-parse-mimetypes)
1031   (let* ((all-mime-type
1032           ;; All unique MIME types from file extensions
1033           (mailcap-delete-duplicates
1034            (mapcar (lambda (file)
1035                      (mailcap-extension-to-mime
1036                       (file-name-extension file t)))
1037                    files)))
1038          (all-mime-info
1039           ;; All MIME info lists
1040           (mailcap-delete-duplicates
1041            (mapcar (lambda (mime-type)
1042                      (mailcap-mime-info mime-type 'all))
1043                    all-mime-type)))
1044          (common-mime-info
1045           ;; Intersection of mime-infos from different mime-types;
1046           ;; or just the first MIME info for a single MIME type
1047           (if (cdr all-mime-info)
1048               (delq nil (mapcar (lambda (mi1)
1049                                   (unless (memq nil (mapcar
1050                                                      (lambda (mi2)
1051                                                        (member mi1 mi2))
1052                                                      (cdr all-mime-info)))
1053                                     mi1))
1054                                 (car all-mime-info)))
1055             (car all-mime-info)))
1056          (commands
1057           ;; Command strings from `viewer' field of the MIME info
1058           (mailcap-delete-duplicates
1059            (delq nil (mapcar (lambda (mime-info)
1060                                (let ((command (cdr (assoc 'viewer mime-info))))
1061                                  (if (stringp command)
1062                                      (mailcap-replace-in-string
1063                                       ;; Replace mailcap's `%s' placeholder
1064                                       ;; with dired's `?' placeholder
1065                                       (mailcap-replace-in-string
1066                                        ;; Remove the final filename placeholder
1067                                        command "[ \t\n]*\\('\\)?%s\\1?[ \t\n]*\\'" "" t)
1068                                       "%s" "?" t))))
1069                              common-mime-info)))))
1070     commands))
1071
1072 (provide 'mailcap)
1073
1074 ;; arch-tag: 1fd4f9c9-c305-4d2e-9747-3a4d45baa0bd
1075 ;;; mailcap.el ends here