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