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