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