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