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