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