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