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