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