(article-verify-x-pgp-sig): Autoload "mm-uu".
[elisp/gnus.git-] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mail-parse)
28 (require 'gnus-mailcap)
29 (require 'mm-bodies)
30 (eval-when-compile (require 'cl))
31
32 (eval-and-compile
33   (autoload 'mm-inline-partial "mm-partial")
34   (autoload 'mm-inline-external-body "mm-extern"))
35
36 (defgroup mime-display ()
37   "Display of MIME in mail and news articles."
38   :link '(custom-manual "(emacs-mime)Customization")
39   :group 'mail
40   :group 'news
41   :group 'multimedia)
42
43 (defgroup mime-security ()
44   "MIME security in mail and news articles."
45   :link '(custom-manual "(emacs-mime)Customization")
46   :group 'mail
47   :group 'news
48   :group 'multimedia)
49
50 ;;; Convenience macros.
51
52 (defmacro mm-handle-buffer (handle)
53   `(nth 0 ,handle))
54 (defmacro mm-handle-type (handle)
55   `(nth 1 ,handle))
56 (defsubst mm-handle-media-type (handle)
57   (if (stringp (car handle))
58       (car handle)
59     (car (mm-handle-type handle))))
60 (defsubst mm-handle-media-supertype (handle)
61   (car (split-string (mm-handle-media-type handle) "/")))
62 (defsubst mm-handle-media-subtype (handle)
63   (cadr (split-string (mm-handle-media-type handle) "/")))
64 (defmacro mm-handle-encoding (handle)
65   `(nth 2 ,handle))
66 (defmacro mm-handle-undisplayer (handle)
67   `(nth 3 ,handle))
68 (defmacro mm-handle-set-undisplayer (handle function)
69   `(setcar (nthcdr 3 ,handle) ,function))
70 (defmacro mm-handle-disposition (handle)
71   `(nth 4 ,handle))
72 (defmacro mm-handle-description (handle)
73   `(nth 5 ,handle))
74 (defmacro mm-handle-cache (handle)
75   `(nth 6 ,handle))
76 (defmacro mm-handle-set-cache (handle contents)
77   `(setcar (nthcdr 6 ,handle) ,contents))
78 (defmacro mm-handle-id (handle)
79   `(nth 7 ,handle))
80 (defmacro mm-handle-multipart-original-buffer (handle)
81   `(get-text-property 0 'buffer (car ,handle)))
82 (defmacro mm-handle-multipart-ctl-parameter (handle parameter)
83   `(get-text-property 0 ,parameter (car ,handle)))
84
85 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
86                                     disposition description cache
87                                     id)
88   `(list ,buffer ,type ,encoding ,undisplayer
89          ,disposition ,description ,cache ,id))
90
91 (defcustom mm-inline-media-tests
92   '(("image/jpeg"
93      mm-inline-image
94      (lambda (handle)
95        (mm-valid-and-fit-image-p 'jpeg handle)))
96     ("image/png"
97      mm-inline-image
98      (lambda (handle)
99        (mm-valid-and-fit-image-p 'png handle)))
100     ("image/gif"
101      mm-inline-image
102      (lambda (handle)
103        (mm-valid-and-fit-image-p 'gif handle)))
104     ("image/tiff"
105      mm-inline-image
106      (lambda (handle)
107        (mm-valid-and-fit-image-p 'tiff handle)) )
108     ("image/xbm"
109      mm-inline-image
110      (lambda (handle)
111        (mm-valid-and-fit-image-p 'xbm handle)))
112     ("image/x-xbitmap"
113      mm-inline-image
114      (lambda (handle)
115        (mm-valid-and-fit-image-p 'xbm handle)))
116     ("image/xpm"
117      mm-inline-image
118      (lambda (handle)
119        (mm-valid-and-fit-image-p 'xpm handle)))
120     ("image/x-pixmap"
121      mm-inline-image
122      (lambda (handle)
123        (mm-valid-and-fit-image-p 'xpm handle)))
124     ("image/bmp"
125      mm-inline-image
126      (lambda (handle)
127        (mm-valid-and-fit-image-p 'bmp handle)))
128     ("text/plain" mm-inline-text identity)
129     ("text/enriched" mm-inline-text identity)
130     ("text/richtext" mm-inline-text identity)
131     ("text/x-patch" mm-display-patch-inline
132      (lambda (handle)
133        (locate-library "diff-mode")))
134     ("application/emacs-lisp" mm-display-elisp-inline identity)
135     ("text/html"
136      mm-inline-text
137      (lambda (handle)
138        (locate-library "w3")))
139     ("text/x-vcard"
140      mm-inline-text
141      (lambda (handle)
142        (or (featurep 'vcard)
143            (locate-library "vcard"))))
144     ("message/delivery-status" mm-inline-text identity)
145     ("message/rfc822" mm-inline-message identity)
146     ("message/partial" mm-inline-partial identity)
147     ("message/external-body" mm-inline-external-body identity)
148     ("text/.*" mm-inline-text identity)
149     ("audio/wav" mm-inline-audio
150      (lambda (handle)
151        (and (or (featurep 'nas-sound) (featurep 'native-sound))
152             (device-sound-enabled-p))))
153     ("audio/au"
154      mm-inline-audio
155      (lambda (handle)
156        (and (or (featurep 'nas-sound) (featurep 'native-sound))
157             (device-sound-enabled-p))))
158     ("application/pgp-signature" ignore identity)
159     ("application/x-pkcs7-signature" ignore identity)
160     ("application/pkcs7-signature" ignore identity)
161     ("multipart/alternative" ignore identity)
162     ("multipart/mixed" ignore identity)
163     ("multipart/related" ignore identity))
164   "Alist of media types/tests saying whether types can be displayed inline."
165   :type '(repeat (list (string :tag "MIME type")
166                        (function :tag "Display function")
167                        (function :tag "Display test")))
168   :group 'mime-display)
169
170 (defcustom mm-inlined-types
171   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
172     "message/partial" "message/external-body" "application/emacs-lisp"
173     "application/pgp-signature" "application/x-pkcs7-signature"
174     "application/pkcs7-signature")
175   "List of media types that are to be displayed inline."
176   :type '(repeat string)
177   :group 'mime-display)
178   
179 (defcustom mm-automatic-display
180   '("text/plain" "text/enriched" "text/richtext" "text/html"
181     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
182     "message/rfc822" "text/x-patch" "application/pgp-signature"
183     "application/emacs-lisp" "application/x-pkcs7-signature"
184     "application/pkcs7-signature")
185   "A list of MIME types to be displayed automatically."
186   :type '(repeat string)
187   :group 'mime-display)
188
189 (defcustom mm-attachment-override-types '("text/x-vcard")
190   "Types to have \"attachment\" ignored if they can be displayed inline."
191   :type '(repeat string)
192   :group 'mime-display)
193
194 (defcustom mm-inline-override-types nil
195   "Types to be treated as attachments even if they can be displayed inline."
196   :type '(repeat string)
197   :group 'mime-display)
198
199 (defcustom mm-automatic-external-display nil
200   "List of MIME type regexps that will be displayed externally automatically."
201   :type '(repeat string)
202   :group 'mime-display)
203
204 (defcustom mm-discouraged-alternatives nil
205   "List of MIME types that are discouraged when viewing multipart/alternative.
206 Viewing agents are supposed to view the last possible part of a message,
207 as that is supposed to be the richest.  However, users may prefer other
208 types instead, and this list says what types are most unwanted.  If,
209 for instance, text/html parts are very unwanted, and text/richtext are
210 somewhat unwanted, then the value of this variable should be set
211 to:
212
213  (\"text/html\" \"text/richtext\")"
214   :type '(repeat string)
215   :group 'mime-display)
216
217 (defvar mm-tmp-directory
218   (cond ((fboundp 'temp-directory) (temp-directory))
219         ((boundp 'temporary-file-directory) temporary-file-directory)
220         ("/tmp/"))
221   "Where mm will store its temporary files.")
222
223 (defcustom mm-inline-large-images nil
224   "If non-nil, then all images fit in the buffer."
225   :type 'boolean
226   :group 'mime-display)
227
228 ;;; Internal variables.
229
230 (defvar mm-dissection-list nil)
231 (defvar mm-last-shell-command "")
232 (defvar mm-content-id-alist nil)
233
234 ;; According to RFC2046, in particular, in a digest, the default
235 ;; Content-Type value for a body part is changed from "text/plain" to
236 ;; "message/rfc822".
237 (defvar mm-dissect-default-type "text/plain")
238
239 (autoload 'mml2015-verify "mml2015")
240 (autoload 'mml2015-verify-test "mml2015")
241 (autoload 'mml-smime-verify "mml-smime")
242 (autoload 'mml-smime-verify-test "mml-smime")
243
244 (defvar mm-verify-function-alist
245   '(("application/pgp-signature" mml2015-verify "PGP" mml2015-verify-test)
246     ("application/pkcs7-signature" mml-smime-verify "S/MIME" 
247      mml-smime-verify-test)
248     ("application/x-pkcs7-signature" mml-smime-verify "S/MIME" 
249      mml-smime-verify-test)))
250
251 (defcustom mm-verify-option nil
252   "Option of verifying signed parts.
253 `never', not verify; `always', always verify; 
254 `known', only verify known protocols. Otherwise, ask user."
255   :type '(choice (item always)
256                  (item never)
257                  (item :tag "only known protocols" known)
258                  (item :tag "ask" nil))
259   :group 'mime-security)
260
261 (autoload 'mml2015-decrypt "mml2015")
262 (autoload 'mml2015-decrypt-test "mml2015")
263
264 (defvar mm-decrypt-function-alist
265   '(("application/pgp-encrypted" mml2015-decrypt "PGP" mml2015-decrypt-test)))
266
267 (defcustom mm-decrypt-option nil
268   "Option of decrypting signed parts.
269 `never', not decrypt; `always', always decrypt; 
270 `known', only decrypt known protocols. Otherwise, ask user."
271   :type '(choice (item always)
272                  (item never)
273                  (item :tag "only known protocols" known)
274                  (item :tag "ask" nil))
275   :group 'mime-security)
276
277 (defvar mm-viewer-completion-map
278   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
279     (set-keymap-parent map minibuffer-local-completion-map)
280     map)
281   "Keymap for input viewer with completion.")
282
283 ;; Should we bind other key to minibuffer-complete-word?
284 (define-key mm-viewer-completion-map " " 'self-insert-command) 
285
286 ;;; The functions.
287
288 (defun mm-alist-to-plist (alist)
289   "Convert association list ALIST into the equivalent property-list form.
290 The plist is returned.  This converts from
291
292 \((a . 1) (b . 2) (c . 3))
293
294 into
295
296 \(a 1 b 2 c 3)
297
298 The original alist is not modified.  See also `destructive-alist-to-plist'."
299   (let (plist)
300     (while alist
301       (let ((el (car alist)))
302         (setq plist (cons (cdr el) (cons (car el) plist))))
303       (setq alist (cdr alist)))
304     (nreverse plist)))
305
306 (defun mm-dissect-buffer (&optional no-strict-mime)
307   "Dissect the current buffer and return a list of MIME handles."
308   (save-excursion
309     (let (ct ctl type subtype cte cd description id result)
310       (save-restriction
311         (mail-narrow-to-head)
312         (when (or no-strict-mime
313                   (mail-fetch-field "mime-version"))
314           (setq ct (mail-fetch-field "content-type")
315                 ctl (ignore-errors (mail-header-parse-content-type ct))
316                 cte (mail-fetch-field "content-transfer-encoding")
317                 cd (mail-fetch-field "content-disposition")
318                 description (mail-fetch-field "content-description")
319                 id (mail-fetch-field "content-id"))))
320       (when cte
321         (setq cte (mail-header-strip cte)))
322       (if (or (not ctl)
323               (not (string-match "/" (car ctl))))
324           (mm-dissect-singlepart
325            (list mm-dissect-default-type)
326            (and cte (intern (downcase (mail-header-remove-whitespace
327                                        (mail-header-remove-comments
328                                         cte)))))
329            no-strict-mime
330            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
331            description)
332         (setq type (split-string (car ctl) "/"))
333         (setq subtype (cadr type)
334               type (pop type))
335         (setq
336          result
337          (cond
338           ((equal type "multipart")
339            (let ((mm-dissect-default-type (if (equal subtype "digest")
340                                               "message/rfc822"
341                                             "text/plain")))
342              (add-text-properties 0 (length (car ctl))
343                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
344
345              ;; what really needs to be done here is a way to link a
346              ;; MIME handle back to it's parent MIME handle (in a multilevel
347              ;; MIME article).  That would probably require changing
348              ;; the mm-handle API so we simply store the multipart buffert
349              ;; name as a text property of the "multipart/whatever" string.
350              (add-text-properties 0 (length (car ctl))
351                                   (list 'buffer (mm-copy-to-buffer))
352                                   (car ctl))
353              (cons (car ctl) (mm-dissect-multipart ctl))))
354           (t
355            (mm-dissect-singlepart
356             ctl
357             (and cte (intern (downcase (mail-header-remove-whitespace
358                                         (mail-header-remove-comments
359                                          cte)))))
360             no-strict-mime
361             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
362             description id))))
363         (when id
364           (when (string-match " *<\\(.*\\)> *" id)
365             (setq id (match-string 1 id)))
366           (push (cons id result) mm-content-id-alist))
367         result))))
368
369 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
370   (when (or force
371             (if (equal "text/plain" (car ctl))
372                 (assoc 'format ctl)
373               t))
374     (let ((res (mm-make-handle
375                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
376       (push (car res) mm-dissection-list)
377       res)))
378
379 (defun mm-remove-all-parts ()
380   "Remove all MIME handles."
381   (interactive)
382   (mapcar 'mm-remove-part mm-dissection-list)
383   (setq mm-dissection-list nil))
384
385 (defun mm-dissect-multipart (ctl)
386   (goto-char (point-min))
387   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
388          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
389          start parts
390          (end (save-excursion
391                 (goto-char (point-max))
392                 (if (re-search-backward close-delimiter nil t)
393                     (match-beginning 0)
394                   (point-max)))))
395     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
396     (while (re-search-forward boundary end t)
397       (goto-char (match-beginning 0))
398       (when start
399         (save-excursion
400           (save-restriction
401             (narrow-to-region start (point))
402             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
403       (forward-line 2)
404       (setq start (point)))
405     (when start
406       (save-excursion
407         (save-restriction
408           (narrow-to-region start end)
409           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
410     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
411
412 (defun mm-copy-to-buffer ()
413   "Copy the contents of the current buffer to a fresh buffer."
414   (save-excursion
415     (let ((obuf (current-buffer))
416           beg)
417       (goto-char (point-min))
418       (search-forward-regexp "^\n" nil t)
419       (setq beg (point))
420       (set-buffer (generate-new-buffer " *mm*"))
421       (insert-buffer-substring obuf beg)
422       (current-buffer))))
423
424 (defun mm-display-parts (handle &optional no-default)
425   (if (stringp (car handle))
426       (mapcar 'mm-display-parts (cdr handle))
427     (if (bufferp (car handle))
428         (save-restriction
429           (narrow-to-region (point) (point))
430           (mm-display-part handle)
431           (goto-char (point-max)))
432       (mapcar 'mm-display-parts handle))))
433
434 (defun mm-display-part (handle &optional no-default)
435   "Display the MIME part represented by HANDLE.
436 Returns nil if the part is removed; inline if displayed inline;
437 external if displayed external."
438   (save-excursion
439     (mailcap-parse-mailcaps)
440     (if (mm-handle-displayed-p handle)
441         (mm-remove-part handle)
442       (let* ((type (mm-handle-media-type handle))
443              (method (mailcap-mime-info type)))
444         (if (mm-inlined-p handle)
445             (progn
446               (forward-line 1)
447               (mm-display-inline handle)
448               'inline)
449           (when (or method
450                     (not no-default))
451             (if (and (not method)
452                      (equal "text" (car (split-string type))))
453                 (progn
454                   (forward-line 1)
455                   (mm-insert-inline handle (mm-get-part handle))
456                   'inline)
457               (mm-display-external
458                handle (or method 'mailcap-save-binary-file)))))))))
459
460 (defun mm-display-external (handle method)
461   "Display HANDLE using METHOD."
462   (let ((outbuf (current-buffer)))
463     (mm-with-unibyte-buffer
464       (if (functionp method)
465           (let ((cur (current-buffer)))
466             (if (eq method 'mailcap-save-binary-file)
467                 (progn
468                   (set-buffer (generate-new-buffer " *mm*"))
469                   (setq method nil))
470               (mm-insert-part handle)
471               (let ((win (get-buffer-window cur t)))
472                 (when win
473                   (select-window win)))
474               (switch-to-buffer (generate-new-buffer " *mm*")))
475             (buffer-disable-undo)
476             (mm-set-buffer-file-coding-system mm-binary-coding-system)
477             (insert-buffer-substring cur)
478             (goto-char (point-min))
479             (message "Viewing with %s" method)
480             (let ((mm (current-buffer))
481                   (non-viewer (assq 'non-viewer
482                                     (mailcap-mime-info
483                                      (mm-handle-media-type handle) t))))
484               (unwind-protect
485                   (if method
486                       (funcall method)
487                     (mm-save-part handle))
488                 (when (and (not non-viewer)
489                            method)
490                   (mm-handle-set-undisplayer handle mm)))))
491         ;; The function is a string to be executed.
492         (mm-insert-part handle)
493         (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
494                (filename (mail-content-type-get
495                           (mm-handle-disposition handle) 'filename))
496                (mime-info (mailcap-mime-info
497                            (mm-handle-media-type handle) t))
498                (needsterm (or (assoc "needsterm" mime-info)
499                               (assoc "needsterminal" mime-info)))
500                (copiousoutput (assoc "copiousoutput" mime-info))
501                file buffer)
502           ;; We create a private sub-directory where we store our files.
503           (make-directory dir)
504           (set-file-modes dir 448)
505           (if filename
506               (setq file (expand-file-name (file-name-nondirectory filename)
507                                            dir))
508             (setq file (make-temp-name (expand-file-name "mm." dir))))
509           (let ((coding-system-for-write mm-binary-coding-system))
510             (write-region (point-min) (point-max) file nil 'nomesg))
511           (message "Viewing with %s" method)
512           (cond (needsterm
513                  (unwind-protect
514                      (start-process "*display*" nil
515                                     "xterm"
516                                     "-e" shell-file-name
517                                     shell-command-switch
518                                     (mm-mailcap-command
519                                      method file (mm-handle-type handle)))
520                    (mm-handle-set-undisplayer handle (cons file buffer)))
521                  (message "Displaying %s..." (format method file))
522                  'external)
523                 (copiousoutput
524                  (with-current-buffer outbuf
525                    (forward-line 1)
526                    (mm-insert-inline
527                     handle
528                     (unwind-protect
529                         (progn
530                           (call-process shell-file-name nil
531                                         (setq buffer
532                                               (generate-new-buffer " *mm*"))
533                                         nil
534                                         shell-command-switch
535                                         (mm-mailcap-command
536                                          method file (mm-handle-type handle)))
537                           (if (buffer-live-p buffer)
538                               (save-excursion
539                                 (set-buffer buffer)
540                                 (buffer-string))))
541                       (progn
542                         (ignore-errors (delete-file file))
543                         (ignore-errors (delete-directory
544                                         (file-name-directory file)))
545                         (ignore-errors (kill-buffer buffer))))))
546                  'inline)
547                 (t
548                  (unwind-protect
549                      (start-process "*display*"
550                                     (setq buffer
551                                           (generate-new-buffer " *mm*"))
552                                     shell-file-name
553                                     shell-command-switch
554                                     (mm-mailcap-command
555                                      method file (mm-handle-type handle)))
556                    (mm-handle-set-undisplayer handle (cons file buffer)))
557                  (message "Displaying %s..." (format method file))
558                  'external)))))))
559   
560 (defun mm-mailcap-command (method file type-list)
561   (let ((ctl (cdr type-list))
562         (beg 0)
563         (uses-stdin t)
564         out sub total)
565     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
566       (push (substring method beg (match-beginning 0)) out)
567       (setq beg (match-end 0)
568             total (match-string 0 method)
569             sub (match-string 1 method))
570       (cond
571        ((string= total "%%")
572         (push "%" out))
573        ((string= total "%s")
574         (setq uses-stdin nil)
575         (push (mm-quote-arg file) out))
576        ((string= total "%t")
577         (push (mm-quote-arg (car type-list)) out))
578        (t
579         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
580     (push (substring method beg (length method)) out)
581     (if uses-stdin
582         (progn
583           (push "<" out)
584           (push (mm-quote-arg file) out)))
585     (mapconcat 'identity (nreverse out) "")))
586
587 (defun mm-remove-parts (handles)
588   "Remove the displayed MIME parts represented by HANDLES."
589   (if (and (listp handles)
590            (bufferp (car handles)))
591       (mm-remove-part handles)
592     (let (handle)
593       (while (setq handle (pop handles))
594         (cond
595          ((stringp handle)
596           (when (buffer-live-p (get-text-property 0 'buffer handle))
597             (kill-buffer (get-text-property 0 'buffer handle))))
598          ((and (listp handle)
599                (stringp (car handle)))
600           (mm-remove-parts (cdr handle)))
601          (t
602           (mm-remove-part handle)))))))
603
604 (defun mm-destroy-parts (handles)
605   "Remove the displayed MIME parts represented by HANDLES."
606   (if (and (listp handles)
607            (bufferp (car handles)))
608       (mm-destroy-part handles)
609     (let (handle)
610       (while (setq handle (pop handles))
611         (cond
612          ((stringp handle)
613           (when (buffer-live-p (get-text-property 0 'buffer handle))
614             (kill-buffer (get-text-property 0 'buffer handle))))
615          ((and (listp handle)
616                (stringp (car handle)))
617           (mm-destroy-parts (cdr handle)))
618          (t
619           (mm-destroy-part handle)))))))
620
621 (defun mm-remove-part (handle)
622   "Remove the displayed MIME part represented by HANDLE."
623   (when (listp handle)
624     (let ((object (mm-handle-undisplayer handle)))
625       (ignore-errors
626         (cond
627          ;; Internally displayed part.
628          ((mm-annotationp object)
629           (delete-annotation object))
630          ((or (functionp object)
631               (and (listp object)
632                    (eq (car object) 'lambda)))
633           (funcall object))
634          ;; Externally displayed part.
635          ((consp object)
636           (ignore-errors (delete-file (car object)))
637           (ignore-errors (delete-directory (file-name-directory (car object))))
638           (ignore-errors (kill-buffer (cdr object))))
639          ((bufferp object)
640           (when (buffer-live-p object)
641             (kill-buffer object)))))
642       (mm-handle-set-undisplayer handle nil))))
643
644 (defun mm-display-inline (handle)
645   (let* ((type (mm-handle-media-type handle))
646          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
647     (funcall function handle)
648     (goto-char (point-min))))
649
650 (defun mm-assoc-string-match (alist type)
651   (dolist (elem alist)
652     (when (string-match (car elem) type)
653       (return elem))))
654
655 (defun mm-inlinable-p (handle)
656   "Say whether HANDLE can be displayed inline."
657   (let ((alist mm-inline-media-tests)
658         (type (mm-handle-media-type handle))
659         test)
660     (while alist
661       (when (string-match (caar alist) type)
662         (setq test (caddar alist)
663               alist nil)
664         (setq test (funcall test handle)))
665       (pop alist))
666     test))
667
668 (defun mm-automatic-display-p (handle)
669   "Say whether the user wants HANDLE to be displayed automatically."
670   (let ((methods mm-automatic-display)
671         (type (mm-handle-media-type handle))
672         method result)
673     (while (setq method (pop methods))
674       (when (and (not (mm-inline-override-p handle))
675                  (string-match method type)
676                  (mm-inlinable-p handle))
677         (setq result t
678               methods nil)))
679     result))
680
681 (defun mm-inlined-p (handle)
682   "Say whether the user wants HANDLE to be displayed automatically."
683   (let ((methods mm-inlined-types)
684         (type (mm-handle-media-type handle))
685         method result)
686     (while (setq method (pop methods))
687       (when (and (not (mm-inline-override-p handle))
688                  (string-match method type)
689                  (mm-inlinable-p handle))
690         (setq result t
691               methods nil)))
692     result))
693
694 (defun mm-attachment-override-p (handle)
695   "Say whether HANDLE should have attachment behavior overridden."
696   (let ((types mm-attachment-override-types)
697         (type (mm-handle-media-type handle))
698         ty)
699     (catch 'found
700       (while (setq ty (pop types))
701         (when (and (string-match ty type)
702                    (mm-inlinable-p handle))
703           (throw 'found t))))))
704
705 (defun mm-inline-override-p (handle)
706   "Say whether HANDLE should have inline behavior overridden."
707   (let ((types mm-inline-override-types)
708         (type (mm-handle-media-type handle))
709         ty)
710     (catch 'found
711       (while (setq ty (pop types))
712         (when (string-match ty type)
713           (throw 'found t))))))
714
715 (defun mm-automatic-external-display-p (type)
716   "Return the user-defined method for TYPE."
717   (let ((methods mm-automatic-external-display)
718         method result)
719     (while (setq method (pop methods))
720       (when (string-match method type)
721         (setq result t
722               methods nil)))
723     result))
724
725 (defun mm-destroy-part (handle)
726   "Destroy the data structures connected to HANDLE."
727   (when (listp handle)
728     (mm-remove-part handle)
729     (when (buffer-live-p (mm-handle-buffer handle))
730       (kill-buffer (mm-handle-buffer handle)))))
731
732 (defun mm-handle-displayed-p (handle)
733   "Say whether HANDLE is displayed or not."
734   (mm-handle-undisplayer handle))
735
736 ;;;
737 ;;; Functions for outputting parts
738 ;;;
739
740 (defun mm-get-part (handle)
741   "Return the contents of HANDLE as a string."
742   (mm-with-unibyte-buffer
743     (mm-insert-part handle)
744     (buffer-string)))
745
746 (defun mm-insert-part (handle)
747   "Insert the contents of HANDLE in the current buffer."
748   (let ((cur (current-buffer)))
749     (save-excursion
750       (if (member (mm-handle-media-supertype handle) '("text" "message"))
751           (with-temp-buffer
752             (insert-buffer-substring (mm-handle-buffer handle))
753             (mm-decode-content-transfer-encoding
754              (mm-handle-encoding handle)
755              (mm-handle-media-type handle))
756             (let ((temp (current-buffer)))
757               (set-buffer cur)
758               (insert-buffer-substring temp)))
759         (mm-with-unibyte-buffer
760           (insert-buffer-substring (mm-handle-buffer handle))
761           (mm-decode-content-transfer-encoding
762            (mm-handle-encoding handle)
763            (mm-handle-media-type handle))
764           (let ((temp (current-buffer)))
765             (set-buffer cur)
766             (insert-buffer-substring temp)))))))
767
768 (defvar mm-default-directory nil)
769
770 (defun mm-save-part (handle)
771   "Write HANDLE to a file."
772   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
773          (filename (mail-content-type-get
774                     (mm-handle-disposition handle) 'filename))
775          file)
776     (when filename
777       (setq filename (file-name-nondirectory filename)))
778     (setq file
779           (read-file-name "Save MIME part to: "
780                           (expand-file-name
781                            (or filename name "")
782                            (or mm-default-directory default-directory))))
783     (setq mm-default-directory (file-name-directory file))
784     (and (or (not (file-exists-p file))
785              (yes-or-no-p (format "File %s already exists; overwrite? "
786                                   file)))
787          (progn
788            (mm-save-part-to-file handle file)
789            file))))
790
791 (defun mm-save-part-to-file (handle file)
792   (mm-with-unibyte-buffer
793     (mm-insert-part handle)
794     (let ((coding-system-for-write 'binary)
795           ;; Don't re-compress .gz & al.  Arguably we should make
796           ;; `file-name-handler-alist' nil, but that would chop
797           ;; ange-ftp, which is reasonable to use here.
798           (inhibit-file-name-operation 'write-region)
799           (inhibit-file-name-handlers
800            (cons 'jka-compr-handler inhibit-file-name-handlers)))
801       (write-region (point-min) (point-max) file))))
802
803 (defun mm-pipe-part (handle)
804   "Pipe HANDLE to a process."
805   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
806          (command
807           (read-string "Shell command on MIME part: " mm-last-shell-command)))
808     (mm-with-unibyte-buffer
809       (mm-insert-part handle)
810       (shell-command-on-region (point-min) (point-max) command nil))))
811
812 (defun mm-interactively-view-part (handle)
813   "Display HANDLE using METHOD."
814   (let* ((type (mm-handle-media-type handle))
815          (methods
816           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
817                   (mailcap-mime-info type 'all)))
818          (method (let ((minibuffer-local-completion-map
819                         mm-viewer-completion-map))
820                    (completing-read "Viewer: " methods))))
821     (when (string= method "")
822       (error "No method given"))
823     (if (string-match "^[^% \t]+$" method) 
824         (setq method (concat method " %s")))
825     (mm-display-external (copy-sequence handle) method)))
826
827 (defun mm-preferred-alternative (handles &optional preferred)
828   "Say which of HANDLES are preferred."
829   (let ((prec (if preferred (list preferred)
830                 (mm-preferred-alternative-precedence handles)))
831         p h result type handle)
832     (while (setq p (pop prec))
833       (setq h handles)
834       (while h
835         (setq handle (car h))
836         (setq type (mm-handle-media-type handle))
837         (when (and (equal p type)
838                    (mm-automatic-display-p handle)
839                    (or (stringp (car handle))
840                        (not (mm-handle-disposition handle))
841                        (equal (car (mm-handle-disposition handle))
842                               "inline")))
843           (setq result handle
844                 h nil
845                 prec nil))
846         (pop h)))
847     result))
848
849 (defun mm-preferred-alternative-precedence (handles)
850   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
851   (let ((seq (nreverse (mapcar #'mm-handle-media-type
852                                handles))))
853     (dolist (disc (reverse mm-discouraged-alternatives))
854       (dolist (elem (copy-sequence seq))
855         (when (string-match disc elem)
856           (setq seq (nconc (delete elem seq) (list elem))))))
857     seq))
858
859 (defun mm-get-content-id (id)
860   "Return the handle(s) referred to by ID."
861   (cdr (assoc id mm-content-id-alist)))
862
863 (defun mm-get-image (handle)
864   "Return an image instance based on HANDLE."
865   (let ((type (mm-handle-media-subtype handle))
866         spec)
867     ;; Allow some common translations.
868     (setq type
869           (cond
870            ((equal type "x-pixmap")
871             "xpm")
872            ((equal type "x-xbitmap")
873             "xbm")
874            (t type)))
875     (or (mm-handle-cache handle)
876         (mm-with-unibyte-buffer
877           (mm-insert-part handle)
878           (prog1
879               (setq spec
880                     (ignore-errors
881                      ;; Avoid testing `make-glyph' since W3 may define
882                      ;; a bogus version of it.
883                       (if (fboundp 'create-image)
884                           (create-image (buffer-string) (intern type) 'data-p)
885                         (cond
886                          ((equal type "xbm")
887                           ;; xbm images require special handling, since
888                           ;; the only way to create glyphs from these
889                           ;; (without a ton of work) is to write them
890                           ;; out to a file, and then create a file
891                           ;; specifier.
892                           (let ((file (make-temp-name
893                                        (expand-file-name "emm.xbm"
894                                                          mm-tmp-directory))))
895                             (unwind-protect
896                                 (progn
897                                   (write-region (point-min) (point-max) file)
898                                   (make-glyph (list (cons 'x file))))
899                               (ignore-errors
900                                (delete-file file)))))
901                          (t
902                           (make-glyph
903                            (vector (intern type) :data (buffer-string))))))))
904             (mm-handle-set-cache handle spec))))))
905
906 (defun mm-image-fit-p (handle)
907   "Say whether the image in HANDLE will fit the current window."
908   (let ((image (mm-get-image handle)))
909     (if (fboundp 'glyph-width)
910         ;; XEmacs' glyphs can actually tell us about their width, so
911         ;; lets be nice and smart about them.
912         (or mm-inline-large-images
913             (and (< (glyph-width image) (window-pixel-width))
914                  (< (glyph-height image) (window-pixel-height))))
915       (let* ((size (image-size image))
916              (w (car size))
917              (h (cdr size)))
918         (or mm-inline-large-images
919             (and (< h (1- (window-height))) ; Don't include mode line.
920                  (< w (window-width))))))))
921
922 (defun mm-valid-image-format-p (format)
923   "Say whether FORMAT can be displayed natively by Emacs."
924   (cond
925    ;; Handle XEmacs
926    ((fboundp 'valid-image-instantiator-format-p)
927     (valid-image-instantiator-format-p format))
928    ;; Handle Emacs 21
929    ((fboundp 'image-type-available-p)
930     (and (display-graphic-p)
931          (image-type-available-p format)))
932    ;; Nobody else can do images yet.
933    (t
934     nil)))
935
936 (defun mm-valid-and-fit-image-p (format handle)
937   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
938   (and (mm-valid-image-format-p format)
939        (mm-image-fit-p handle)))
940
941 (defun mm-find-part-by-type (handles type &optional notp recursive) 
942   "Search in HANDLES for part with TYPE.
943 If NOTP, returns first non-matching part.
944 If RECURSIVE, search recursively."
945   (let (handle)
946     (while handles
947       (if (and recursive (stringp (caar handles)))
948           (if (setq handle (mm-find-part-by-type (cdar handles) type
949                                                  notp recursive))
950               (setq handles nil))
951         (if (if notp
952                 (not (equal (mm-handle-media-type (car handles)) type))
953               (equal (mm-handle-media-type (car handles)) type))
954             (setq handle (car handles)
955                   handles nil)))
956       (setq handles (cdr handles)))
957     handle))
958
959 (defun mm-find-raw-part-by-type (ctl type &optional notp) 
960   (goto-char (point-min))
961   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
962          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
963          start
964          (end (save-excursion
965                 (goto-char (point-max))
966                 (if (re-search-backward close-delimiter nil t)
967                     (match-beginning 0)
968                   (point-max))))
969          result)
970     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
971     (while (and (not result)
972                 (re-search-forward boundary end t))
973       (goto-char (match-beginning 0))
974       (when start
975         (save-excursion
976           (save-restriction
977             (narrow-to-region start (point))
978             (when (let ((ctl (ignore-errors 
979                                (mail-header-parse-content-type 
980                                 (mail-fetch-field "content-type")))))
981                     (if notp
982                         (not (equal (car ctl) type))
983                       (equal (car ctl) type)))
984               (setq result (buffer-substring (point-min) (point-max)))))))
985       (forward-line 2)
986       (setq start (point)))
987     (when (and (not result) start)
988       (save-excursion
989         (save-restriction
990           (narrow-to-region start end)
991           (when (let ((ctl (ignore-errors 
992                              (mail-header-parse-content-type 
993                               (mail-fetch-field "content-type")))))
994                   (if notp
995                       (not (equal (car ctl) type))
996                     (equal (car ctl) type)))
997             (setq result (buffer-substring (point-min) (point-max)))))))
998     result))
999
1000 (defvar mm-security-handle nil)
1001
1002 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1003   ;; HANDLE could be a CTL.
1004   (if handle
1005       (put-text-property 0 (length (car handle)) parameter value 
1006                          (car handle))))
1007
1008 (defun mm-possibly-verify-or-decrypt (parts ctl)
1009   (let ((subtype (cadr (split-string (car ctl) "/")))
1010         (mm-security-handle ctl) ;; (car CTL) is the type.
1011         protocol func functest)
1012     (cond 
1013      ((equal subtype "signed")
1014       (unless (and (setq protocol (mail-content-type-get ctl 'protocol))
1015                    (not (equal protocol "multipart/mixed")))
1016         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1017         (let ((protocols mm-verify-function-alist))
1018           (while protocols
1019             (if (and (or (not (setq functest (nth 3 (car protocols))))
1020                          (funcall functest parts ctl))
1021                      (mm-find-part-by-type parts (caar protocols) nil t))
1022                 (setq protocol (caar protocols)
1023                       protocols nil)
1024               (setq protocols (cdr protocols))))))
1025       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1026       (if (cond
1027            ((eq mm-verify-option 'never) nil)
1028            ((eq mm-verify-option 'always) t)
1029            ((eq mm-verify-option 'known) 
1030             (and func 
1031                  (or (not (setq functest 
1032                                 (nth 3 (assoc protocol 
1033                                               mm-verify-function-alist))))
1034                      (funcall functest parts ctl))))
1035            (t (y-or-n-p
1036                (format "Verify signed (%s) part? "
1037                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1038                            (format "protocol=%s" protocol))))))
1039           (save-excursion
1040             (if func
1041                 (funcall func parts ctl)
1042               (mm-set-handle-multipart-parameter 
1043                mm-security-handle 'gnus-details 
1044                (format "Unknown sign protocol (%s)" protocol))))))
1045      ((equal subtype "encrypted")
1046       (unless (setq protocol (mail-content-type-get ctl 'protocol))
1047         ;; The message is broken.
1048         (let ((parts parts))
1049           (while parts
1050             (if (assoc (mm-handle-media-type (car parts)) 
1051                        mm-decrypt-function-alist)
1052                 (setq protocol (mm-handle-media-type (car parts))
1053                       parts nil)
1054               (setq parts (cdr parts))))))
1055       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1056       (if (cond
1057            ((eq mm-decrypt-option 'never) nil)
1058            ((eq mm-decrypt-option 'always) t)
1059            ((eq mm-decrypt-option 'known)
1060             (and func 
1061                  (or (not (setq functest 
1062                                 (nth 3 (assoc protocol 
1063                                               mm-decrypt-function-alist))))
1064                      (funcall functest parts ctl))))
1065            (t (y-or-n-p 
1066                (format "Decrypt (%s) part? "
1067                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1068                            (format "protocol=%s" protocol))))))
1069           (save-excursion
1070             (if func
1071                 (setq parts (funcall func parts ctl))
1072               (mm-set-handle-multipart-parameter 
1073                mm-security-handle 'gnus-details 
1074                (format "Unknown encrypt protocol (%s)" protocol))))))
1075      (t nil))
1076     parts))
1077
1078 (provide 'mm-decode)
1079
1080 ;;; mm-decode.el ends here