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