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