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