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