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