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