7975fae21e284e6c59e40803c2364a5223a4a1d4
[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-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 ((flag enable-multibyte-characters)
544           (new-buffer (generate-new-buffer " *mm*")))
545       (goto-char (point-min))
546       (search-forward-regexp "^\n" nil t)
547       (save-restriction
548         (narrow-to-region (point) (point-max))
549         (when flag
550           (set-buffer-multibyte nil))
551         (copy-to-buffer new-buffer (point-min) (point-max))
552         (when flag
553           (set-buffer-multibyte t)))
554       new-buffer)))
555
556 (defun mm-display-parts (handle &optional no-default)
557   (if (stringp (car handle))
558       (mapcar 'mm-display-parts (cdr handle))
559     (if (bufferp (car handle))
560         (save-restriction
561           (narrow-to-region (point) (point))
562           (mm-display-part handle)
563           (goto-char (point-max)))
564       (mapcar 'mm-display-parts handle))))
565
566 (defun mm-display-part (handle &optional no-default)
567   "Display the MIME part represented by HANDLE.
568 Returns nil if the part is removed; inline if displayed inline;
569 external if displayed external."
570   (save-excursion
571     (mailcap-parse-mailcaps)
572     (if (mm-handle-displayed-p handle)
573         (mm-remove-part handle)
574       (let* ((type (mm-handle-media-type handle))
575              (method (mailcap-mime-info type)))
576         (if (and (mm-inlinable-p handle)
577                  (mm-inlined-p handle))
578             (progn
579               (forward-line 1)
580               (mm-display-inline handle)
581               'inline)
582           (when (or method
583                     (not no-default))
584             (if (and (not method)
585                      (equal "text" (car (split-string type))))
586                 (progn
587                   (forward-line 1)
588                   (mm-insert-inline handle (mm-get-part handle))
589                   'inline)
590               (mm-display-external
591                handle (or method 'mailcap-save-binary-file)))))))))
592
593 (defun mm-display-external (handle method)
594   "Display HANDLE using METHOD."
595   (let ((outbuf (current-buffer)))
596     (mm-with-unibyte-buffer
597       (if (functionp method)
598           (let ((cur (current-buffer)))
599             (if (eq method 'mailcap-save-binary-file)
600                 (progn
601                   (set-buffer (generate-new-buffer " *mm*"))
602                   (setq method nil))
603               (mm-insert-part handle)
604               (let ((win (get-buffer-window cur t)))
605                 (when win
606                   (select-window win)))
607               (switch-to-buffer (generate-new-buffer " *mm*")))
608             (buffer-disable-undo)
609             (mm-set-buffer-file-coding-system mm-binary-coding-system)
610             (insert-buffer-substring cur)
611             (goto-char (point-min))
612             (message "Viewing with %s" method)
613             (let ((mm (current-buffer))
614                   (non-viewer (assq 'non-viewer
615                                     (mailcap-mime-info
616                                      (mm-handle-media-type handle) t))))
617               (unwind-protect
618                   (if method
619                       (funcall method)
620                     (mm-save-part handle))
621                 (when (and (not non-viewer)
622                            method)
623                   (mm-handle-set-undisplayer handle mm)))))
624         ;; The function is a string to be executed.
625         (mm-insert-part handle)
626         (let* ((dir (make-temp-name
627                      (expand-file-name "emm." mm-tmp-directory)))
628                (filename (mail-content-type-get
629                           (mm-handle-disposition handle) 'filename))
630                (mime-info (mailcap-mime-info
631                            (mm-handle-media-type handle) t))
632                (needsterm (or (assoc "needsterm" mime-info)
633                               (assoc "needsterminal" mime-info)))
634                (copiousoutput (assoc "copiousoutput" mime-info))
635                file buffer)
636           ;; We create a private sub-directory where we store our files.
637           (make-directory dir)
638           (set-file-modes dir 448)
639           (if filename
640               (setq file (expand-file-name (file-name-nondirectory filename)
641                                            dir))
642             (setq file (make-temp-name (expand-file-name "mm." dir))))
643           (let ((coding-system-for-write mm-binary-coding-system))
644             (write-region (point-min) (point-max) file nil 'nomesg))
645           (message "Viewing with %s" method)
646           (cond
647            (needsterm
648             (unwind-protect
649                 (if window-system
650                     (start-process "*display*" nil
651                                    mm-external-terminal-program
652                                    "-e" shell-file-name
653                                    shell-command-switch
654                                    (mm-mailcap-command
655                                     method file (mm-handle-type handle)))
656                   (require 'term)
657                   (require 'gnus-win)
658                   (set-buffer
659                    (setq buffer
660                          (make-term "display"
661                                     shell-file-name
662                                     nil
663                                     shell-command-switch
664                                     (mm-mailcap-command
665                                      method file
666                                      (mm-handle-type handle)))))
667                   (term-mode)
668                   (term-char-mode)
669                   (set-process-sentinel
670                    (get-buffer-process buffer)
671                    `(lambda (process state)
672                       (if (eq 'exit (process-status process))
673                           (gnus-configure-windows
674                            ',gnus-current-window-configuration))))
675                   (gnus-configure-windows 'display-term))
676               (mm-handle-set-external-undisplayer handle (cons file buffer)))
677             (message "Displaying %s..." (format method file))
678             'external)
679            (copiousoutput
680             (with-current-buffer outbuf
681               (forward-line 1)
682               (mm-insert-inline
683                handle
684                (unwind-protect
685                    (progn
686                      (call-process shell-file-name nil
687                                    (setq buffer
688                                          (generate-new-buffer " *mm*"))
689                                    nil
690                                    shell-command-switch
691                                    (mm-mailcap-command
692                                     method file (mm-handle-type handle)))
693                      (if (buffer-live-p buffer)
694                          (save-excursion
695                            (set-buffer buffer)
696                            (buffer-string))))
697                  (progn
698                    (ignore-errors (delete-file file))
699                    (ignore-errors (delete-directory
700                                    (file-name-directory file)))
701                    (ignore-errors (kill-buffer buffer))))))
702             'inline)
703            (t
704             (unwind-protect
705                 (start-process "*display*"
706                                (setq buffer
707                                      (generate-new-buffer " *mm*"))
708                                shell-file-name
709                                shell-command-switch
710                                (mm-mailcap-command
711                                 method file (mm-handle-type handle)))
712               (mm-handle-set-external-undisplayer
713                handle (cons file buffer)))
714             (message "Displaying %s..." (format method file))
715             'external)))))))
716
717 (defun mm-mailcap-command (method file type-list)
718   (let ((ctl (cdr type-list))
719         (beg 0)
720         (uses-stdin t)
721         out sub total)
722     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
723       (push (substring method beg (match-beginning 0)) out)
724       (setq beg (match-end 0)
725             total (match-string 0 method)
726             sub (match-string 1 method))
727       (cond
728        ((string= total "%%")
729         (push "%" out))
730        ((string= total "%s")
731         (setq uses-stdin nil)
732         (push (mm-quote-arg
733                (gnus-map-function mm-path-name-rewrite-functions file)) out))
734        ((string= total "%t")
735         (push (mm-quote-arg (car type-list)) out))
736        (t
737         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
738     (push (substring method beg (length method)) out)
739     (when uses-stdin
740       (push "<" out)
741       (push (mm-quote-arg
742              (gnus-map-function mm-path-name-rewrite-functions file))
743             out))
744     (mapconcat 'identity (nreverse out) "")))
745
746 (defun mm-remove-parts (handles)
747   "Remove the displayed MIME parts represented by HANDLES."
748   (if (and (listp handles)
749            (bufferp (car handles)))
750       (mm-remove-part handles)
751     (let (handle)
752       (while (setq handle (pop handles))
753         (cond
754          ((stringp handle)
755           (when (buffer-live-p (get-text-property 0 'buffer handle))
756             (kill-buffer (get-text-property 0 'buffer handle))))
757          ((and (listp handle)
758                (stringp (car handle)))
759           (mm-remove-parts (cdr handle)))
760          (t
761           (mm-remove-part handle)))))))
762
763 (defun mm-destroy-parts (handles)
764   "Remove the displayed MIME parts represented by HANDLES."
765   (if (and (listp handles)
766            (bufferp (car handles)))
767       (mm-destroy-part handles)
768     (let (handle)
769       (while (setq handle (pop handles))
770         (cond
771          ((stringp handle)
772           (when (buffer-live-p (get-text-property 0 'buffer handle))
773             (kill-buffer (get-text-property 0 'buffer handle))))
774          ((and (listp handle)
775                (stringp (car handle)))
776           (mm-destroy-parts handle))
777          (t
778           (mm-destroy-part handle)))))))
779
780 (defun mm-remove-part (handle)
781   "Remove the displayed MIME part represented by HANDLE."
782   (when (listp handle)
783     (let ((object (mm-handle-undisplayer handle)))
784       (ignore-errors
785         (cond
786          ;; Internally displayed part.
787          ((mm-annotationp object)
788           (delete-annotation object))
789          ((or (functionp object)
790               (and (listp object)
791                    (eq (car object) 'lambda)))
792           (funcall object))
793          ;; Externally displayed part.
794          ((consp object)
795           (ignore-errors (delete-file (car object)))
796           (ignore-errors (delete-directory (file-name-directory (car object))))
797           (ignore-errors (and (cdr object) (kill-buffer (cdr object)))))
798          ((bufferp object)
799           (when (buffer-live-p object)
800             (kill-buffer object)))))
801       (mm-handle-set-undisplayer handle nil))))
802
803 (defun mm-display-inline (handle)
804   (let* ((type (mm-handle-media-type handle))
805          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
806     (funcall function handle)
807     (goto-char (point-min))))
808
809 (defun mm-assoc-string-match (alist type)
810   (dolist (elem alist)
811     (when (string-match (car elem) type)
812       (return elem))))
813
814 (defun mm-automatic-display-p (handle)
815   "Say whether the user wants HANDLE to be displayed automatically."
816   (let ((methods mm-automatic-display)
817         (type (mm-handle-media-type handle))
818         method result)
819     (while (setq method (pop methods))
820       (when (and (not (mm-inline-override-p handle))
821                  (string-match method type))
822         (setq result t
823               methods nil)))
824     result))
825
826 (defun mm-inlinable-p (handle)
827   "Say whether HANDLE can be displayed inline."
828   (let ((alist mm-inline-media-tests)
829         (type (mm-handle-media-type handle))
830         test)
831     (while alist
832       (when (string-match (caar alist) type)
833         (setq test (caddar alist)
834               alist nil)
835         (setq test (funcall test handle)))
836       (pop alist))
837     test))
838
839 (defun mm-inlined-p (handle)
840   "Say whether the user wants HANDLE to be displayed inline."
841   (let ((methods mm-inlined-types)
842         (type (mm-handle-media-type handle))
843         method result)
844     (while (setq method (pop methods))
845       (when (and (not (mm-inline-override-p handle))
846                  (string-match method type))
847         (setq result t
848               methods nil)))
849     result))
850
851 (defun mm-attachment-override-p (handle)
852   "Say whether HANDLE should have attachment behavior overridden."
853   (let ((types mm-attachment-override-types)
854         (type (mm-handle-media-type handle))
855         ty)
856     (catch 'found
857       (while (setq ty (pop types))
858         (when (and (string-match ty type)
859                    (mm-inlinable-p handle))
860           (throw 'found t))))))
861
862 (defun mm-inline-override-p (handle)
863   "Say whether HANDLE should have inline behavior overridden."
864   (let ((types mm-inline-override-types)
865         (type (mm-handle-media-type handle))
866         ty)
867     (catch 'found
868       (while (setq ty (pop types))
869         (when (string-match ty type)
870           (throw 'found t))))))
871
872 (defun mm-automatic-external-display-p (type)
873   "Return the user-defined method for TYPE."
874   (let ((methods mm-automatic-external-display)
875         method result)
876     (while (setq method (pop methods))
877       (when (string-match method type)
878         (setq result t
879               methods nil)))
880     result))
881
882 (defun mm-destroy-part (handle)
883   "Destroy the data structures connected to HANDLE."
884   (when (listp handle)
885     (mm-remove-part handle)
886     (when (buffer-live-p (mm-handle-buffer handle))
887       (kill-buffer (mm-handle-buffer handle)))))
888
889 (defun mm-handle-displayed-p (handle)
890   "Say whether HANDLE is displayed or not."
891   (mm-handle-undisplayer handle))
892
893 ;;;
894 ;;; Functions for outputting parts
895 ;;;
896
897 (defun mm-get-part (handle)
898   "Return the contents of HANDLE as a string."
899   (mm-with-unibyte-buffer
900     (insert (with-current-buffer (mm-handle-buffer handle)
901               (mm-with-unibyte-current-buffer-mule4
902                 (buffer-string))))
903     (mm-decode-content-transfer-encoding
904      (mm-handle-encoding handle)
905      (mm-handle-media-type handle))
906     (buffer-string)))
907
908 (defun mm-insert-part (handle)
909   "Insert the contents of HANDLE in the current buffer."
910   (let ((cur (current-buffer)))
911     (save-excursion
912       (if (member (mm-handle-media-supertype handle) '("text" "message"))
913           (with-temp-buffer
914             (insert-buffer-substring (mm-handle-buffer handle))
915             (prog1
916                 (mm-decode-content-transfer-encoding
917                  (mm-handle-encoding handle)
918                  (mm-handle-media-type handle))
919               (let ((temp (current-buffer)))
920                 (set-buffer cur)
921                 (insert-buffer-substring temp))))
922         (mm-with-unibyte-buffer
923           (insert-buffer-substring (mm-handle-buffer handle))
924           (prog1
925               (mm-decode-content-transfer-encoding
926                (mm-handle-encoding handle)
927                (mm-handle-media-type handle))
928             (let ((temp (current-buffer)))
929               (set-buffer cur)
930               (insert-buffer-substring temp))))))))
931
932 (defun mm-file-name-delete-whitespace (file-name)
933   "Remove all whitespace characters from FILE-NAME."
934   (while (string-match "\\s-+" file-name)
935     (setq file-name (replace-match "" t t file-name)))
936   file-name)
937
938 (defun mm-file-name-trim-whitespace (file-name)
939   "Remove leading and trailing whitespace characters from FILE-NAME."
940   (when (string-match "\\`\\s-+" file-name)
941     (setq file-name (substring file-name (match-end 0))))
942   (when (string-match "\\s-+\\'" file-name)
943     (setq file-name (substring file-name 0 (match-beginning 0))))
944   file-name)
945
946 (defun mm-file-name-collapse-whitespace (file-name)
947   "Collapse multiple whitespace characters in FILE-NAME."
948   (while (string-match "\\s-\\s-+" file-name)
949     (setq file-name (replace-match " " t t file-name)))
950   file-name)
951
952 (defun mm-file-name-replace-whitespace (file-name)
953   "Replace whitespace characters in FILE-NAME with underscores.
954 Set `mm-file-name-replace-whitespace' to any other string if you do not
955 like underscores."
956   (let ((s (or mm-file-name-replace-whitespace "_")))
957     (while (string-match "\\s-" file-name)
958       (setq file-name (replace-match s t t file-name))))
959   file-name)
960
961 (defun mm-save-part (handle)
962   "Write HANDLE to a file."
963   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
964          (filename (mail-content-type-get
965                     (mm-handle-disposition handle) 'filename))
966          file)
967     (when filename
968       (setq filename (gnus-map-function mm-file-name-rewrite-functions
969                                         (file-name-nondirectory filename))))
970     (setq file
971           (read-file-name "Save MIME part to: "
972                           (expand-file-name
973                            (or filename name "")
974                            (or mm-default-directory default-directory))))
975     (setq mm-default-directory (file-name-directory file))
976     (and (or (not (file-exists-p file))
977              (yes-or-no-p (format "File %s already exists; overwrite? "
978                                   file)))
979          (progn
980            (mm-save-part-to-file handle file)
981            file))))
982
983 (defun mm-save-part-to-file (handle file)
984   (mm-with-unibyte-buffer
985     (mm-insert-part handle)
986     (let ((coding-system-for-write 'binary)
987           ;; Don't re-compress .gz & al.  Arguably we should make
988           ;; `file-name-handler-alist' nil, but that would chop
989           ;; ange-ftp, which is reasonable to use here.
990           (inhibit-file-name-operation 'write-region)
991           (inhibit-file-name-handlers
992            (cons 'jka-compr-handler inhibit-file-name-handlers)))
993       (write-region (point-min) (point-max) file))))
994
995 (defun mm-pipe-part (handle)
996   "Pipe HANDLE to a process."
997   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
998          (command
999           (read-string "Shell command on MIME part: " mm-last-shell-command)))
1000     (mm-with-unibyte-buffer
1001       (mm-insert-part handle)
1002       (let ((coding-system-for-write 'binary))
1003         (shell-command-on-region (point-min) (point-max) command nil)))))
1004
1005 (defun mm-interactively-view-part (handle)
1006   "Display HANDLE using METHOD."
1007   (let* ((type (mm-handle-media-type handle))
1008          (methods
1009           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
1010                   (mailcap-mime-info type 'all)))
1011          (method (let ((minibuffer-local-completion-map
1012                         mm-viewer-completion-map))
1013                    (completing-read "Viewer: " methods))))
1014     (when (string= method "")
1015       (error "No method given"))
1016     (if (string-match "^[^% \t]+$" method)
1017         (setq method (concat method " %s")))
1018     (mm-display-external handle method)))
1019
1020 (defun mm-preferred-alternative (handles &optional preferred)
1021   "Say which of HANDLES are preferred."
1022   (let ((prec (if preferred (list preferred)
1023                 (mm-preferred-alternative-precedence handles)))
1024         p h result type handle)
1025     (while (setq p (pop prec))
1026       (setq h handles)
1027       (while h
1028         (setq handle (car h))
1029         (setq type (mm-handle-media-type handle))
1030         (when (and (equal p type)
1031                    (mm-automatic-display-p handle)
1032                    (or (stringp (car handle))
1033                        (not (mm-handle-disposition handle))
1034                        (equal (car (mm-handle-disposition handle))
1035                               "inline")))
1036           (setq result handle
1037                 h nil
1038                 prec nil))
1039         (pop h)))
1040     result))
1041
1042 (defun mm-preferred-alternative-precedence (handles)
1043   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1044   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1045                                handles))))
1046     (dolist (disc (reverse mm-discouraged-alternatives))
1047       (dolist (elem (copy-sequence seq))
1048         (when (string-match disc elem)
1049           (setq seq (nconc (delete elem seq) (list elem))))))
1050     seq))
1051
1052 (defun mm-get-content-id (id)
1053   "Return the handle(s) referred to by ID."
1054   (cdr (assoc id mm-content-id-alist)))
1055
1056 (defconst mm-image-type-regexps
1057   '(("/\\*.*XPM.\\*/" . xpm)
1058     ("P[1-6]" . pbm)
1059     ("GIF8" . gif)
1060     ("\377\330" . jpeg)
1061     ("\211PNG\r\n" . png)
1062     ("#define" . xbm)
1063     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1064     ("%!PS" . postscript))
1065   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1066 When the first bytes of an image file match REGEXP, it is assumed to
1067 be of image type IMAGE-TYPE.")
1068
1069 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1070 (defun mm-image-type-from-buffer ()
1071   "Determine the image type from data in the current buffer.
1072 Value is a symbol specifying the image type or nil if type cannot
1073 be determined."
1074   (let ((types mm-image-type-regexps)
1075         type)
1076     (goto-char (point-min))
1077     (while (and types (null type))
1078       (let ((regexp (car (car types)))
1079             (image-type (cdr (car types))))
1080         (when (looking-at regexp)
1081           (setq type image-type))
1082         (setq types (cdr types))))
1083     type))
1084
1085 (defun mm-get-image (handle)
1086   "Return an image instance based on HANDLE."
1087   (let ((type (mm-handle-media-subtype handle))
1088         spec)
1089     ;; Allow some common translations.
1090     (setq type
1091           (cond
1092            ((equal type "x-pixmap")
1093             "xpm")
1094            ((equal type "x-xbitmap")
1095             "xbm")
1096            ((equal type "x-portable-bitmap")
1097             "pbm")
1098            (t type)))
1099     (or (mm-handle-cache handle)
1100         (mm-with-unibyte-buffer
1101           (mm-insert-part handle)
1102           (prog1
1103               (setq spec
1104                     (ignore-errors
1105                       ;; Avoid testing `make-glyph' since W3 may define
1106                       ;; a bogus version of it.
1107                       (if (fboundp 'create-image)
1108                           (create-image (buffer-string)
1109                                         (or (mm-image-type-from-buffer)
1110                                             (intern type))
1111                                         'data-p)
1112                         (cond
1113                          ((equal type "xbm")
1114                           ;; xbm images require special handling, since
1115                           ;; the only way to create glyphs from these
1116                           ;; (without a ton of work) is to write them
1117                           ;; out to a file, and then create a file
1118                           ;; specifier.
1119                           (let ((file (make-temp-name
1120                                        (expand-file-name "emm.xbm"
1121                                                          mm-tmp-directory))))
1122                             (unwind-protect
1123                                 (progn
1124                                   (write-region (point-min) (point-max) file)
1125                                   (make-glyph (list (cons 'x file))))
1126                               (ignore-errors
1127                                 (delete-file file)))))
1128                          (t
1129                           (make-glyph
1130                            (vector
1131                             (or (mm-image-type-from-buffer)
1132                                 (intern type))
1133                             :data (buffer-string))))))))
1134             (mm-handle-set-cache handle spec))))))
1135
1136 (defun mm-image-fit-p (handle)
1137   "Say whether the image in HANDLE will fit the current window."
1138   (let ((image (mm-get-image handle)))
1139     (if (fboundp 'glyph-width)
1140         ;; XEmacs' glyphs can actually tell us about their width, so
1141         ;; lets be nice and smart about them.
1142         (or mm-inline-large-images
1143             (and (< (glyph-width image) (window-pixel-width))
1144                  (< (glyph-height image) (window-pixel-height))))
1145       (let* ((size (image-size image))
1146              (w (car size))
1147              (h (cdr size)))
1148         (or mm-inline-large-images
1149             (and (< h (1- (window-height))) ; Don't include mode line.
1150                  (< w (window-width))))))))
1151
1152 (defun mm-valid-image-format-p (format)
1153   "Say whether FORMAT can be displayed natively by Emacs."
1154   (cond
1155    ;; Handle XEmacs
1156    ((fboundp 'valid-image-instantiator-format-p)
1157     (valid-image-instantiator-format-p format))
1158    ;; Handle Emacs 21
1159    ((fboundp 'image-type-available-p)
1160     (and (display-graphic-p)
1161          (image-type-available-p format)))
1162    ;; Nobody else can do images yet.
1163    (t
1164     nil)))
1165
1166 (defun mm-valid-and-fit-image-p (format handle)
1167   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1168   (and (mm-valid-image-format-p format)
1169        (mm-image-fit-p handle)))
1170
1171 (defun mm-find-part-by-type (handles type &optional notp recursive)
1172   "Search in HANDLES for part with TYPE.
1173 If NOTP, returns first non-matching part.
1174 If RECURSIVE, search recursively."
1175   (let (handle)
1176     (while handles
1177       (if (and recursive (stringp (caar handles)))
1178           (if (setq handle (mm-find-part-by-type (cdar handles) type
1179                                                  notp recursive))
1180               (setq handles nil))
1181         (if (if notp
1182                 (not (equal (mm-handle-media-type (car handles)) type))
1183               (equal (mm-handle-media-type (car handles)) type))
1184             (setq handle (car handles)
1185                   handles nil)))
1186       (setq handles (cdr handles)))
1187     handle))
1188
1189 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1190   (goto-char (point-min))
1191   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1192                                                                    'boundary)))
1193          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1194          start
1195          (end (save-excursion
1196                 (goto-char (point-max))
1197                 (if (re-search-backward close-delimiter nil t)
1198                     (match-beginning 0)
1199                   (point-max))))
1200          result)
1201     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1202     (while (and (not result)
1203                 (re-search-forward boundary end t))
1204       (goto-char (match-beginning 0))
1205       (when start
1206         (save-excursion
1207           (save-restriction
1208             (narrow-to-region start (1- (point)))
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       (forward-line 1)
1217       (setq start (point)))
1218     (when (and (not result) start)
1219       (save-excursion
1220         (save-restriction
1221           (narrow-to-region start end)
1222           (when (let ((ctl (ignore-errors
1223                              (mail-header-parse-content-type
1224                               (mail-fetch-field "content-type")))))
1225                   (if notp
1226                       (not (equal (car ctl) type))
1227                     (equal (car ctl) type)))
1228             (setq result (buffer-substring (point-min) (point-max)))))))
1229     result))
1230
1231 (defvar mm-security-handle nil)
1232
1233 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1234   ;; HANDLE could be a CTL.
1235   (if handle
1236       (put-text-property 0 (length (car handle)) parameter value
1237                          (car handle))))
1238
1239 (defun mm-possibly-verify-or-decrypt (parts ctl)
1240   (let ((type (car ctl))
1241         (subtype (cadr (split-string (car ctl) "/")))
1242         (mm-security-handle ctl) ;; (car CTL) is the type.
1243         protocol func functest)
1244     (cond
1245      ((or (equal type "application/x-pkcs7-mime")
1246           (equal type "application/pkcs7-mime"))
1247       (with-temp-buffer
1248         (when (and (cond
1249                     ((eq mm-decrypt-option 'never) nil)
1250                     ((eq mm-decrypt-option 'always) t)
1251                     ((eq mm-decrypt-option 'known) t)
1252                     (t (y-or-n-p
1253                         (format "Decrypt (S/MIME) part? "))))
1254                    (mm-view-pkcs7 parts))
1255           (setq parts (mm-dissect-buffer t)))))
1256      ((equal subtype "signed")
1257       (unless (and (setq protocol
1258                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1259                    (not (equal protocol "multipart/mixed")))
1260         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1261         (let ((protocols mm-verify-function-alist))
1262           (while protocols
1263             (if (and (or (not (setq functest (nth 3 (car protocols))))
1264                          (funcall functest parts ctl))
1265                      (mm-find-part-by-type parts (caar protocols) nil t))
1266                 (setq protocol (caar protocols)
1267                       protocols nil)
1268               (setq protocols (cdr protocols))))))
1269       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1270       (if (cond
1271            ((eq mm-verify-option 'never) nil)
1272            ((eq mm-verify-option 'always) t)
1273            ((eq mm-verify-option 'known)
1274             (and func
1275                  (or (not (setq functest
1276                                 (nth 3 (assoc protocol
1277                                               mm-verify-function-alist))))
1278                      (funcall functest parts ctl))))
1279            (t (y-or-n-p
1280                (format "Verify signed (%s) part? "
1281                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1282                            (format "protocol=%s" protocol))))))
1283           (save-excursion
1284             (if func
1285                 (funcall func parts ctl)
1286               (mm-set-handle-multipart-parameter
1287                mm-security-handle 'gnus-details
1288                (format "Unknown sign protocol (%s)" protocol))))))
1289      ((equal subtype "encrypted")
1290       (unless (setq protocol
1291                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1292         ;; The message is broken.
1293         (let ((parts parts))
1294           (while parts
1295             (if (assoc (mm-handle-media-type (car parts))
1296                        mm-decrypt-function-alist)
1297                 (setq protocol (mm-handle-media-type (car parts))
1298                       parts nil)
1299               (setq parts (cdr parts))))))
1300       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1301       (if (cond
1302            ((eq mm-decrypt-option 'never) nil)
1303            ((eq mm-decrypt-option 'always) t)
1304            ((eq mm-decrypt-option 'known)
1305             (and func
1306                  (or (not (setq functest
1307                                 (nth 3 (assoc protocol
1308                                               mm-decrypt-function-alist))))
1309                      (funcall functest parts ctl))))
1310            (t (y-or-n-p
1311                (format "Decrypt (%s) part? "
1312                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1313                            (format "protocol=%s" protocol))))))
1314           (save-excursion
1315             (if func
1316                 (setq parts (funcall func parts ctl))
1317               (mm-set-handle-multipart-parameter
1318                mm-security-handle 'gnus-details
1319                (format "Unknown encrypt protocol (%s)" protocol))))))
1320      (t nil))
1321     parts))
1322
1323 (defun mm-multiple-handles (handles)
1324   (and (listp (car handles))
1325        (> (length handles) 1)))
1326
1327 (defun mm-merge-handles (handles1 handles2)
1328   (append
1329    (if (listp (car handles1))
1330        handles1
1331      (list handles1))
1332    (if (listp (car handles2))
1333        handles2
1334      (list handles2))))
1335
1336 (defun mm-readable-p (handle)
1337   "Say whether the content of HANDLE is readable."
1338   (and (< (with-current-buffer (mm-handle-buffer handle)
1339             (buffer-size)) 10000)
1340        (mm-with-unibyte-buffer
1341          (mm-insert-part handle)
1342          (and (eq (mm-body-7-or-8) '7bit)
1343               (not (mm-long-lines-p 76))))))
1344
1345 (provide 'mm-decode)
1346
1347 ;;; mm-decode.el ends here