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