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