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