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