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