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