parse-time.el: Use cl-lib as much as possible following the 2014-09-26 change in...
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- MIME media types configuration
2
3 ;; Copyright (C) 1998-2014 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 . "gv -safer %s")
157       (type . "application/pdf")
158       (test . window-system)
159       ("print" . ,(concat "pdf2ps %s - | " mailcap-print-command)))
160      ("pdf"
161       (viewer . "gpdf %s")
162       (type . "application/pdf")
163       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
164       (test . (eq window-system 'x)))
165      ("pdf"
166       (viewer . "xpdf %s")
167       (type . "application/pdf")
168       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
169       (test . (eq window-system 'x)))
170      ("pdf"
171       (viewer . ,(concat "pdftotext %s -"))
172       (type   . "application/pdf")
173       ("print" . ,(concat "pdftops %s - | " mailcap-print-command))
174       ("copiousoutput"))
175      ("postscript"
176       (viewer . "gv -safer %s")
177       (type . "application/postscript")
178       (test   . window-system)
179       ("print" . ,(concat mailcap-print-command " %s"))
180       ("needsx11"))
181      ("postscript"
182       (viewer . "ghostview -dSAFER %s")
183       (type . "application/postscript")
184       (test   . (eq window-system 'x))
185       ("print" . ,(concat mailcap-print-command " %s"))
186       ("needsx11"))
187      ("postscript"
188       (viewer . "ps2ascii %s")
189       (type . "application/postscript")
190       (test . (not (getenv "DISPLAY")))
191       ("print" . ,(concat mailcap-print-command " %s"))
192       ("copiousoutput"))
193      ("sieve"
194       (viewer . sieve-mode)
195       (test   . (fboundp '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       (test   . (fboundp 'vm-mode))
217       (type   . "message/rfc822"))
218      ("rfc-*822"
219       (viewer . view-mode)
220       (type   . "message/rfc822")))
221     ("image"
222      ("x-xwd"
223       (viewer  . "xwud -in %s")
224       (type    . "image/x-xwd")
225       ("compose" . "xwd -frame > %s")
226       (test    . (eq window-system 'x))
227       ("needsx11"))
228      ("x11-dump"
229       (viewer . "xwud -in %s")
230       (type . "image/x-xwd")
231       ("compose" . "xwd -frame > %s")
232       (test   . (eq window-system 'x))
233       ("needsx11"))
234      ("windowdump"
235       (viewer . "xwud -in %s")
236       (type . "image/x-xwd")
237       ("compose" . "xwd -frame > %s")
238       (test   . (eq window-system 'x))
239       ("needsx11"))
240      (".*"
241       (viewer . "display %s")
242       (type . "image/*")
243       (test   . (eq window-system 'x))
244       ("needsx11"))
245      (".*"
246       (viewer . "ee %s")
247       (type . "image/*")
248       (test   . (eq window-system 'x))
249       ("needsx11")))
250     ("text"
251      ("plain"
252       (viewer  . view-mode)
253       (test    . (fboundp 'view-mode))
254       (type    . "text/plain"))
255      ("plain"
256       (viewer  . fundamental-mode)
257       (type    . "text/plain"))
258      ("enriched"
259       (viewer . enriched-decode)
260       (test   . (fboundp 'enriched-decode))
261       (type   . "text/enriched"))
262      ("dns"
263       (viewer . dns-mode)
264       (test   . (fboundp 'dns-mode))
265       (type   . "text/dns")))
266     ("video"
267      ("mpeg"
268       (viewer . "mpeg_play %s")
269       (type   . "video/mpeg")
270       (test   . (eq window-system 'x))
271       ("needsx11")))
272     ("x-world"
273      ("x-vrml"
274       (viewer  . "webspace -remote %s -URL %u")
275       (type    . "x-world/x-vrml")
276       ("description"
277        "VRML document")))
278     ("archive"
279      ("tar"
280       (viewer . tar-mode)
281       (type . "archive/tar")
282       (test . (fboundp 'tar-mode)))))
283   "The mailcap structure is an assoc list of assoc lists.
284 1st assoc list is keyed on the major content-type
285 2nd assoc list is keyed on the minor content-type (which can be a regexp)
286
287 Which looks like:
288 -----------------
289  ((\"application\"
290    (\"postscript\" . <info>))
291   (\"text\"
292    (\"plain\" . <info>)))
293
294 Where <info> is another assoc list of the various information
295 related to the mailcap RFC 1524.  This is keyed on the lowercase
296 attribute name (viewer, test, etc).  This looks like:
297  ((viewer . VIEWERINFO)
298   (test   . TESTINFO)
299   (xxxx   . \"STRING\")
300   FLAG)
301
302 Where VIEWERINFO specifies how the content-type is viewed.  Can be
303 a string, in which case it is run through a shell, with
304 appropriate parameters, or a symbol, in which case the symbol is
305 `funcall'ed, with the buffer as an argument.
306
307 TESTINFO is a test for the viewer's applicability, or nil.  If nil, it
308 means the viewer is always valid.  If it is a Lisp function, it is
309 called with a list of items from any extra fields from the
310 Content-Type header as argument to return a boolean value for the
311 validity.  Otherwise, if it is a non-function Lisp symbol or list
312 whose car is a symbol, it is `eval'led to yield the validity.  If it
313 is a string or list of strings, it represents a shell command to run
314 to return a true or false shell value for the validity.")
315 (put 'mailcap-mime-data 'risky-local-variable t)
316
317 (defcustom mailcap-download-directory nil
318   "*Directory to which `mailcap-save-binary-file' downloads files by default.
319 nil means your home directory."
320   :type '(choice (const :tag "Home directory" nil)
321                  directory)
322   :group 'mailcap)
323
324 (defvar mailcap-poor-system-types
325   '(ms-dos windows-nt)
326   "Systems that don't have a Unix-like directory hierarchy.")
327
328 ;;;
329 ;;; Utility functions
330 ;;;
331
332 (defun mailcap-save-binary-file ()
333   (goto-char (point-min))
334   (unwind-protect
335       (let ((file (read-file-name
336                    "Filename to save as: "
337                    (or mailcap-download-directory "~/")))
338             (require-final-newline nil))
339         (write-region (point-min) (point-max) file))
340     (kill-buffer (current-buffer))))
341
342 (defvar mailcap-maybe-eval-warning
343   "*** WARNING ***
344
345 This MIME part contains untrusted and possibly harmful content.
346 If you evaluate the Emacs Lisp code contained in it, a lot of nasty
347 things can happen.  Please examine the code very carefully before you
348 instruct Emacs to evaluate it.  You can browse the buffer containing
349 the code using \\[scroll-other-window].
350
351 If you are unsure what to do, please answer \"no\"."
352   "Text of warning message displayed by `mailcap-maybe-eval'.
353 Make sure that this text consists only of few text lines.  Otherwise,
354 Gnus might fail to display all of it.")
355
356 (defun mailcap-maybe-eval ()
357   "Maybe evaluate a buffer of Emacs Lisp code."
358   (let ((lisp-buffer (current-buffer)))
359     (goto-char (point-min))
360     (when
361         (save-window-excursion
362           (delete-other-windows)
363           (let ((buffer (get-buffer-create (generate-new-buffer-name
364                                             "*Warning*"))))
365             (unwind-protect
366                 (with-current-buffer buffer
367                   (insert (substitute-command-keys
368                            mailcap-maybe-eval-warning))
369                   (goto-char (point-min))
370                   (display-buffer buffer)
371                   (yes-or-no-p "This is potentially dangerous emacs-lisp code, evaluate it? "))
372               (kill-buffer buffer))))
373       (eval-buffer (current-buffer)))
374     (when (buffer-live-p lisp-buffer)
375       (with-current-buffer lisp-buffer
376         (emacs-lisp-mode)))))
377
378
379 ;;;
380 ;;; The mailcap parser
381 ;;;
382
383 (defun mailcap-replace-regexp (regexp to-string)
384   ;; Quiet replace-regexp.
385   (goto-char (point-min))
386   (while (re-search-forward regexp nil t)
387     (replace-match to-string t nil)))
388
389 (defvar mailcap-parsed-p nil)
390
391 (defun mailcap-parse-mailcaps (&optional path force)
392   "Parse out all the mailcaps specified in a path string PATH.
393 Components of PATH are separated by the `path-separator' character
394 appropriate for this system.  If FORCE, re-parse even if already
395 parsed.  If PATH is omitted, use the value of environment variable
396 MAILCAPS if set; otherwise (on Unix) use the path from RFC 1524, plus
397 /usr/local/etc/mailcap."
398   (interactive (list nil t))
399   (when (or (not mailcap-parsed-p)
400             force)
401     (cond
402      (path nil)
403      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
404      ((memq system-type mailcap-poor-system-types)
405       (setq path '("~/.mailcap" "~/mail.cap" "~/etc/mail.cap")))
406      (t (setq path
407               ;; This is per RFC 1524, specifically
408               ;; with /usr before /usr/local.
409               '("~/.mailcap" "/etc/mailcap" "/usr/etc/mailcap"
410                 "/usr/local/etc/mailcap"))))
411     (let ((fnames (reverse
412                    (if (stringp path)
413                        (split-string path path-separator t)
414                      path)))
415           fname)
416       (while fnames
417         (setq fname (car fnames))
418         (if (and (file-readable-p fname)
419                  (file-regular-p fname))
420             (mailcap-parse-mailcap fname))
421         (setq fnames (cdr fnames))))
422       (setq mailcap-parsed-p t)))
423
424 (defun mailcap-parse-mailcap (fname)
425   "Parse out the mailcap file specified by FNAME."
426   (let (major                           ; The major mime type (image/audio/etc)
427         minor                           ; The minor mime type (gif, basic, etc)
428         save-pos                        ; Misc saved positions used in parsing
429         viewer                          ; How to view this mime type
430         info                            ; Misc info about this mime type
431         )
432     (with-temp-buffer
433       (insert-file-contents fname)
434       (set-syntax-table mailcap-parse-args-syntax-table)
435       (mailcap-replace-regexp "#.*" "") ; Remove all comments
436       (mailcap-replace-regexp "\\\\[ \t]*\n" " ") ; And collapse spaces
437       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
438       (goto-char (point-max))
439       (skip-chars-backward " \t\n")
440       (delete-region (point) (point-max))
441       (while (not (bobp))
442         (skip-chars-backward " \t\n")
443         (beginning-of-line)
444         (setq save-pos (point)
445               info nil)
446         (skip-chars-forward "^/; \t\n")
447         (downcase-region save-pos (point))
448         (setq major (buffer-substring save-pos (point)))
449         (skip-chars-forward " \t")
450         (setq minor "")
451         (when (eq (char-after) ?/)
452           (forward-char)
453           (skip-chars-forward " \t")
454           (setq save-pos (point))
455           (skip-chars-forward "^; \t\n")
456           (downcase-region save-pos (point))
457           (setq minor
458                 (cond
459                  ((eq ?* (or (char-after save-pos) 0)) ".*")
460                  ((= (point) save-pos) ".*")
461                  (t (regexp-quote (buffer-substring save-pos (point)))))))
462         (skip-chars-forward " \t")
463         ;;; Got the major/minor chunks, now for the viewers/etc
464         ;;; The first item _must_ be a viewer, according to the
465         ;;; RFC for mailcap files (#1524)
466         (setq viewer "")
467         (when (eq (char-after) ?\;)
468           (forward-char)
469           (skip-chars-forward " \t")
470           (setq save-pos (point))
471           (skip-chars-forward "^;\n")
472           ;; skip \;
473           (while (eq (char-before) ?\\)
474             (backward-delete-char 1)
475             (forward-char)
476             (skip-chars-forward "^;\n"))
477           (if (eq (or (char-after save-pos) 0) ?')
478               (setq viewer (progn
479                              (narrow-to-region (1+ save-pos) (point))
480                              (goto-char (point-min))
481                              (prog1
482                                  (read (current-buffer))
483                                (goto-char (point-max))
484                                (widen))))
485             (setq viewer (buffer-substring save-pos (point)))))
486         (setq save-pos (point))
487         (end-of-line)
488         (unless (equal viewer "")
489           (setq info (nconc (list (cons 'viewer viewer)
490                                   (cons 'type (concat major "/"
491                                                       (if (string= minor ".*")
492                                                           "*" minor))))
493                             (mailcap-parse-mailcap-extras save-pos (point))))
494           (mailcap-mailcap-entry-passes-test info)
495           (mailcap-add-mailcap-entry major minor info))
496         (beginning-of-line)))))
497
498 (defun mailcap-parse-mailcap-extras (st nd)
499   "Grab all the extra stuff from a mailcap entry."
500   (let (
501         name                            ; From name=
502         value                           ; its value
503         results                         ; Assoc list of results
504         name-pos                        ; Start of XXXX= position
505         val-pos                         ; Start of value position
506         done                            ; Found end of \'d ;s?
507         )
508     (save-restriction
509       (narrow-to-region st nd)
510       (goto-char (point-min))
511       (skip-chars-forward " \n\t;")
512       (while (not (eobp))
513         (setq done nil)
514         (setq name-pos (point))
515         (skip-chars-forward "^ \n\t=;")
516         (downcase-region name-pos (point))
517         (setq name (buffer-substring name-pos (point)))
518         (skip-chars-forward " \t\n")
519         (if (not (eq (char-after (point)) ?=)) ; There is no value
520             (setq value t)
521           (skip-chars-forward " \t\n=")
522           (setq val-pos (point))
523           (if (memq (char-after val-pos) '(?\" ?'))
524               (progn
525                 (setq val-pos (1+ val-pos))
526                 (condition-case nil
527                     (progn
528                       (forward-sexp 1)
529                       (backward-char 1))
530                   (error (goto-char (point-max)))))
531             (while (not done)
532               (skip-chars-forward "^;")
533               (if (eq (char-after (1- (point))) ?\\ )
534                   (progn
535                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
536                     (skip-chars-forward ";"))
537                 (setq done t))))
538           (setq value (buffer-substring val-pos (point))))
539         ;; `test' as symbol, others like "copiousoutput" and "needsx11" as
540         ;; strings
541         (setq results (cons (cons (if (string-equal name "test")
542                                       'test
543                                     name)
544                                   value) results))
545         (skip-chars-forward " \";\n\t"))
546       results)))
547
548 (defun mailcap-mailcap-entry-passes-test (info)
549   "Return non-nil if mailcap entry INFO passes its test clause.
550 Also return non-nil if no test clause is present."
551   (let ((test (assq 'test info))        ; The test clause
552         status)
553     (setq status (and test (split-string (cdr test) " ")))
554     (if (and (or (assoc "needsterm" info)
555                  (assoc "needsterminal" info)
556                  (assoc "needsx11" info))
557              (not (getenv "DISPLAY")))
558         (setq status nil)
559       (cond
560        ((and (equal (nth 0 status) "test")
561              (equal (nth 1 status) "-n")
562              (or (equal (nth 2 status) "$DISPLAY")
563                  (equal (nth 2 status) "\"$DISPLAY\"")))
564         (setq status (if (getenv "DISPLAY") t nil)))
565        ((and (equal (nth 0 status) "test")
566              (equal (nth 1 status) "-z")
567              (or (equal (nth 2 status) "$DISPLAY")
568                  (equal (nth 2 status) "\"$DISPLAY\"")))
569         (setq status (if (getenv "DISPLAY") nil t)))
570        (test nil)
571        (t nil)))
572     (and test (listp test) (setcdr test status))))
573
574 ;;;
575 ;;; The action routines.
576 ;;;
577
578 (defun mailcap-possible-viewers (major minor)
579   "Return a list of possible viewers from MAJOR for minor type MINOR."
580   (let ((exact '())
581         (wildcard '()))
582     (while major
583       (cond
584        ((equal (car (car major)) minor)
585         (setq exact (cons (cdr (car major)) exact)))
586        ((and minor (string-match (concat "^" (car (car major)) "$") minor))
587         (setq wildcard (cons (cdr (car major)) wildcard))))
588       (setq major (cdr major)))
589     (nconc exact wildcard)))
590
591 (defun mailcap-unescape-mime-test (test type-info)
592   (let (save-pos save-chr subst)
593     (cond
594      ((symbolp test) test)
595      ((and (listp test) (symbolp (car test))) test)
596      ((or (stringp test)
597           (and (listp test) (stringp (car test))
598                (setq test (mapconcat 'identity test " "))))
599       (with-temp-buffer
600         (insert test)
601         (goto-char (point-min))
602         (while (not (eobp))
603           (skip-chars-forward "^%")
604           (if (/= (- (point)
605                      (progn (skip-chars-backward "\\\\")
606                             (point)))
607                   0)                    ; It is an escaped %
608               (progn
609                 (delete-char 1)
610                 (skip-chars-forward "%."))
611             (setq save-pos (point))
612             (skip-chars-forward "%")
613             (setq save-chr (char-after (point)))
614             ;; Escapes:
615             ;; %s: name of a file for the body data
616             ;; %t: content-type
617             ;; %{<parameter name}: value of parameter in mailcap entry
618             ;; %n: number of sub-parts for multipart content-type
619             ;; %F: a set of content-type/filename pairs for multiparts
620             (cond
621              ((null save-chr) nil)
622              ((= save-chr ?t)
623               (delete-region save-pos (progn (forward-char 1) (point)))
624               (insert (or (cdr (assq 'type type-info)) "\"\"")))
625              ((memq save-chr '(?M ?n ?F))
626               (delete-region save-pos (progn (forward-char 1) (point)))
627               (insert "\"\""))
628              ((= save-chr ?{)
629               (forward-char 1)
630               (skip-chars-forward "^}")
631               (downcase-region (+ 2 save-pos) (point))
632               (setq subst (buffer-substring (+ 2 save-pos) (point)))
633               (delete-region save-pos (1+ (point)))
634               (insert (or (cdr (assoc subst type-info)) "\"\"")))
635              (t nil))))
636         (buffer-string)))
637      (t (error "Bad value to mailcap-unescape-mime-test: %s" test)))))
638
639 (defvar mailcap-viewer-test-cache nil)
640
641 (defun mailcap-viewer-passes-test (viewer-info type-info)
642   "Return non-nil if viewer specified by VIEWER-INFO passes its test clause.
643 Also return non-nil if it has no test clause.  TYPE-INFO is an argument
644 to supply to the test."
645   (let* ((test-info (assq 'test viewer-info))
646          (test (cdr test-info))
647          (otest test)
648          (viewer (cdr (assoc 'viewer viewer-info)))
649          (default-directory (expand-file-name "~/"))
650          status parsed-test cache result)
651     (cond ((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
749         major-info                      ; (assoc major mailcap-mime-data)
750         minor-info                      ; (assoc minor major-info)
751         test                            ; current test proc.
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 (provide 'mailcap)
1064
1065 ;;; mailcap.el ends here