(gnus-mime-view-part-internally): Bind buffer-read-only to nil.
[gnus] / 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 '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 ((obuf (current-buffer))
590           beg)
591       (goto-char (point-min))
592       (search-forward-regexp "^\n" nil t)
593       (setq beg (point))
594       (set-buffer (generate-new-buffer " *mm*"))
595       (insert-buffer-substring obuf beg)
596       (current-buffer))))
597
598 (defun mm-display-parts (handle &optional no-default)
599   (if (stringp (car handle))
600       (mapcar 'mm-display-parts (cdr handle))
601     (if (bufferp (car handle))
602         (save-restriction
603           (narrow-to-region (point) (point))
604           (mm-display-part handle)
605           (goto-char (point-max)))
606       (mapcar 'mm-display-parts handle))))
607
608 (defun mm-display-part (handle &optional no-default)
609   "Display the MIME part represented by HANDLE.
610 Returns nil if the part is removed; inline if displayed inline;
611 external if displayed external."
612   (save-excursion
613     (mailcap-parse-mailcaps)
614     (if (mm-handle-displayed-p handle)
615         (mm-remove-part handle)
616       (let* ((type (mm-handle-media-type handle))
617              (method (mailcap-mime-info type)))
618         (if (and (mm-inlinable-p handle)
619                  (mm-inlined-p handle))
620             (progn
621               (forward-line 1)
622               (mm-display-inline handle)
623               'inline)
624           (when (or method
625                     (not no-default))
626             (if (and (not method)
627                      (equal "text" (car (split-string type))))
628                 (progn
629                   (forward-line 1)
630                   (mm-insert-inline handle (mm-get-part handle))
631                   'inline)
632               (mm-display-external
633                handle (or method 'mailcap-save-binary-file)))))))))
634
635 (defun mm-display-external (handle method)
636   "Display HANDLE using METHOD."
637   (let ((outbuf (current-buffer)))
638     (mm-with-unibyte-buffer
639       (if (functionp method)
640           (let ((cur (current-buffer)))
641             (if (eq method 'mailcap-save-binary-file)
642                 (progn
643                   (set-buffer (generate-new-buffer " *mm*"))
644                   (setq method nil))
645               (mm-insert-part handle)
646               (let ((win (get-buffer-window cur t)))
647                 (when win
648                   (select-window win)))
649               (switch-to-buffer (generate-new-buffer " *mm*")))
650             (buffer-disable-undo)
651             (mm-set-buffer-file-coding-system mm-binary-coding-system)
652             (insert-buffer-substring cur)
653             (goto-char (point-min))
654             (message "Viewing with %s" method)
655             (let ((mm (current-buffer))
656                   (non-viewer (assq 'non-viewer
657                                     (mailcap-mime-info
658                                      (mm-handle-media-type handle) t))))
659               (unwind-protect
660                   (if method
661                       (funcall method)
662                     (mm-save-part handle))
663                 (when (and (not non-viewer)
664                            method)
665                   (mm-handle-set-undisplayer handle mm)))))
666         ;; The function is a string to be executed.
667         (mm-insert-part handle)
668         (let* ((dir (mm-make-temp-file
669                      (expand-file-name "emm." mm-tmp-directory) 'dir))
670                (filename (or
671                           (mail-content-type-get
672                            (mm-handle-disposition handle) 'filename)
673                           (mail-content-type-get
674                            (mm-handle-type handle) 'name)))
675                (mime-info (mailcap-mime-info
676                            (mm-handle-media-type handle) t))
677                (needsterm (or (assoc "needsterm" mime-info)
678                               (assoc "needsterminal" mime-info)))
679                (copiousoutput (assoc "copiousoutput" mime-info))
680                file buffer)
681           ;; We create a private sub-directory where we store our files.
682           (set-file-modes dir 448)
683           (if filename
684               (setq file (expand-file-name
685                           (gnus-map-function mm-file-name-rewrite-functions
686                                              (file-name-nondirectory filename))
687                           dir))
688             (setq file (mm-make-temp-file (expand-file-name "mm." dir))))
689           (let ((coding-system-for-write mm-binary-coding-system))
690             (write-region (point-min) (point-max) file nil 'nomesg))
691           (message "Viewing with %s" method)
692           (cond
693            (needsterm
694             (let ((command (mm-mailcap-command
695                             method file (mm-handle-type handle))))
696               (unwind-protect
697                   (if window-system
698                       (start-process "*display*" nil
699                                      mm-external-terminal-program
700                                      "-e" shell-file-name
701                                      shell-command-switch command)
702                     (require 'term)
703                     (require 'gnus-win)
704                     (set-buffer
705                      (setq buffer
706                            (make-term "display"
707                                       shell-file-name
708                                       nil
709                                       shell-command-switch command)))
710                     (term-mode)
711                     (term-char-mode)
712                     (set-process-sentinel
713                      (get-buffer-process buffer)
714                      `(lambda (process state)
715                         (if (eq 'exit (process-status process))
716                             (gnus-configure-windows
717                              ',gnus-current-window-configuration))))
718                     (gnus-configure-windows 'display-term))
719                 (mm-handle-set-external-undisplayer handle (cons file buffer)))
720               (message "Displaying %s..." command))
721             'external)
722            (copiousoutput
723             (with-current-buffer outbuf
724               (forward-line 1)
725               (mm-insert-inline
726                handle
727                (unwind-protect
728                    (progn
729                      (call-process shell-file-name nil
730                                    (setq buffer
731                                          (generate-new-buffer " *mm*"))
732                                    nil
733                                    shell-command-switch
734                                    (mm-mailcap-command
735                                     method file (mm-handle-type handle)))
736                      (if (buffer-live-p buffer)
737                          (save-excursion
738                            (set-buffer buffer)
739                            (buffer-string))))
740                  (progn
741                    (ignore-errors (delete-file file))
742                    (ignore-errors (delete-directory
743                                    (file-name-directory file)))
744                    (ignore-errors (kill-buffer buffer))))))
745             'inline)
746            (t
747             (let ((command (mm-mailcap-command
748                             method file (mm-handle-type handle))))
749               (unwind-protect
750                   (start-process "*display*"
751                                  (setq buffer
752                                        (generate-new-buffer " *mm*"))
753                                  shell-file-name
754                                  shell-command-switch command)
755                 (mm-handle-set-external-undisplayer
756                  handle (cons file buffer)))
757               (message "Displaying %s..." command))
758             'external)))))))
759
760 (defun mm-mailcap-command (method file type-list)
761   (let ((ctl (cdr type-list))
762         (beg 0)
763         (uses-stdin t)
764         out sub total)
765     (while (string-match "%{\\([^}]+\\)}\\|'%s'\\|\"%s\"\\|%s\\|%t\\|%%"
766                          method beg)
767       (push (substring method beg (match-beginning 0)) out)
768       (setq beg (match-end 0)
769             total (match-string 0 method)
770             sub (match-string 1 method))
771       (cond
772        ((string= total "%%")
773         (push "%" out))
774        ((or (string= total "%s")
775             ;; We do our own quoting.
776             (string= total "'%s'")
777             (string= total "\"%s\""))
778         (setq uses-stdin nil)
779         (push (mm-quote-arg
780                (gnus-map-function mm-path-name-rewrite-functions file)) out))
781        ((string= total "%t")
782         (push (mm-quote-arg (car type-list)) out))
783        (t
784         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
785     (push (substring method beg (length method)) out)
786     (when uses-stdin
787       (push "<" out)
788       (push (mm-quote-arg
789              (gnus-map-function mm-path-name-rewrite-functions file))
790             out))
791     (mapconcat 'identity (nreverse out) "")))
792
793 (defun mm-remove-parts (handles)
794   "Remove the displayed MIME parts represented by HANDLES."
795   (if (and (listp handles)
796            (bufferp (car handles)))
797       (mm-remove-part handles)
798     (let (handle)
799       (while (setq handle (pop handles))
800         (cond
801          ((stringp handle)
802           (when (buffer-live-p (get-text-property 0 'buffer handle))
803             (kill-buffer (get-text-property 0 'buffer handle))))
804          ((and (listp handle)
805                (stringp (car handle)))
806           (mm-remove-parts (cdr handle)))
807          (t
808           (mm-remove-part handle)))))))
809
810 (defun mm-destroy-parts (handles)
811   "Remove the displayed MIME parts represented by HANDLES."
812   (if (and (listp handles)
813            (bufferp (car handles)))
814       (mm-destroy-part handles)
815     (let (handle)
816       (while (setq handle (pop handles))
817         (cond
818          ((stringp handle)
819           (when (buffer-live-p (get-text-property 0 'buffer handle))
820             (kill-buffer (get-text-property 0 'buffer handle))))
821          ((and (listp handle)
822                (stringp (car handle)))
823           (mm-destroy-parts handle))
824          (t
825           (mm-destroy-part handle)))))))
826
827 (defun mm-remove-part (handle)
828   "Remove the displayed MIME part represented by HANDLE."
829   (when (listp handle)
830     (let ((object (mm-handle-undisplayer handle)))
831       (ignore-errors
832         (cond
833          ;; Internally displayed part.
834          ((mm-annotationp object)
835           (delete-annotation object))
836          ((or (functionp object)
837               (and (listp object)
838                    (eq (car object) 'lambda)))
839           (funcall object))
840          ;; Externally displayed part.
841          ((consp object)
842           (ignore-errors (delete-file (car object)))
843           (ignore-errors (delete-directory (file-name-directory (car object))))
844           (ignore-errors (and (cdr object) (kill-buffer (cdr object)))))
845          ((bufferp object)
846           (when (buffer-live-p object)
847             (kill-buffer object)))))
848       (mm-handle-set-undisplayer handle nil))))
849
850 (defun mm-display-inline (handle)
851   (let* ((type (mm-handle-media-type handle))
852          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
853     (funcall function handle)
854     (goto-char (point-min))))
855
856 (defun mm-assoc-string-match (alist type)
857   (dolist (elem alist)
858     (when (string-match (car elem) type)
859       (return elem))))
860
861 (defun mm-automatic-display-p (handle)
862   "Say whether the user wants HANDLE to be displayed automatically."
863   (let ((methods mm-automatic-display)
864         (type (mm-handle-media-type handle))
865         method result)
866     (while (setq method (pop methods))
867       (when (and (not (mm-inline-override-p handle))
868                  (string-match method type))
869         (setq result t
870               methods nil)))
871     result))
872
873 (defun mm-inlinable-p (handle)
874   "Say whether HANDLE can be displayed inline."
875   (let ((alist mm-inline-media-tests)
876         (type (mm-handle-media-type handle))
877         test)
878     (while alist
879       (when (string-match (caar alist) type)
880         (setq test (caddar alist)
881               alist nil)
882         (setq test (funcall test handle)))
883       (pop alist))
884     test))
885
886 (defun mm-inlined-p (handle)
887   "Say whether the user wants HANDLE to be displayed inline."
888   (let ((methods mm-inlined-types)
889         (type (mm-handle-media-type handle))
890         method result)
891     (while (setq method (pop methods))
892       (when (and (not (mm-inline-override-p handle))
893                  (string-match method type))
894         (setq result t
895               methods nil)))
896     result))
897
898 (defun mm-attachment-override-p (handle)
899   "Say whether HANDLE should have attachment behavior overridden."
900   (let ((types mm-attachment-override-types)
901         (type (mm-handle-media-type handle))
902         ty)
903     (catch 'found
904       (while (setq ty (pop types))
905         (when (and (string-match ty type)
906                    (mm-inlinable-p handle))
907           (throw 'found t))))))
908
909 (defun mm-inline-override-p (handle)
910   "Say whether HANDLE should have inline behavior overridden."
911   (let ((types mm-inline-override-types)
912         (type (mm-handle-media-type handle))
913         ty)
914     (catch 'found
915       (while (setq ty (pop types))
916         (when (string-match ty type)
917           (throw 'found t))))))
918
919 (defun mm-automatic-external-display-p (type)
920   "Return the user-defined method for TYPE."
921   (let ((methods mm-automatic-external-display)
922         method result)
923     (while (setq method (pop methods))
924       (when (string-match method type)
925         (setq result t
926               methods nil)))
927     result))
928
929 (defun mm-destroy-part (handle)
930   "Destroy the data structures connected to HANDLE."
931   (when (listp handle)
932     (mm-remove-part handle)
933     (when (buffer-live-p (mm-handle-buffer handle))
934       (kill-buffer (mm-handle-buffer handle)))))
935
936 (defun mm-handle-displayed-p (handle)
937   "Say whether HANDLE is displayed or not."
938   (mm-handle-undisplayer handle))
939
940 ;;;
941 ;;; Functions for outputting parts
942 ;;;
943
944 (defun mm-get-part (handle)
945   "Return the contents of HANDLE as a string."
946   (mm-with-unibyte-buffer
947     (insert (with-current-buffer (mm-handle-buffer handle)
948               (mm-with-unibyte-current-buffer
949                 (buffer-string))))
950     (mm-decode-content-transfer-encoding
951      (mm-handle-encoding handle)
952      (mm-handle-media-type handle))
953     (buffer-string)))
954
955 (defun mm-insert-part (handle)
956   "Insert the contents of HANDLE in the current buffer."
957   (let ((cur (current-buffer)))
958     (save-excursion
959       (if (member (mm-handle-media-supertype handle) '("text" "message"))
960           (with-temp-buffer
961             (insert-buffer-substring (mm-handle-buffer handle))
962             (prog1
963                 (mm-decode-content-transfer-encoding
964                  (mm-handle-encoding handle)
965                  (mm-handle-media-type handle))
966               (let ((temp (current-buffer)))
967                 (set-buffer cur)
968                 (insert-buffer-substring temp))))
969         (mm-with-unibyte-buffer
970           (insert-buffer-substring (mm-handle-buffer handle))
971           (prog1
972               (mm-decode-content-transfer-encoding
973                (mm-handle-encoding handle)
974                (mm-handle-media-type handle))
975             (let ((temp (current-buffer)))
976               (set-buffer cur)
977               (insert-buffer-substring temp))))))))
978
979 (defun mm-file-name-delete-whitespace (file-name)
980   "Remove all whitespace characters from FILE-NAME."
981   (while (string-match "\\s-+" file-name)
982     (setq file-name (replace-match "" t t file-name)))
983   file-name)
984
985 (defun mm-file-name-trim-whitespace (file-name)
986   "Remove leading and trailing whitespace characters from FILE-NAME."
987   (when (string-match "\\`\\s-+" file-name)
988     (setq file-name (substring file-name (match-end 0))))
989   (when (string-match "\\s-+\\'" file-name)
990     (setq file-name (substring file-name 0 (match-beginning 0))))
991   file-name)
992
993 (defun mm-file-name-collapse-whitespace (file-name)
994   "Collapse multiple whitespace characters in FILE-NAME."
995   (while (string-match "\\s-\\s-+" file-name)
996     (setq file-name (replace-match " " t t file-name)))
997   file-name)
998
999 (defun mm-file-name-replace-whitespace (file-name)
1000   "Replace whitespace characters in FILE-NAME with underscores.
1001 Set `mm-file-name-replace-whitespace' to any other string if you do not
1002 like underscores."
1003   (let ((s (or mm-file-name-replace-whitespace "_")))
1004     (while (string-match "\\s-" file-name)
1005       (setq file-name (replace-match s t t file-name))))
1006   file-name)
1007
1008 (defun mm-save-part (handle)
1009   "Write HANDLE to a file."
1010   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1011          (filename (mail-content-type-get
1012                     (mm-handle-disposition handle) 'filename))
1013          file)
1014     (when filename
1015       (setq filename (gnus-map-function mm-file-name-rewrite-functions
1016                                         (file-name-nondirectory filename))))
1017     (setq file
1018           (read-file-name "Save MIME part to: "
1019                           (or mm-default-directory default-directory)
1020                           nil nil (or filename name "")))
1021     (setq mm-default-directory (file-name-directory file))
1022     (and (or (not (file-exists-p file))
1023              (yes-or-no-p (format "File %s already exists; overwrite? "
1024                                   file)))
1025          (progn
1026            (mm-save-part-to-file handle file)
1027            file))))
1028
1029 (defun mm-save-part-to-file (handle file)
1030   (mm-with-unibyte-buffer
1031     (mm-insert-part handle)
1032     (let ((coding-system-for-write 'binary)
1033           ;; Don't re-compress .gz & al.  Arguably we should make
1034           ;; `file-name-handler-alist' nil, but that would chop
1035           ;; ange-ftp, which is reasonable to use here.
1036           (inhibit-file-name-operation 'write-region)
1037           (inhibit-file-name-handlers
1038            (cons 'jka-compr-handler inhibit-file-name-handlers)))
1039       (write-region (point-min) (point-max) file))))
1040
1041 (defun mm-pipe-part (handle)
1042   "Pipe HANDLE to a process."
1043   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1044          (command
1045           (read-string "Shell command on MIME part: " mm-last-shell-command)))
1046     (mm-with-unibyte-buffer
1047       (mm-insert-part handle)
1048       (let ((coding-system-for-write 'binary))
1049         (shell-command-on-region (point-min) (point-max) command nil)))))
1050
1051 (defun mm-interactively-view-part (handle)
1052   "Display HANDLE using METHOD."
1053   (let* ((type (mm-handle-media-type handle))
1054          (methods
1055           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
1056                   (mailcap-mime-info type 'all)))
1057          (method (let ((minibuffer-local-completion-map
1058                         mm-viewer-completion-map))
1059                    (completing-read "Viewer: " methods))))
1060     (when (string= method "")
1061       (error "No method given"))
1062     (if (string-match "^[^% \t]+$" method)
1063         (setq method (concat method " %s")))
1064     (mm-display-external handle method)))
1065
1066 (defun mm-preferred-alternative (handles &optional preferred)
1067   "Say which of HANDLES are preferred."
1068   (let ((prec (if preferred (list preferred)
1069                 (mm-preferred-alternative-precedence handles)))
1070         p h result type handle)
1071     (while (setq p (pop prec))
1072       (setq h handles)
1073       (while h
1074         (setq handle (car h))
1075         (setq type (mm-handle-media-type handle))
1076         (when (and (equal p type)
1077                    (mm-automatic-display-p handle)
1078                    (or (stringp (car handle))
1079                        (not (mm-handle-disposition handle))
1080                        (equal (car (mm-handle-disposition handle))
1081                               "inline")))
1082           (setq result handle
1083                 h nil
1084                 prec nil))
1085         (pop h)))
1086     result))
1087
1088 (defun mm-preferred-alternative-precedence (handles)
1089   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1090   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1091                                handles))))
1092     (dolist (disc (reverse mm-discouraged-alternatives))
1093       (dolist (elem (copy-sequence seq))
1094         (when (string-match disc elem)
1095           (setq seq (nconc (delete elem seq) (list elem))))))
1096     seq))
1097
1098 (defun mm-get-content-id (id)
1099   "Return the handle(s) referred to by ID."
1100   (cdr (assoc id mm-content-id-alist)))
1101
1102 (defconst mm-image-type-regexps
1103   '(("/\\*.*XPM.\\*/" . xpm)
1104     ("P[1-6]" . pbm)
1105     ("GIF8" . gif)
1106     ("\377\330" . jpeg)
1107     ("\211PNG\r\n" . png)
1108     ("#define" . xbm)
1109     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1110     ("%!PS" . postscript))
1111   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1112 When the first bytes of an image file match REGEXP, it is assumed to
1113 be of image type IMAGE-TYPE.")
1114
1115 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1116 (defun mm-image-type-from-buffer ()
1117   "Determine the image type from data in the current buffer.
1118 Value is a symbol specifying the image type or nil if type cannot
1119 be determined."
1120   (let ((types mm-image-type-regexps)
1121         type)
1122     (goto-char (point-min))
1123     (while (and types (null type))
1124       (let ((regexp (car (car types)))
1125             (image-type (cdr (car types))))
1126         (when (looking-at regexp)
1127           (setq type image-type))
1128         (setq types (cdr types))))
1129     type))
1130
1131 (defun mm-get-image (handle)
1132   "Return an image instance based on HANDLE."
1133   (let ((type (mm-handle-media-subtype handle))
1134         spec)
1135     ;; Allow some common translations.
1136     (setq type
1137           (cond
1138            ((equal type "x-pixmap")
1139             "xpm")
1140            ((equal type "x-xbitmap")
1141             "xbm")
1142            ((equal type "x-portable-bitmap")
1143             "pbm")
1144            (t type)))
1145     (or (mm-handle-cache handle)
1146         (mm-with-unibyte-buffer
1147           (mm-insert-part handle)
1148           (prog1
1149               (setq spec
1150                     (ignore-errors
1151                       ;; Avoid testing `make-glyph' since W3 may define
1152                       ;; a bogus version of it.
1153                       (if (fboundp 'create-image)
1154                           (create-image (buffer-string)
1155                                         (or (mm-image-type-from-buffer)
1156                                             (intern type))
1157                                         'data-p)
1158                         (mm-create-image-xemacs type))))
1159             (mm-handle-set-cache handle spec))))))
1160
1161 (defun mm-create-image-xemacs (type)
1162   (cond
1163    ((equal type "xbm")
1164     ;; xbm images require special handling, since
1165     ;; the only way to create glyphs from these
1166     ;; (without a ton of work) is to write them
1167     ;; out to a file, and then create a file
1168     ;; specifier.
1169     (let ((file (mm-make-temp-file
1170                  (expand-file-name "emm.xbm"
1171                                    mm-tmp-directory))))
1172       (unwind-protect
1173           (progn
1174             (write-region (point-min) (point-max) file)
1175             (make-glyph (list (cons 'x file))))
1176         (ignore-errors
1177           (delete-file file)))))
1178    (t
1179     (make-glyph
1180      (vector
1181       (or (mm-image-type-from-buffer)
1182           (intern type))
1183       :data (buffer-string))))))
1184
1185 (defun mm-image-fit-p (handle)
1186   "Say whether the image in HANDLE will fit the current window."
1187   (let ((image (mm-get-image handle)))
1188     (if (fboundp 'glyph-width)
1189         ;; XEmacs' glyphs can actually tell us about their width, so
1190         ;; lets be nice and smart about them.
1191         (or mm-inline-large-images
1192             (and (< (glyph-width image) (window-pixel-width))
1193                  (< (glyph-height image) (window-pixel-height))))
1194       (let* ((size (image-size image))
1195              (w (car size))
1196              (h (cdr size)))
1197         (or mm-inline-large-images
1198             (and (< h (1- (window-height))) ; Don't include mode line.
1199                  (< w (window-width))))))))
1200
1201 (defun mm-valid-image-format-p (format)
1202   "Say whether FORMAT can be displayed natively by Emacs."
1203   (cond
1204    ;; Handle XEmacs
1205    ((fboundp 'valid-image-instantiator-format-p)
1206     (valid-image-instantiator-format-p format))
1207    ;; Handle Emacs 21
1208    ((fboundp 'image-type-available-p)
1209     (and (display-graphic-p)
1210          (image-type-available-p format)))
1211    ;; Nobody else can do images yet.
1212    (t
1213     nil)))
1214
1215 (defun mm-valid-and-fit-image-p (format handle)
1216   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1217   (and (mm-valid-image-format-p format)
1218        (mm-image-fit-p handle)))
1219
1220 (defun mm-find-part-by-type (handles type &optional notp recursive)
1221   "Search in HANDLES for part with TYPE.
1222 If NOTP, returns first non-matching part.
1223 If RECURSIVE, search recursively."
1224   (let (handle)
1225     (while handles
1226       (if (and recursive (stringp (caar handles)))
1227           (if (setq handle (mm-find-part-by-type (cdar handles) type
1228                                                  notp recursive))
1229               (setq handles nil))
1230         (if (if notp
1231                 (not (equal (mm-handle-media-type (car handles)) type))
1232               (equal (mm-handle-media-type (car handles)) type))
1233             (setq handle (car handles)
1234                   handles nil)))
1235       (setq handles (cdr handles)))
1236     handle))
1237
1238 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1239   (goto-char (point-min))
1240   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1241                                                                    'boundary)))
1242          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1243          start
1244          (end (save-excursion
1245                 (goto-char (point-max))
1246                 (if (re-search-backward close-delimiter nil t)
1247                     (match-beginning 0)
1248                   (point-max))))
1249          result)
1250     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1251     (while (and (not result)
1252                 (re-search-forward boundary end t))
1253       (goto-char (match-beginning 0))
1254       (when start
1255         (save-excursion
1256           (save-restriction
1257             (narrow-to-region start (1- (point)))
1258             (when (let ((ctl (ignore-errors
1259                                (mail-header-parse-content-type
1260                                 (mail-fetch-field "content-type")))))
1261                     (if notp
1262                         (not (equal (car ctl) type))
1263                       (equal (car ctl) type)))
1264               (setq result (buffer-substring (point-min) (point-max)))))))
1265       (forward-line 1)
1266       (setq start (point)))
1267     (when (and (not result) start)
1268       (save-excursion
1269         (save-restriction
1270           (narrow-to-region start end)
1271           (when (let ((ctl (ignore-errors
1272                              (mail-header-parse-content-type
1273                               (mail-fetch-field "content-type")))))
1274                   (if notp
1275                       (not (equal (car ctl) type))
1276                     (equal (car ctl) type)))
1277             (setq result (buffer-substring (point-min) (point-max)))))))
1278     result))
1279
1280 (defvar mm-security-handle nil)
1281
1282 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1283   ;; HANDLE could be a CTL.
1284   (when handle
1285     (put-text-property 0 (length (car handle)) parameter value
1286                        (car handle))))
1287
1288 (defun mm-possibly-verify-or-decrypt (parts ctl)
1289   (let ((type (car ctl))
1290         (subtype (cadr (split-string (car ctl) "/")))
1291         (mm-security-handle ctl) ;; (car CTL) is the type.
1292         protocol func functest)
1293     (cond
1294      ((or (equal type "application/x-pkcs7-mime")
1295           (equal type "application/pkcs7-mime"))
1296       (with-temp-buffer
1297         (when (and (cond
1298                     ((eq mm-decrypt-option 'never) nil)
1299                     ((eq mm-decrypt-option 'always) t)
1300                     ((eq mm-decrypt-option 'known) t)
1301                     (t (y-or-n-p
1302                         (format "Decrypt (S/MIME) part? "))))
1303                    (mm-view-pkcs7 parts))
1304           (setq parts (mm-dissect-buffer t)))))
1305      ((equal subtype "signed")
1306       (unless (and (setq protocol
1307                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1308                    (not (equal protocol "multipart/mixed")))
1309         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1310         (let ((protocols mm-verify-function-alist))
1311           (while protocols
1312             (if (and (or (not (setq functest (nth 3 (car protocols))))
1313                          (funcall functest parts ctl))
1314                      (mm-find-part-by-type parts (caar protocols) nil t))
1315                 (setq protocol (caar protocols)
1316                       protocols nil)
1317               (setq protocols (cdr protocols))))))
1318       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1319       (when (cond
1320              ((eq mm-verify-option 'never) nil)
1321              ((eq mm-verify-option 'always) t)
1322              ((eq mm-verify-option 'known)
1323               (and func
1324                    (or (not (setq functest
1325                                   (nth 3 (assoc protocol
1326                                                 mm-verify-function-alist))))
1327                        (funcall functest parts ctl))))
1328              (t
1329               (y-or-n-p
1330                (format "Verify signed (%s) part? "
1331                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1332                            (format "protocol=%s" protocol))))))
1333         (save-excursion
1334           (if func
1335               (funcall func parts ctl)
1336             (mm-set-handle-multipart-parameter
1337              mm-security-handle 'gnus-details
1338              (format "Unknown sign protocol (%s)" protocol))))))
1339      ((equal subtype "encrypted")
1340       (unless (setq protocol
1341                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1342         ;; The message is broken.
1343         (let ((parts parts))
1344           (while parts
1345             (if (assoc (mm-handle-media-type (car parts))
1346                        mm-decrypt-function-alist)
1347                 (setq protocol (mm-handle-media-type (car parts))
1348                       parts nil)
1349               (setq parts (cdr parts))))))
1350       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1351       (when (cond
1352              ((eq mm-decrypt-option 'never) nil)
1353              ((eq mm-decrypt-option 'always) t)
1354              ((eq mm-decrypt-option 'known)
1355               (and func
1356                    (or (not (setq functest
1357                                   (nth 3 (assoc protocol
1358                                                 mm-decrypt-function-alist))))
1359                        (funcall functest parts ctl))))
1360              (t
1361               (y-or-n-p
1362                (format "Decrypt (%s) part? "
1363                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1364                            (format "protocol=%s" protocol))))))
1365         (save-excursion
1366           (if func
1367               (setq parts (funcall func parts ctl))
1368             (mm-set-handle-multipart-parameter
1369              mm-security-handle 'gnus-details
1370              (format "Unknown encrypt protocol (%s)" protocol))))))
1371      (t nil))
1372     parts))
1373
1374 (defun mm-multiple-handles (handles)
1375   (and (listp (car handles))
1376        (> (length handles) 1)))
1377
1378 (defun mm-merge-handles (handles1 handles2)
1379   (append
1380    (if (listp (car handles1))
1381        handles1
1382      (list handles1))
1383    (if (listp (car handles2))
1384        handles2
1385      (list handles2))))
1386
1387 (defun mm-readable-p (handle)
1388   "Say whether the content of HANDLE is readable."
1389   (and (< (with-current-buffer (mm-handle-buffer handle)
1390             (buffer-size)) 10000)
1391        (mm-with-unibyte-buffer
1392          (mm-insert-part handle)
1393          (and (eq (mm-body-7-or-8) '7bit)
1394               (not (mm-long-lines-p 76))))))
1395
1396 (provide 'mm-decode)
1397
1398 ;;; mm-decode.el ends here