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