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