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