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