cda6987474264f1400dcfd027c5aca08366f38c6
[gnus] / lisp / mailcap.el
1 ;;; mailcap.el --- Functions for displaying MIME parts
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: William M. Perry <wmperry@aventail.com>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30 (require 'mail-parse)
31 (require 'mm-util)
32
33 (defvar mailcap-parse-args-syntax-table
34   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
35     (modify-syntax-entry ?' "\"" table)
36     (modify-syntax-entry ?` "\"" table)
37     (modify-syntax-entry ?{ "(" table)
38     (modify-syntax-entry ?} ")" table)
39     table)
40   "A syntax table for parsing sgml attributes.")
41
42 (defvar mailcap-mime-data
43   '(("application"
44      ("x-x509-ca-cert"
45       (viewer . ssl-view-site-cert)
46       (test . (fboundp 'ssl-view-site-cert))
47       (type . "application/x-x509-ca-cert"))
48      ("x-x509-user-cert"
49       (viewer . ssl-view-user-cert)
50       (test . (fboundp 'ssl-view-user-cert))
51       (type . "application/x-x509-user-cert"))
52      ("octet-stream"
53       (viewer . mailcap-save-binary-file)
54       (non-viewer . t)
55       (type ."application/octet-stream"))
56      ("dvi"
57       (viewer . "open %s")
58       (type   . "application/dvi")
59       (test   . (eq (mm-device-type) 'ns)))
60      ("dvi"
61       (viewer . "xdvi %s")
62       (test   . (eq (mm-device-type) 'x))
63       ("needsx11")
64       (type   . "application/dvi"))
65      ("dvi"
66       (viewer . "dvitty %s")
67       (test   . (not (getenv "DISPLAY")))
68       (type   . "application/dvi"))
69      ("emacs-lisp"
70       (viewer . mailcap-maybe-eval)
71       (type   . "application/emacs-lisp"))
72      ("x-tar"
73       (viewer . mailcap-save-binary-file)
74       (non-viewer . t)
75       (type   . "application/x-tar"))
76      ("x-latex"
77       (viewer . tex-mode)
78       (test   . (fboundp 'tex-mode))
79       (type   . "application/x-latex"))
80      ("x-tex"
81       (viewer . tex-mode)
82       (test   . (fboundp 'tex-mode))
83       (type   . "application/x-tex"))
84      ("latex"
85       (viewer . tex-mode)
86       (test   . (fboundp 'tex-mode))
87       (type   . "application/latex"))
88      ("tex"
89       (viewer . tex-mode)
90       (test   . (fboundp 'tex-mode))
91       (type   . "application/tex"))
92      ("texinfo"
93       (viewer . texinfo-mode)
94       (test   . (fboundp 'texinfo-mode))
95       (type   . "application/tex"))
96      ("zip"
97       (viewer . mailcap-save-binary-file)
98       (non-viewer . t)
99       (type   . "application/zip")
100       ("copiousoutput"))
101      ("pdf"
102       (viewer . "acroread %s")
103       (type   . "application/pdf"))
104      ("postscript"
105       (viewer . "open %s")
106       (type   . "application/postscript")
107       (test   . (eq (mm-device-type) 'ns)))
108      ("postscript"
109       (viewer . "ghostview -dSAFER %s")
110       (type . "application/postscript")
111       (test   . (eq (mm-device-type) 'x))
112       ("needsx11"))
113      ("postscript"
114       (viewer . "ps2ascii %s")
115       (type . "application/postscript")
116       (test . (not (getenv "DISPLAY")))
117       ("copiousoutput")))
118     ("audio"
119      ("x-mpeg"
120       (viewer . "maplay %s")
121       (type   . "audio/x-mpeg"))
122      (".*"
123       (viewer . "showaudio")
124       (type   . "audio/*")))
125     ("message"
126      ("rfc-*822"
127       (viewer . mm-view-message)
128       (test   . (and (featurep 'gnus)
129                      (gnus-alive-p)))
130       (type   . "message/rfc822"))
131      ("rfc-*822"
132       (viewer . vm-mode)
133       (test   . (fboundp 'vm-mode))
134       (type   . "message/rfc822"))
135      ("rfc-*822"
136       (viewer . w3-mode)
137       (test   . (fboundp 'w3-mode))
138       (type   . "message/rfc822"))
139      ("rfc-*822"
140       (viewer . view-mode)
141       (test   . (fboundp 'view-mode))
142       (type   . "message/rfc822"))
143      ("rfc-*822"
144       (viewer . fundamental-mode)
145       (type   . "message/rfc822")))
146     ("image"
147      ("x-xwd"
148       (viewer  . "xwud -in %s")
149       (type    . "image/x-xwd")
150       ("compose" . "xwd -frame > %s")
151       (test    . (eq (mm-device-type) 'x))
152       ("needsx11"))
153      ("x11-dump"
154       (viewer . "xwud -in %s")
155       (type . "image/x-xwd")
156       ("compose" . "xwd -frame > %s")
157       (test   . (eq (mm-device-type) 'x))
158       ("needsx11"))
159      ("windowdump"
160       (viewer . "xwud -in %s")
161       (type . "image/x-xwd")
162       ("compose" . "xwd -frame > %s")
163       (test   . (eq (mm-device-type) 'x))
164       ("needsx11"))
165      (".*"
166       (viewer . "aopen %s")
167       (type   . "image/*")
168       (test   . (eq (mm-device-type) 'ns)))
169      (".*"
170       (viewer . "display %s")
171       (type . "image/*")
172       (test   . (eq (mm-device-type) 'x))
173       ("needsx11"))
174      (".*"
175       (viewer . "ee %s")
176       (type . "image/*")
177       (test   . (eq (mm-device-type) 'x))
178       ("needsx11")))
179     ("text"
180      ("plain"
181       (viewer  . w3-mode)
182       (test    . (fboundp 'w3-mode))
183       (type    . "text/plain"))
184      ("plain"
185       (viewer  . view-mode)
186       (test    . (fboundp 'view-mode))
187       (type    . "text/plain"))
188      ("plain"
189       (viewer  . fundamental-mode)
190       (type    . "text/plain"))
191      ("enriched"
192       (viewer . enriched-decode-region)
193       (test   . (fboundp 'enriched-decode))
194       (type   . "text/enriched"))
195      ("html"
196       (viewer . mm-w3-prepare-buffer)
197       (test   . (fboundp 'w3-prepare-buffer))
198       (type   . "text/html")))
199     ("video"
200      ("mpeg"
201       (viewer . "mpeg_play %s")
202       (type   . "video/mpeg")
203       (test   . (eq (mm-device-type) 'x))
204       ("needsx11")))
205     ("x-world"
206      ("x-vrml"
207       (viewer  . "webspace -remote %s -URL %u")
208       (type    . "x-world/x-vrml")
209       ("description"
210        "VRML document")))
211     ("archive"
212      ("tar"
213       (viewer . tar-mode)
214       (type . "archive/tar")
215       (test . (fboundp 'tar-mode)))))
216   "The mailcap structure is an assoc list of assoc lists.
217 1st assoc list is keyed on the major content-type
218 2nd assoc list is keyed on the minor content-type (which can be a regexp)
219
220 Which looks like:
221 -----------------
222  ((\"application\"
223    (\"postscript\" . <info>))
224   (\"text\"
225    (\"plain\" . <info>)))
226
227 Where <info> is another assoc list of the various information
228 related to the mailcap RFC.  This is keyed on the lowercase
229 attribute name (viewer, test, etc).  This looks like:
230  ((viewer . viewerinfo)
231   (test   . testinfo)
232   (xxxx   . \"string\"))
233
234 Where viewerinfo specifies how the content-type is viewed.  Can be
235 a string, in which case it is run through a shell, with
236 appropriate parameters, or a symbol, in which case the symbol is
237 funcall'd, with the buffer as an argument.
238
239 testinfo is a list of strings, or nil.  If nil, it means the
240 viewer specified is always valid.  If it is a list of strings,
241 these are used to determine whether a viewer passes the 'test' or
242 not.")
243
244 (defvar mailcap-download-directory nil
245   "*Where downloaded files should go by default.")
246
247 (defvar mailcap-temporary-directory
248   (cond ((fboundp 'temp-directory) (temp-directory))
249         ((boundp 'temporary-file-directory) temporary-file-directory)
250         ("/tmp/"))
251   "*Where temporary files go.")
252
253 ;;;
254 ;;; Utility functions
255 ;;;
256
257 (defun mailcap-generate-unique-filename (&optional fmt)
258   "Generate a unique filename in mailcap-temporary-directory."
259   (if (not fmt)
260       (let ((base (format "mailcap-tmp.%d" (user-real-uid)))
261             (fname "")
262             (x 0))
263         (setq fname (format "%s%d" base x))
264         (while (file-exists-p
265                 (expand-file-name fname mailcap-temporary-directory))
266           (setq x (1+ x)
267                 fname (concat base (int-to-string x))))
268         (expand-file-name fname mailcap-temporary-directory))
269     (let ((base (concat "mm" (int-to-string (user-real-uid))))
270           (fname "")
271           (x 0))
272       (setq fname (format fmt (concat base (int-to-string x))))
273       (while (file-exists-p
274               (expand-file-name fname mailcap-temporary-directory))
275         (setq x (1+ x)
276               fname (format fmt (concat base (int-to-string x)))))
277       (expand-file-name fname mailcap-temporary-directory))))
278
279 (defun mailcap-save-binary-file ()
280   (goto-char (point-min))
281   (unwind-protect
282       (let ((file (read-file-name
283                    "Filename to save as: "
284                    (or mailcap-download-directory "~/")))
285             (require-final-newline nil))
286         (write-region (point-min) (point-max) file))
287     (kill-buffer (current-buffer))))
288
289 (defun mailcap-maybe-eval ()
290   "Maybe evaluate a buffer of emacs lisp code."
291   (if (yes-or-no-p "This is emacs-lisp code, evaluate it? ")
292       (eval-buffer (current-buffer))
293     (emacs-lisp-mode)))
294
295 ;;;
296 ;;; The mailcap parser
297 ;;;
298
299 (defun mailcap-replace-regexp (regexp to-string)
300   ;; Quiet replace-regexp.
301   (goto-char (point-min))
302   (while (re-search-forward regexp nil t)
303     (replace-match to-string t nil)))
304
305 (defvar mailcap-parsed-p nil)
306
307 (defun mailcap-parse-mailcaps (&optional path force)
308   "Parse out all the mailcaps specified in a unix-style path string PATH.
309 If FORCE, re-parse even if already parsed."
310   (interactive (list nil t))
311   (when (or (not mailcap-parsed-p)
312             force)
313     (cond
314      (path nil)
315      ((getenv "MAILCAPS") (setq path (getenv "MAILCAPS")))
316      ((memq system-type '(ms-dos ms-windows windows-nt))
317       (setq path (mapconcat 'expand-file-name
318                             '("~/mail.cap" "~/etc/mail.cap" "~/.mailcap")
319                             ";")))
320      (t (setq path (mapconcat 'expand-file-name
321                               '("~/.mailcap"
322                                 "/etc/mailcap:/usr/etc/mailcap"
323                                 "/usr/local/etc/mailcap") ":"))))
324     (let ((fnames (reverse
325                    (split-string
326                     path (if (memq system-type
327                                    '(ms-dos ms-windows windows-nt))
328                              ";"
329                            ":"))))
330           fname)
331       (while fnames
332         (setq fname (car fnames))
333         (if (and (file-exists-p fname) (file-readable-p fname)
334                  (file-regular-p fname))
335             (mailcap-parse-mailcap (car fnames)))
336         (setq fnames (cdr fnames))))
337     (setq mailcap-parsed-p t)))
338
339 (defun mailcap-parse-mailcap (fname)
340   ;; Parse out the mailcap file specified by FNAME
341   (let (major                           ; The major mime type (image/audio/etc)
342         minor                           ; The minor mime type (gif, basic, etc)
343         save-pos                        ; Misc saved positions used in parsing
344         viewer                          ; How to view this mime type
345         info                            ; Misc info about this mime type
346         )
347     (with-temp-buffer
348       (insert-file-contents fname)
349       (set-syntax-table mailcap-parse-args-syntax-table)
350       (mailcap-replace-regexp "#.*" "") ; Remove all comments
351       (mailcap-replace-regexp "\n+" "\n") ; And blank lines
352       (mailcap-replace-regexp "\\\\[ \t\n]+" " ") ; And collapse spaces
353       (mailcap-replace-regexp (concat (regexp-quote "\\") "[ \t]*\n") "")
354       (goto-char (point-max))
355       (skip-chars-backward " \t\n")
356       (delete-region (point) (point-max))
357       (goto-char (point-min))
358       (while (not (eobp))
359         (skip-chars-forward " \t\n")
360         (setq save-pos (point)
361               info nil)
362         (skip-chars-forward "^/; \t\n")
363         (downcase-region save-pos (point))
364         (setq major (buffer-substring save-pos (point)))
365         (skip-chars-forward " \t\n")
366         (setq minor "")
367         (when (eq (char-after) ?/)
368           (forward-char)
369           (skip-chars-forward " \t\n")
370           (setq save-pos (point))
371           (skip-chars-forward "^; \t\n")
372           (downcase-region save-pos (point))
373           (setq minor
374                 (cond
375                  ((eq ?* (or (char-after save-pos) 0)) ".*")
376                  ((= (point) save-pos) ".*")
377                  (t (regexp-quote (buffer-substring save-pos (point)))))))
378         (skip-chars-forward " \t\n")
379         ;;; Got the major/minor chunks, now for the viewers/etc
380         ;;; The first item _must_ be a viewer, according to the
381         ;;; RFC for mailcap files (#1343)
382         (setq viewer "")
383         (when (eq (char-after) ?\;) 
384           (forward-char)
385           (skip-chars-forward " \t\n")
386           (setq save-pos (point))
387           (skip-chars-forward "^;\n")
388           ;; skip \;
389           (while (eq (char-before) ?\\)
390             (backward-delete-char 1)
391             (forward-char)
392             (skip-chars-forward "^;\n"))
393           (if (eq (or (char-after save-pos) 0) ?')
394               (setq viewer (progn
395                              (narrow-to-region (1+ save-pos) (point))
396                              (goto-char (point-min))
397                              (prog1
398                                  (read (current-buffer))
399                                (goto-char (point-max))
400                                (widen))))
401             (setq viewer (buffer-substring save-pos (point)))))
402         (setq save-pos (point))
403         (end-of-line)
404         (unless (equal viewer "") 
405           (setq info (nconc (list (cons 'viewer viewer)
406                                   (cons 'type (concat major "/"
407                                                       (if (string= minor ".*")
408                                                           "*" minor))))
409                             (mailcap-parse-mailcap-extras save-pos (point))))
410           (mailcap-mailcap-entry-passes-test info)
411           (mailcap-add-mailcap-entry major minor info))))))
412
413 (defun mailcap-parse-mailcap-extras (st nd)
414   ;; Grab all the extra stuff from a mailcap entry
415   (let (
416         name                            ; From name=
417         value                           ; its value
418         results                         ; Assoc list of results
419         name-pos                        ; Start of XXXX= position
420         val-pos                         ; Start of value position
421         done                            ; Found end of \'d ;s?
422         )
423     (save-restriction
424       (narrow-to-region st nd)
425       (goto-char (point-min))
426       (skip-chars-forward " \n\t;")
427       (while (not (eobp))
428         (setq done nil)
429         (setq name-pos (point))
430         (skip-chars-forward "^ \n\t=;")
431         (downcase-region name-pos (point))
432         (setq name (buffer-substring name-pos (point)))
433         (skip-chars-forward " \t\n")
434         (if (not (eq (char-after (point)) ?=)) ; There is no value
435             (setq value t)
436           (skip-chars-forward " \t\n=")
437           (setq val-pos (point))
438           (if (memq (char-after val-pos) '(?\" ?'))
439               (progn
440                 (setq val-pos (1+ val-pos))
441                 (condition-case nil
442                     (progn
443                       (forward-sexp 1)
444                       (backward-char 1))
445                   (error (goto-char (point-max)))))
446             (while (not done)
447               (skip-chars-forward "^;")
448               (if (eq (char-after (1- (point))) ?\\ )
449                   (progn
450                     (subst-char-in-region (1- (point)) (point) ?\\ ? )
451                     (skip-chars-forward ";"))
452                 (setq done t))))
453           (setq value (buffer-substring val-pos (point))))
454         (setq results (cons (cons name value) results))
455         (skip-chars-forward " \";\n\t"))
456       results)))
457
458 (defun mailcap-mailcap-entry-passes-test (info)
459   ;; Return t iff a mailcap entry passes its test clause or no test
460   ;; clause is present.
461   (let (status                          ; Call-process-regions return value
462         (test (assq 'test info))        ; The test clause
463         )
464     (setq status (and test (split-string (cdr test) " ")))
465     (if (and (or (assoc "needsterm" info)
466                  (assoc "needsterminal" info)
467                  (assoc "needsx11" info))
468              (not (getenv "DISPLAY")))
469         (setq status nil)
470       (cond
471        ((and (equal (nth 0 status) "test")
472              (equal (nth 1 status) "-n")
473              (or (equal (nth 2 status) "$DISPLAY")
474                  (equal (nth 2 status) "\"$DISPLAY\"")))
475         (setq status (if (getenv "DISPLAY") t nil)))
476        ((and (equal (nth 0 status) "test")
477              (equal (nth 1 status) "-z")
478              (or (equal (nth 2 status) "$DISPLAY")
479                  (equal (nth 2 status) "\"$DISPLAY\"")))
480         (setq status (if (getenv "DISPLAY") nil t)))
481        (test nil)
482        (t nil)))
483     (and test (listp test) (setcdr test status))))
484
485 ;;;
486 ;;; The action routines.
487 ;;;
488
489 (defun mailcap-possible-viewers (major minor)
490   ;; Return a list of possible viewers from MAJOR for minor type MINOR
491   (let ((exact '())
492         (wildcard '()))
493     (while major
494       (cond
495        ((equal (car (car major)) minor)
496         (setq exact (cons (cdr (car major)) exact)))
497        ((and minor (string-match (car (car major)) minor))
498         (setq wildcard (cons (cdr (car major)) wildcard))))
499       (setq major (cdr major)))
500     (nconc (nreverse exact) (nreverse wildcard))))
501
502 (defun mailcap-unescape-mime-test (test type-info)
503   (let (save-pos save-chr subst)
504     (cond
505      ((symbolp test) test)
506      ((and (listp test) (symbolp (car test))) test)
507      ((or (stringp test)
508           (and (listp test) (stringp (car test))
509                (setq test (mapconcat 'identity test " "))))
510       (with-temp-buffer
511         (insert test)
512         (goto-char (point-min))
513         (while (not (eobp))
514           (skip-chars-forward "^%")
515           (if (/= (- (point)
516                      (progn (skip-chars-backward "\\\\")
517                             (point)))
518                   0)                    ; It is an escaped %
519               (progn
520                 (delete-char 1)
521                 (skip-chars-forward "%."))
522             (setq save-pos (point))
523             (skip-chars-forward "%")
524             (setq save-chr (char-after (point)))
525             (cond
526              ((null save-chr) nil)
527              ((= save-chr ?t)
528               (delete-region save-pos (progn (forward-char 1) (point)))
529               (insert (or (cdr (assq 'type type-info)) "\"\"")))
530              ((= save-chr ?M)
531               (delete-region save-pos (progn (forward-char 1) (point)))
532               (insert "\"\""))
533              ((= save-chr ?n)
534               (delete-region save-pos (progn (forward-char 1) (point)))
535               (insert "\"\""))
536              ((= save-chr ?F)
537               (delete-region save-pos (progn (forward-char 1) (point)))
538               (insert "\"\""))
539              ((= save-chr ?{)
540               (forward-char 1)
541               (skip-chars-forward "^}")
542               (downcase-region (+ 2 save-pos) (point))
543