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