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