* mailcap.el (mailcap-mime-data): Conditonalize `doc-view-mode',
[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   "Return non-nil if mailcap entry INFO passes its test clause.
560 Also return non-nil if no test clause is present."
561   (let ((test (assq 'test info))        ; The test clause
562         status)
563     (setq status (and test (split-string (cdr test) " ")))
564     (if (and (or (assoc "needsterm" info)
565                  (assoc "needsterminal" info)
566                  (assoc "needsx11" info))
567              (not (getenv "DISPLAY")))
568         (setq status nil)
569       (cond
570        ((and (equal (nth 0 status) "test")
571              (equal (nth 1 status) "-n")
572              (or (equal (nth 2 status) "$DISPLAY")
573                  (equal (nth 2 status) "\"$DISPLAY\"")))
574         (setq status (if (getenv "DISPLAY") t nil)))
575        ((and (equal (nth 0 status) "test")
576              (equal (nth 1 status) "-z")
577              (or (equal (nth 2 status) "$DISPLAY")
578                  (equal (nth 2 status) "\"$DISPLAY\"")))
579         (setq status (if (getenv "DISPLAY") nil t)))
580        (test nil)
581        (t nil)))
582     (and test (listp test) (setcdr test status))))
583
584 ;;;
585 ;;; The action routines.
586 ;;;
587
588 (defun mailcap-possible-viewers (major minor)
589   "Return a list of possible viewers from MAJOR for minor type MINOR."
590   (let ((exact '())
591         (wildcard '()))
592     (while major
593       (cond
594        ((equal (car (car major)) minor)
595         (setq exact (cons (cdr (car major)) exact)))
596        ((and minor (string-match (concat "^" (car (car major)) "$") minor))
597         (setq wildcard (cons (cdr (car major)) wildcard))))
598       (setq major (cdr major)))
599     (nconc exact wildcard)))
600
601 (defun mailcap-unescape-mime-test (test type-info)
602   (let (save-pos save-chr subst)
603     (cond
604      ((symbolp test) test)
605      ((and (listp test) (symbolp (car test))) test)
606      ((or (stringp test)
607           (and (listp test) (stringp (car test))
608                (setq test (mapconcat 'identity test " "))))
609       (with-temp-buffer
610         (insert test)
611         (goto-char (point-min))
612         (while (not (eobp))
613           (skip-chars-forward "^%")
614           (if (/= (- (point)
615                      (progn (skip-chars-backward "\\\\")
616                             (point)))
617                   0)                    ; It is an escaped %
618               (progn
619                 (delete-char 1)
620                 (skip-chars-forward "%."))
621             (setq save-pos (point))
622             (skip-chars-forward "%")
623             (setq save-chr (char-after (point)))
624             ;; Escapes:
625             ;; %s: name of a file for the body data
626             ;; %t: content-type
627             ;; %{<parameter name}: value of parameter in mailcap entry
628             ;; %n: number of sub-parts for multipart content-type
629             ;; %F: a set of content-type/filename pairs for multiparts
630             (cond
631              ((null save-chr) nil)
632              ((= save-chr ?t)
633               (delete-region save-pos (progn (forward-char 1) (point)))
634               (insert (or (cdr (assq 'type type-info)) "\"\"")))
635              ((memq save-chr '(?M ?n ?F))
636               (delete-region save-pos (progn (forward-char 1) (point)))
637               (insert "\"\""))
638              ((= save-chr ?{)
639               (forward-char 1)
640               (skip-chars-forward "^}")
641               (downcase-region (+ 2 save-pos) (point))
642               (setq subst (buffer-substring (+ 2 save-pos) (point)))
643               (delete-region save-pos (1+ (point)))
644               (insert (or (cdr (assoc subst type-info)) "\"\"")))
645              (t nil))))
646         (buffer-string)))
647      (t (error "Bad value to mailcap-unescape-mime-test: %s" test)))))
648
649 (defvar mailcap-viewer-test-cache nil)
650
651 (defun mailcap-viewer-passes-test (viewer-info type-info)
652   "Return non-nil if viewer specified by VIEWER-INFO passes its test clause.
653 Also return non-nil if it has no test clause.  TYPE-INFO is an argument
654 to supply to the test."
655   (let* ((test-info (assq 'test viewer-info))
656          (test (cdr test-info))
657          (otest test)
658          (viewer (cdr (assoc 'viewer viewer-info)))
659          (default-directory (expand-file-name "~/"))
660          status parsed-test cache result)
661     (cond ((setq cache (assoc test mailcap-viewer-test-cache))
662            (cadr cache))
663           ((not test-info) t)           ; No test clause
664           (t
665            (setq
666             result
667             (cond
668              ((not test) nil)           ; Already failed test
669              ((eq test t) t)            ; Already passed test
670              ((functionp test)          ; Lisp function as test
671               (funcall test type-info))
672              ((and (symbolp test)       ; Lisp variable as test
673                    (boundp test))
674               (symbol-value test))
675              ((and (listp test)         ; List to be eval'd
676                    (symbolp (car test)))
677               (eval test))
678              (t
679               (setq test (mailcap-unescape-mime-test test type-info)
680                     test (list shell-file-name nil nil nil
681                                shell-command-switch test)
682                     status (apply 'call-process test))
683               (eq 0 status))))
684            (push (list otest result) mailcap-viewer-test-cache)
685            result))))
686
687 (defun mailcap-add-mailcap-entry (major minor info)
688   (let ((old-major (assoc major mailcap-mime-data)))
689     (if (null old-major)                ; New major area
690         (setq mailcap-mime-data
691               (cons (cons major (list (cons minor info)))
692                     mailcap-mime-data))
693       (let ((cur-minor (assoc minor old-major)))
694         (cond
695          ((or (null cur-minor)          ; New minor area, or
696               (assq 'test info))        ; Has a test, insert at beginning
697           (setcdr old-major (cons (cons minor info) (cdr old-major))))
698          ((and (not (assq 'test info))  ; No test info, replace completely
699                (not (assq 'test cur-minor))
700                (equal (assq 'viewer info)  ; Keep alternative viewer
701                       (assq 'viewer cur-minor)))
702           (setcdr cur-minor info))
703          (t
704           (setcdr old-major (cons (cons minor info) (cdr old-major))))))
705       )))
706
707 (defun mailcap-add (type viewer &optional test)
708   "Add VIEWER as a handler for TYPE.
709 If TEST is not given, it defaults to t."
710   (let ((tl (split-string type "/")))
711     (when (or (not (car tl))
712               (not (cadr tl)))
713       (error "%s is not a valid MIME type" type))
714     (mailcap-add-mailcap-entry
715      (car tl) (cadr tl)
716      `((viewer . ,viewer)
717        (test . ,(if test test t))
718        (type . ,type)))))
719
720 ;;;
721 ;;; The main whabbo
722 ;;;
723
724 (defun mailcap-viewer-lessp (x y)
725   "Return t if viewer X is more desirable than viewer Y."
726   (let ((x-wild (string-match "[*?]" (or (cdr-safe (assq 'type x)) "")))
727         (y-wild (string-match "[*?]" (or (cdr-safe (assq 'type y)) "")))
728         (x-lisp (not (stringp (or (cdr-safe (assq 'viewer x)) ""))))
729         (y-lisp (not (stringp (or (cdr-safe (assq 'viewer y)) "")))))
730     (cond
731      ((and x-wild (not y-wild))
732       nil)
733      ((and (not x-wild) y-wild)
734       t)
735      ((and (not y-lisp) x-lisp)
736       t)
737      (t nil))))
738
739 (defun mailcap-mime-info (string &optional request no-decode)
740   "Get the MIME viewer command for STRING, return nil if none found.
741 Expects a complete content-type header line as its argument.
742
743 Second argument REQUEST specifies what information to return.  If it is
744 nil or the empty string, the viewer (second field of the mailcap
745 entry) will be returned.  If it is a string, then the mailcap field
746 corresponding to that string will be returned (print, description,
747 whatever).  If a number, then all the information for this specific
748 viewer is returned.  If `all', then all possible viewers for
749 this type is returned.
750
751 If NO-DECODE is non-nil, don't decode STRING."
752   ;; NO-DECODE avoids calling `mail-header-parse-content-type' from
753   ;; `mail-parse.el'
754   (let (
755         major                           ; Major encoding (text, etc)
756         minor                           ; Minor encoding (html, etc)
757         info                            ; Other info
758         save-pos                        ; Misc. position during parse
759         major-info                      ; (assoc major mailcap-mime-data)
760         minor-info                      ; (assoc minor major-info)
761         test                            ; current test proc.
762         viewers                         ; Possible viewers
763         passed                          ; Viewers that passed the test
764         viewer                          ; The one and only viewer
765         ctl)
766     (save-excursion
767       (setq ctl
768             (if no-decode
769                 (list (or string "text/plain"))
770               (mail-header-parse-content-type (or string "text/plain"))))
771       (setq major (split-string (car ctl) "/"))
772       (setq minor (cadr major)
773             major (car major))
774       (when (setq major-info (cdr (assoc major mailcap-mime-data)))
775         (when (setq viewers (mailcap-possible-viewers major-info minor))
776           (setq info (mapcar (lambda (a) (cons (symbol-name (car a))
777                                                (cdr a)))
778                              (cdr ctl)))
779           (while viewers
780             (if (mailcap-viewer-passes-test (car viewers) info)
781                 (setq passed (cons (car viewers) passed)))
782             (setq viewers (cdr viewers)))
783           (setq passed (sort passed 'mailcap-viewer-lessp))
784           (setq viewer (car passed))))
785       (when (and (stringp (cdr (assq 'viewer viewer)))
786                  passed)
787         (setq viewer (car passed)))
788       (cond
789        ((and (null viewer) (not (equal major "default")) request)
790         (mailcap-mime-info "default" request no-decode))
791        ((or (null request) (equal request ""))
792         (mailcap-unescape-mime-test (cdr (assq 'viewer viewer)) info))
793        ((stringp request)
794         (mailcap-unescape-mime-test
795          (cdr-safe (assoc request viewer)) info))
796        ((eq request 'all)
797         passed)
798        (t
799         ;; MUST make a copy *sigh*, else we modify mailcap-mime-data
800         (setq viewer (copy-sequence viewer))
801         (let ((view (assq 'viewer viewer))
802               (test (assq 'test viewer)))
803           (if view (setcdr view (mailcap-unescape-mime-test (cdr view) info)))
804           (if test (setcdr test (mailcap-unescape-mime-test (cdr test) info))))
805         viewer)))))
806
807 ;;;
808 ;;; Experimental MIME-types parsing
809 ;;;
810
811 (defvar mailcap-mime-extensions
812   '((""       . "text/plain")
813     (".1"     . "text/plain")  ;; Manual pages
814     (".3"     . "text/plain")
815     (".8"     . "text/plain")
816     (".abs"   . "audio/x-mpeg")
817     (".aif"   . "audio/aiff")
818     (".aifc"  . "audio/aiff")
819     (".aiff"  . "audio/aiff")
820     (".ano"   . "application/x-annotator")
821     (".au"    . "audio/ulaw")
822     (".avi"   . "video/x-msvideo")
823     (".bcpio" . "application/x-bcpio")
824     (".bin"   . "application/octet-stream")
825     (".cdf"   . "application/x-netcdr")
826     (".cpio"  . "application/x-cpio")
827     (".csh"   . "application/x-csh")
828     (".css"   . "text/css")
829     (".dvi"   . "application/x-dvi")
830     (".diff"  . "text/x-patch")
831     (".dpatch". "test/x-patch")
832     (".el"    . "application/emacs-lisp")
833     (".eps"   . "application/postscript")
834     (".etx"   . "text/x-setext")
835     (".exe"   . "application/octet-stream")
836     (".fax"   . "image/x-fax")
837     (".gif"   . "image/gif")
838     (".hdf"   . "application/x-hdf")
839     (".hqx"   . "application/mac-binhex40")
840     (".htm"   . "text/html")
841     (".html"  . "text/html")
842     (".icon"  . "image/x-icon")
843     (".ief"   . "image/ief")
844     (".jpg"   . "image/jpeg")
845     (".macp"  . "image/x-macpaint")
846     (".man"   . "application/x-troff-man")
847     (".me"    . "application/x-troff-me")
848     (".mif"   . "application/mif")
849     (".mov"   . "video/quicktime")
850     (".movie" . "video/x-sgi-movie")
851     (".mp2"   . "audio/x-mpeg")
852     (".mp3"   . "audio/x-mpeg")
853     (".mp2a"  . "audio/x-mpeg2")
854     (".mpa"   . "audio/x-mpeg")
855     (".mpa2"  . "audio/x-mpeg2")
856     (".mpe"   . "video/mpeg")
857     (".mpeg"  . "video/mpeg")
858     (".mpega" . "audio/x-mpeg")
859     (".mpegv" . "video/mpeg")
860     (".mpg"   . "video/mpeg")
861     (".mpv"   . "video/mpeg")
862     (".ms"    . "application/x-troff-ms")
863     (".nc"    . "application/x-netcdf")
864     (".nc"    . "application/x-netcdf")
865     (".oda"   . "application/oda")
866     (".patch" . "text/x-patch")
867     (".pbm"   . "image/x-portable-bitmap")
868     (".pdf"   . "application/pdf")
869     (".pgm"   . "image/portable-graymap")
870     (".pict"  . "image/pict")
871     (".png"   . "image/png")
872     (".pnm"   . "image/x-portable-anymap")
873     (".pod"   . "text/plain")
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     (".org"   . "text/x-org"))
912   "An alist of file extensions and corresponding MIME content-types.
913 This exists for you to customize the information in Lisp.  It is
914 merged with values from mailcap files by `mailcap-parse-mimetypes'.")
915
916 (defvar mailcap-mimetypes-parsed-p nil)
917
918 (defun mailcap-parse-mimetypes (&optional path force)
919   "Parse out all the mimetypes specified in a Unix-style path string PATH.
920 Components of PATH are separated by the `path-separator' character
921 appropriate for this system.  If PATH is omitted, use the value of
922 environment variable MIMETYPES if set; otherwise use a default path.
923 If FORCE, re-parse even if already parsed."
924   (interactive (list nil t))
925   (when (or (not mailcap-mimetypes-parsed-p)
926             force)
927     (cond
928      (path nil)
929      ((getenv "MIMETYPES") (setq path (getenv "MIMETYPES")))
930      ((memq system-type mailcap-poor-system-types)
931       (setq path '("~/mime.typ" "~/etc/mime.typ")))
932      (t (setq path
933               ;; mime.types seems to be the normal name, definitely so
934               ;; on current GNUish systems.  The search order follows
935               ;; that for mailcap.
936               '("~/.mime.types"
937                 "/etc/mime.types"
938                 "/usr/etc/mime.types"
939                 "/usr/local/etc/mime.types"
940                 "/usr/local/www/conf/mime.types"
941                 "~/.mime-types"
942                 "/etc/mime-types"
943                 "/usr/etc/mime-types"
944                 "/usr/local/etc/mime-types"
945                 "/usr/local/www/conf/mime-types"))))
946     (let ((fnames (reverse (if (stringp path)
947                                (split-string path path-separator t)
948                              path)))
949           fname)
950       (while fnames
951         (setq fname (car fnames))
952         (if (and (file-readable-p fname))
953             (mailcap-parse-mimetype-file fname))
954         (setq fnames (cdr fnames))))
955     (setq mailcap-mimetypes-parsed-p t)))
956
957 (defun mailcap-parse-mimetype-file (fname)
958   "Parse out a mime-types file FNAME."
959   (let (type                            ; The MIME type for this line
960         extns                           ; The extensions for this line
961         save-pos                        ; Misc. saved buffer positions
962         )
963     (with-temp-buffer
964       (insert-file-contents fname)
965       (mailcap-replace-regexp "#.*" "")
966       (mailcap-replace-regexp "\n+" "\n")
967       (mailcap-replace-regexp "[ \t]+$" "")
968       (goto-char (point-max))
969       (skip-chars-backward " \t\n")
970       (delete-region (point) (point-max))
971       (goto-char (point-min))
972       (while (not (eobp))
973         (skip-chars-forward " \t\n")
974         (setq save-pos (point))
975         (skip-chars-forward "^ \t\n")
976         (downcase-region save-pos (point))
977         (setq type (buffer-substring save-pos (point)))
978         (while (not (eolp))
979           (skip-chars-forward " \t")
980           (setq save-pos (point))
981           (skip-chars-forward "^ \t\n")
982           (setq extns (cons (buffer-substring save-pos (point)) extns)))
983         (while extns
984           (setq mailcap-mime-extensions
985                 (cons
986                  (cons (if (= (string-to-char (car extns)) ?.)
987                            (car extns)
988                          (concat "." (car extns))) type)
989                  mailcap-mime-extensions)
990                 extns (cdr extns)))))))
991
992 (defun mailcap-extension-to-mime (extn)
993   "Return the MIME content type of the file extensions EXTN."
994   (mailcap-parse-mimetypes)
995   (if (and (stringp extn)
996            (not (eq (string-to-char extn) ?.)))
997       (setq extn (concat "." extn)))
998   (cdr (assoc (downcase extn) mailcap-mime-extensions)))
999
1000 ;; Unused?
1001 (defalias 'mailcap-command-p 'executable-find)
1002
1003 (defun mailcap-mime-types ()
1004   "Return a list of MIME media types."
1005   (mailcap-parse-mimetypes)
1006   (mailcap-delete-duplicates
1007    (nconc
1008     (mapcar 'cdr mailcap-mime-extensions)
1009     (apply
1010      'nconc
1011      (mapcar
1012       (lambda (l)
1013         (delq nil
1014               (mapcar
1015                (lambda (m)
1016                  (let ((type (cdr (assq 'type (cdr m)))))
1017                    (if (equal (cadr (split-string type "/"))
1018                               "*")
1019                        nil
1020                      type)))
1021                (cdr l))))
1022       mailcap-mime-data)))))
1023
1024 ;;;
1025 ;;; Useful supplementary functions
1026 ;;;
1027
1028 (defun mailcap-file-default-commands (files)
1029   "Return a list of default commands for FILES."
1030   (mailcap-parse-mailcaps)
1031   (mailcap-parse-mimetypes)
1032   (let* ((all-mime-type
1033           ;; All unique MIME types from file extensions
1034           (mailcap-delete-duplicates
1035            (mapcar (lambda (file)
1036                      (mailcap-extension-to-mime
1037                       (file-name-extension file t)))
1038                    files)))
1039          (all-mime-info
1040           ;; All MIME info lists
1041           (mailcap-delete-duplicates
1042            (mapcar (lambda (mime-type)
1043                      (mailcap-mime-info mime-type 'all))
1044                    all-mime-type)))
1045          (common-mime-info
1046           ;; Intersection of mime-infos from different mime-types;
1047           ;; or just the first MIME info for a single MIME type
1048           (if (cdr all-mime-info)
1049               (delq nil (mapcar (lambda (mi1)
1050                                   (unless (memq nil (mapcar
1051                                                      (lambda (mi2)
1052                                                        (member mi1 mi2))
1053                                                      (cdr all-mime-info)))
1054                                     mi1))
1055                                 (car all-mime-info)))
1056             (car all-mime-info)))
1057          (commands
1058           ;; Command strings from `viewer' field of the MIME info
1059           (mailcap-delete-duplicates
1060            (delq nil (mapcar (lambda (mime-info)
1061                                (let ((command (cdr (assoc 'viewer mime-info))))
1062                                  (if (stringp command)
1063                                      (mailcap-replace-in-string
1064                                       ;; Replace mailcap's `%s' placeholder
1065                                       ;; with dired's `?' placeholder
1066                                       (mailcap-replace-in-string
1067                                        ;; Remove the final filename placeholder
1068                                        command "[ \t\n]*\\('\\)?%s\\1?[ \t\n]*\\'" "" t)
1069                                       "%s" "?" t))))
1070                              common-mime-info)))))
1071     commands))
1072
1073 (defun mailcap-view-mime (type)
1074   "View the data in the current buffer that has MIME type TYPE.
1075 `mailcap-mime-data' determines the method to use."
1076   (let ((method (mailcap-mime-info type)))
1077     (if (stringp method)
1078         (shell-command-on-region (point-min) (point-max)
1079                                  ;; Use stdin as the "%s".
1080                                  (format method "-")
1081                                  (current-buffer)
1082                                  t)
1083       (funcall method))))
1084
1085 (provide 'mailcap)
1086
1087 ;;; mailcap.el ends here