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