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