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