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