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