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