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