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