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