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