Delete temporary files when Gnus exits instead of using timers
[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
634 (autoload 'message-fetch-field "message")
635
636 (defun mm-dissect-buffer (&optional no-strict-mime loose-mime from)
637   "Dissect the current buffer and return a list of MIME handles.
638 If NO-STRICT-MIME, don't require the message to have a
639 MIME-Version header before proceeding."
640   (save-excursion
641     (let (ct ctl type subtype cte cd description id result)
642       (save-restriction
643         (mail-narrow-to-head)
644         (when (or no-strict-mime
645                   loose-mime
646                   (mail-fetch-field "mime-version"))
647           (setq ct (mail-fetch-field "content-type")
648                 ctl (and ct (mail-header-parse-content-type ct))
649                 cte (mail-fetch-field "content-transfer-encoding")
650                 cd (or (mail-fetch-field "content-disposition")
651                        (when (and ctl
652                                   (eq 'mm-inline-text
653                                       (cadr (mm-assoc-string-match
654                                              mm-inline-media-tests
655                                              (car ctl)))))
656                          "inline"))
657                 ;; Newlines in description should be stripped so as
658                 ;; not to break the MIME tag into two or more lines.
659                 description (message-fetch-field "content-description")
660                 id (mail-fetch-field "content-id"))
661           (unless from
662             (setq from (mail-fetch-field "from")))
663           ;; FIXME: In some circumstances, this code is running within
664           ;; an unibyte macro.  mail-extract-address-components
665           ;; creates unibyte buffers. This `if', though not a perfect
666           ;; solution, avoids most of them.
667           (if from
668               (setq from (cadr (mail-extract-address-components from))))
669           (if description
670               (setq description (mail-decode-encoded-word-string
671                                  description)))))
672       (if (or (not ctl)
673               (not (string-match "/" (car ctl))))
674           (mm-dissect-singlepart
675            (list mm-dissect-default-type)
676            (and cte (intern (downcase (mail-header-strip cte))))
677            no-strict-mime
678            (and cd (mail-header-parse-content-disposition cd))
679            description)
680         (setq type (split-string (car ctl) "/"))
681         (setq subtype (cadr type)
682               type (car type))
683         (setq
684          result
685          (cond
686           ((equal type "multipart")
687            (let ((mm-dissect-default-type (if (equal subtype "digest")
688                                               "message/rfc822"
689                                             "text/plain"))
690                  (start (cdr (assq 'start (cdr ctl)))))
691              (add-text-properties 0 (length (car ctl))
692                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
693
694              ;; what really needs to be done here is a way to link a
695              ;; MIME handle back to it's parent MIME handle (in a multilevel
696              ;; MIME article).  That would probably require changing
697              ;; the mm-handle API so we simply store the multipart buffer
698              ;; name as a text property of the "multipart/whatever" string.
699              (add-text-properties 0 (length (car ctl))
700                                   (list 'buffer (mm-copy-to-buffer)
701                                         'from from
702                                         'start start)
703                                   (car ctl))
704              (cons (car ctl) (mm-dissect-multipart ctl from))))
705           (t
706            (mm-possibly-verify-or-decrypt
707             (mm-dissect-singlepart
708              ctl
709              (and cte (intern (downcase (mail-header-strip cte))))
710              no-strict-mime
711              (and cd (mail-header-parse-content-disposition cd))
712              description id)
713             ctl from))))
714         (when id
715           (when (string-match " *<\\(.*\\)> *" id)
716             (setq id (match-string 1 id)))
717           (push (cons id result) mm-content-id-alist))
718         result))))
719
720 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
721   (when (or force
722             (if (equal "text/plain" (car ctl))
723                 (assoc 'format ctl)
724               t))
725     ;; Guess what the type of application/octet-stream parts should
726     ;; really be.
727     (let ((filename (cdr (assq 'filename (cdr cdl)))))
728       (when (and (not mm-inhibit-auto-detect-attachment)
729                  (equal (car ctl) "application/octet-stream")
730                  filename
731                  (string-match "\\.\\([^.]+\\)$" filename))
732         (let ((new-type (mailcap-extension-to-mime (match-string 1 filename))))
733           (when new-type
734             (setcar ctl new-type)))))
735     (let ((handle
736            (mm-make-handle
737             (mm-copy-to-buffer) ctl cte nil cdl description nil id))
738           (decoder (assoc (car ctl) (mm-archive-decoders))))
739       (if (and decoder
740                ;; Do automatic decoding
741                (cadr decoder)
742                (executable-find (caddr decoder)))
743           (mm-dissect-archive handle)
744         handle))))
745
746 (defun mm-dissect-multipart (ctl from)
747   (goto-char (point-min))
748   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
749          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
750          start parts
751          (end (save-excursion
752                 (goto-char (point-max))
753                 (if (re-search-backward close-delimiter nil t)
754                     (match-beginning 0)
755                   (point-max))))
756          (mm-inhibit-auto-detect-attachment
757           (equal (car ctl) "multipart/encrypted")))
758     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
759     (while (and (< (point) end) (re-search-forward boundary end t))
760       (goto-char (match-beginning 0))
761       (when start
762         (save-excursion
763           (save-restriction
764             (narrow-to-region start (point))
765             (setq parts (nconc (list (mm-dissect-buffer t nil from)) parts)))))
766       (end-of-line 2)
767       (or (looking-at boundary)
768           (forward-line 1))
769       (setq start (point)))
770     (when (and start (< start end))
771       (save-excursion
772         (save-restriction
773           (narrow-to-region start end)
774           (setq parts (nconc (list (mm-dissect-buffer t nil from)) parts)))))
775     (mm-possibly-verify-or-decrypt (nreverse parts) ctl from)))
776
777 (defun mm-copy-to-buffer ()
778   "Copy the contents of the current buffer to a fresh buffer."
779   (let ((obuf (current-buffer))
780         (mb (mm-multibyte-p))
781         beg)
782     (goto-char (point-min))
783     (search-forward-regexp "^\n" nil t)
784     (setq beg (point))
785     (with-current-buffer
786           (generate-new-buffer " *mm*")
787       ;; Preserve the data's unibyteness (for url-insert-file-contents).
788       (mm-set-buffer-multibyte mb)
789       (insert-buffer-substring obuf beg)
790       (current-buffer))))
791
792 (defun mm-display-parts (handle &optional no-default)
793   (if (stringp (car handle))
794       (mapcar 'mm-display-parts (cdr handle))
795     (if (bufferp (car handle))
796         (save-restriction
797           (narrow-to-region (point) (point))
798           (mm-display-part handle)
799           (goto-char (point-max)))
800       (mapcar 'mm-display-parts handle))))
801
802 (autoload 'mailcap-parse-mailcaps "mailcap")
803 (autoload 'mailcap-mime-info "mailcap")
804
805 (defun mm-display-part (handle &optional no-default force)
806   "Display the MIME part represented by HANDLE.
807 Returns nil if the part is removed; inline if displayed inline;
808 external if displayed external."
809   (save-excursion
810     (mailcap-parse-mailcaps)
811     (if (and (not force)
812              (mm-handle-displayed-p handle))
813         (mm-remove-part handle)
814       (let* ((ehandle (if (equal (mm-handle-media-type handle)
815                                  "message/external-body")
816                           (progn
817                             (unless (mm-handle-cache handle)
818                               (mm-extern-cache-contents handle))
819                             (mm-handle-cache handle))
820                         handle))
821              (type (mm-handle-media-type ehandle))
822              (method (mailcap-mime-info type))
823              (filename (or (mail-content-type-get
824                             (mm-handle-disposition handle) 'filename)
825                            (mail-content-type-get
826                             (mm-handle-type handle) 'name)
827                            "<file>"))
828              (external mm-enable-external)
829              (decoder (assoc (car (mm-handle-type handle))
830                              (mm-archive-decoders))))
831         (cond
832          ((and decoder
833                (executable-find (caddr decoder)))
834           (mm-archive-dissect-and-inline handle)
835           'inline)
836          ((and (mm-inlinable-p ehandle)
837                (mm-inlined-p ehandle))
838           (forward-line 1)
839           (mm-display-inline handle)
840           'inline)
841          ((or method
842               (not no-default))
843           (if (and (not method)
844                    (equal "text" (car (split-string type "/"))))
845               (progn
846                 (forward-line 1)
847                 (mm-insert-inline handle (mm-get-part handle))
848                 'inline)
849             (setq external
850                   (and method         ;; If nil, we always use "save".
851                        (stringp method) ;; 'mailcap-save-binary-file
852                        (or (eq mm-enable-external t)
853                            (and (eq mm-enable-external 'ask)
854                                 (y-or-n-p
855                                  (concat
856                                   "Display part (" type
857                                   ") using external program"
858                                   ;; Can non-string method ever happen?
859                                   (if (stringp method)
860                                       (concat
861                                        " \"" (format method filename) "\"")
862                                     "")
863                                   "? "))))))
864             (if external
865                 (mm-display-external
866                  handle (or method 'mailcap-save-binary-file))
867               (mm-display-external
868                handle 'mailcap-save-binary-file)))))))))
869
870 (declare-function gnus-configure-windows "gnus-win" (setting &optional force))
871 (defvar mailcap-mime-extensions)        ; mailcap-mime-info autoloads
872 (declare-function term-mode "term" ())
873 (declare-function term-char-mode "term" ())
874
875 (defun mm-display-external (handle method)
876   "Display HANDLE using METHOD."
877   (let ((outbuf (current-buffer)))
878     (mm-with-unibyte-buffer
879       (if (functionp method)
880           (let ((cur (current-buffer)))
881             (if (eq method 'mailcap-save-binary-file)
882                 (progn
883                   (set-buffer (generate-new-buffer " *mm*"))
884                   (setq method nil))
885               (mm-insert-part handle)
886               (mm-add-meta-html-tag handle)
887               (let ((win (get-buffer-window cur t)))
888                 (when win
889                   (select-window win)))
890               (switch-to-buffer (generate-new-buffer " *mm*")))
891             (buffer-disable-undo)
892             (mm-set-buffer-file-coding-system mm-binary-coding-system)
893             (insert-buffer-substring cur)
894             (goto-char (point-min))
895             (when method
896               (message "Viewing with %s" method))
897             (let ((mm (current-buffer))
898                   (non-viewer (assq 'non-viewer
899                                     (mailcap-mime-info
900                                      (mm-handle-media-type handle) t))))
901               (unwind-protect
902                   (if method
903                       (funcall method)
904                     (mm-save-part handle))
905                 (when (and (not non-viewer)
906                            method)
907                   (mm-handle-set-undisplayer handle mm)))))
908         ;; The function is a string to be executed.
909         (mm-insert-part handle)
910         (mm-add-meta-html-tag handle)
911         (let* ((dir (mm-make-temp-file
912                      (expand-file-name "emm." mm-tmp-directory) 'dir))
913                (filename (or
914                           (mail-content-type-get
915                            (mm-handle-disposition handle) 'filename)
916                           (mail-content-type-get
917                            (mm-handle-type handle) 'name)))
918                (mime-info (mailcap-mime-info
919                            (mm-handle-media-type handle) t))
920                (needsterm (or (assoc "needsterm" mime-info)
921                               (assoc "needsterminal" mime-info)))
922                (copiousoutput (assoc "copiousoutput" mime-info))
923                file buffer)
924           ;; We create a private sub-directory where we store our files.
925           (set-file-modes dir #o700)
926           (if filename
927               (setq file (expand-file-name
928                           (gnus-map-function mm-file-name-rewrite-functions
929                                              (file-name-nondirectory filename))
930                           dir))
931             ;; Use nametemplate (defined in RFC1524) if it is specified
932             ;; in mailcap.
933             (let ((suffix (cdr (assoc "nametemplate" mime-info))))
934               (if (and suffix
935                        (string-match "\\`%s\\(\\..+\\)\\'" suffix))
936                   (setq suffix (match-string 1 suffix))
937                 ;; Otherwise, use a suffix according to
938                 ;; `mailcap-mime-extensions'.
939                 (setq suffix (car (rassoc (mm-handle-media-type handle)
940                                           mailcap-mime-extensions))))
941               (setq file (mm-make-temp-file (expand-file-name "mm." dir)
942                                             nil suffix))))
943           (let ((coding-system-for-write mm-binary-coding-system))
944             (write-region (point-min) (point-max) file nil 'nomesg))
945           ;; The file is deleted after the viewer exists.  If the users edits
946           ;; the file, changes will be lost.  Set file to read-only to make it
947           ;; clear.
948           (set-file-modes file #o400)
949           (message "Viewing with %s" method)
950           (cond
951            (needsterm
952             (let ((command (mm-mailcap-command
953                             method file (mm-handle-type handle))))
954               (unwind-protect
955                   (if window-system
956                       (start-process "*display*" nil
957                                      mm-external-terminal-program
958                                      "-e" shell-file-name
959                                      shell-command-switch command)
960                     (require 'term)
961                     (require 'gnus-win)
962                     (set-buffer
963                      (setq buffer
964                            (make-term "display"
965                                       shell-file-name
966                                       nil
967                                       shell-command-switch command)))
968                     (term-mode)
969                     (term-char-mode)
970                     (set-process-sentinel
971                      (get-buffer-process buffer)
972                      `(lambda (process state)
973                         (if (eq 'exit (process-status process))
974                             (gnus-configure-windows
975                              ',gnus-current-window-configuration))))
976                     (gnus-configure-windows 'display-term))
977                 (mm-handle-set-external-undisplayer handle (cons file buffer)))
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                            (when (buffer-live-p outbuf)
1026                              (with-current-buffer outbuf
1027                                (let ((buffer-read-only nil)
1028                                      (point (point)))
1029                                  (forward-line 2)
1030                                  (let ((start (point)))
1031                                    (mm-insert-inline
1032                                     handle (with-current-buffer buffer
1033                                              (buffer-string)))
1034                                    (put-text-property start (point)
1035                                                       'face 'mm-command-output))
1036                                  (goto-char point))))
1037                            (when (buffer-live-p buffer)
1038                              (kill-buffer buffer)))
1039                          (message "Displaying %s...done" command)))))
1040                 (mm-handle-set-external-undisplayer
1041                  handle (cons file buffer))
1042                 (add-to-list 'mm-temp-files-to-be-deleted file t))
1043               (message "Displaying %s..." command))
1044             'external)))))))
1045
1046 (defun mm-mailcap-command (method file type-list)
1047   (let ((ctl (cdr type-list))
1048         (beg 0)
1049         (uses-stdin t)
1050         out sub total)
1051     (while (string-match "%{\\([^}]+\\)}\\|'%s'\\|\"%s\"\\|%s\\|%t\\|%%"
1052                          method beg)
1053       (push (substring method beg (match-beginning 0)) out)
1054       (setq beg (match-end 0)
1055             total (match-string 0 method)
1056             sub (match-string 1 method))
1057       (cond
1058        ((string= total "%%")
1059         (push "%" out))
1060        ((or (string= total "%s")
1061             ;; We do our own quoting.
1062             (string= total "'%s'")
1063             (string= total "\"%s\""))
1064         (setq uses-stdin nil)
1065         (push (shell-quote-argument
1066                (gnus-map-function mm-path-name-rewrite-functions file)) out))
1067        ((string= total "%t")
1068         (push (shell-quote-argument (car type-list)) out))
1069        (t
1070         (push (shell-quote-argument (or (cdr (assq (intern sub) ctl)) "")) out))))
1071     (push (substring method beg (length method)) out)
1072     (when uses-stdin
1073       (push "<" out)
1074       (push (shell-quote-argument
1075              (gnus-map-function mm-path-name-rewrite-functions file))
1076             out))
1077     (mapconcat 'identity (nreverse out) "")))
1078
1079 (defun mm-remove-parts (handles)
1080   "Remove the displayed MIME parts represented by HANDLES."
1081   (if (and (listp handles)
1082            (bufferp (car handles)))
1083       (mm-remove-part handles)
1084     (let (handle)
1085       (while (setq handle (pop handles))
1086         (cond
1087          ((stringp handle)
1088           (when (buffer-live-p (get-text-property 0 'buffer handle))
1089             (kill-buffer (get-text-property 0 'buffer handle))))
1090          ((and (listp handle)
1091                (stringp (car handle)))
1092           (mm-remove-parts (cdr handle)))
1093          (t
1094           (mm-remove-part handle)))))))
1095
1096 (defun mm-destroy-parts (handles)
1097   "Remove the displayed MIME parts represented by HANDLES."
1098   (if (and (listp handles)
1099            (bufferp (car handles)))
1100       (mm-destroy-part handles)
1101     (let (handle)
1102       (while (setq handle (pop handles))
1103         (cond
1104          ((stringp handle)
1105           (when (buffer-live-p (get-text-property 0 'buffer handle))
1106             (kill-buffer (get-text-property 0 'buffer handle))))
1107          ((and (listp handle)
1108                (stringp (car handle)))
1109           (mm-destroy-parts handle))
1110          (t
1111           (mm-destroy-part handle)))))))
1112
1113 (defun mm-remove-part (handle)
1114   "Remove the displayed MIME part represented by HANDLE."
1115   (when (listp handle)
1116     (let ((object (mm-handle-undisplayer handle)))
1117       (ignore-errors
1118         (cond
1119          ;; Internally displayed part.
1120          ((mm-annotationp object)
1121           (if (featurep 'xemacs)
1122               (delete-annotation object)))
1123          ((or (functionp object)
1124               (and (listp object)
1125                    (eq (car object) 'lambda)))
1126           (funcall object))
1127          ;; Externally displayed part.
1128          ((consp object)
1129           (condition-case ()
1130               (while (get-buffer-process (cdr object))
1131                 (interrupt-process (get-buffer-process (cdr object)))
1132                 (message "Waiting for external displayer to die...")
1133                 (sit-for 1))
1134             (quit)
1135             (error))
1136           (ignore-errors (and (cdr object) (kill-buffer (cdr object))))
1137           (message "Waiting for external displayer to die...done")
1138           (ignore-errors (delete-file (car object)))
1139           (ignore-errors (delete-directory (file-name-directory
1140                                             (car object)))))
1141          ((bufferp object)
1142           (when (buffer-live-p object)
1143             (kill-buffer object)))))
1144       (mm-handle-set-undisplayer handle nil))))
1145
1146 (defun mm-display-inline (handle)
1147   (let* ((type (mm-handle-media-type handle))
1148          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
1149     (funcall function handle)
1150     (goto-char (point-min))))
1151
1152 (defun mm-assoc-string-match (alist type)
1153   (dolist (elem alist)
1154     (when (string-match (car elem) type)
1155       (return elem))))
1156
1157 (defun mm-automatic-display-p (handle)
1158   "Say whether the user wants HANDLE to be displayed automatically."
1159   (let ((methods mm-automatic-display)
1160         (type (mm-handle-media-type handle))
1161         method result)
1162     (while (setq method (pop methods))
1163       (when (and (not (mm-inline-override-p handle))
1164                  (string-match method type))
1165         (setq result t
1166               methods nil)))
1167     result))
1168
1169 (defun mm-inlinable-p (handle &optional type)
1170   "Say whether HANDLE can be displayed inline.
1171 TYPE is the mime-type of the object; it defaults to the one given
1172 in HANDLE."
1173   (unless type (setq type (mm-handle-media-type handle)))
1174   (let ((alist mm-inline-media-tests)
1175         test)
1176     (while alist
1177       (when (string-match (caar alist) type)
1178         (setq test (caddar alist)
1179               alist nil)
1180         (setq test (funcall test handle)))
1181       (pop alist))
1182     test))
1183
1184 (defun mm-inlined-p (handle)
1185   "Say whether the user wants HANDLE to be displayed inline."
1186   (let ((methods mm-inlined-types)
1187         (type (mm-handle-media-type handle))
1188         method result)
1189     (while (setq method (pop methods))
1190       (when (and (not (mm-inline-override-p handle))
1191                  (string-match method type))
1192         (setq result t
1193               methods nil)))
1194     result))
1195
1196 (defun mm-attachment-override-p (handle)
1197   "Say whether HANDLE should have attachment behavior overridden."
1198   (let ((types mm-attachment-override-types)
1199         (type (mm-handle-media-type handle))
1200         ty)
1201     (catch 'found
1202       (while (setq ty (pop types))
1203         (when (and (string-match ty type)
1204                    (mm-inlinable-p handle))
1205           (throw 'found t))))))
1206
1207 (defun mm-inline-override-p (handle)
1208   "Say whether HANDLE should have inline behavior overridden."
1209   (let ((types mm-inline-override-types)
1210         (type (mm-handle-media-type handle))
1211         ty)
1212     (catch 'found
1213       (while (setq ty (pop types))
1214         (when (string-match ty type)
1215           (throw 'found t))))))
1216
1217 (defun mm-automatic-external-display-p (type)
1218   "Return the user-defined method for TYPE."
1219   (let ((methods mm-automatic-external-display)
1220         method result)
1221     (while (setq method (pop methods))
1222       (when (string-match method type)
1223         (setq result t
1224               methods nil)))
1225     result))
1226
1227 (defun mm-destroy-part (handle)
1228   "Destroy the data structures connected to HANDLE."
1229   (when (listp handle)
1230     (mm-remove-part handle)
1231     (when (buffer-live-p (mm-handle-buffer handle))
1232       (kill-buffer (mm-handle-buffer handle)))))
1233
1234 (defun mm-handle-displayed-p (handle)
1235   "Say whether HANDLE is displayed or not."
1236   (mm-handle-undisplayer handle))
1237
1238 ;;;
1239 ;;; Functions for outputting parts
1240 ;;;
1241
1242 (defmacro mm-with-part (handle &rest forms)
1243   "Run FORMS in the temp buffer containing the contents of HANDLE."
1244   ;; The handle-buffer's content is a sequence of bytes, not a sequence of
1245   ;; chars, so the buffer should be unibyte.  It may happen that the
1246   ;; handle-buffer is multibyte for some reason, in which case now is a good
1247   ;; time to adjust it, since we know at this point that it should
1248   ;; be unibyte.
1249   `(let* ((handle ,handle))
1250      (when (and (mm-handle-buffer handle)
1251                 (buffer-name (mm-handle-buffer handle)))
1252        (with-temp-buffer
1253          (mm-disable-multibyte)
1254          (insert-buffer-substring (mm-handle-buffer handle))
1255          (mm-decode-content-transfer-encoding
1256           (mm-handle-encoding handle)
1257           (mm-handle-media-type handle))
1258          ,@forms))))
1259 (put 'mm-with-part 'lisp-indent-function 1)
1260 (put 'mm-with-part 'edebug-form-spec '(body))
1261
1262 (defun mm-get-part (handle &optional no-cache)
1263   "Return the contents of HANDLE as a string.
1264 If NO-CACHE is non-nil, cached contents of a message/external-body part
1265 are ignored."
1266   (if (and (not no-cache)
1267            (equal (mm-handle-media-type handle) "message/external-body"))
1268       (progn
1269         (unless (mm-handle-cache handle)
1270           (mm-extern-cache-contents handle))
1271         (with-current-buffer (mm-handle-buffer (mm-handle-cache handle))
1272           (buffer-string)))
1273     (mm-with-part handle
1274       (buffer-string))))
1275
1276 (defun mm-insert-part (handle &optional no-cache)
1277   "Insert the contents of HANDLE in the current buffer.
1278 If NO-CACHE is non-nil, cached contents of a message/external-body part
1279 are ignored."
1280   (let ((text (cond ((eq (mail-content-type-get (mm-handle-type handle)
1281                                                 'charset)
1282                          'gnus-decoded)
1283                      (with-current-buffer (mm-handle-buffer handle)
1284                        (buffer-string)))
1285                     ((mm-multibyte-p)
1286                      (mm-string-to-multibyte (mm-get-part handle no-cache)))
1287                     (t
1288                      (mm-get-part handle no-cache)))))
1289     (save-restriction
1290       (widen)
1291       (goto-char
1292        (prog1
1293            (point)
1294          (if (and (eq (get-char-property (max (point-min) (1- (point))) 'face)
1295                       'mm-uu-extract)
1296                   (eq (get-char-property 0 'face text) 'mm-uu-extract))
1297              ;; Separate the extracted parts that have the same faces.
1298              (insert "\n" text)
1299            (insert text)))))))
1300
1301 (defun mm-file-name-delete-whitespace (file-name)
1302   "Remove all whitespace characters from FILE-NAME."
1303   (while (string-match "\\s-+" file-name)
1304     (setq file-name (replace-match "" t t file-name)))
1305   file-name)
1306
1307 (defun mm-file-name-trim-whitespace (file-name)
1308   "Remove leading and trailing whitespace characters from FILE-NAME."
1309   (when (string-match "\\`\\s-+" file-name)
1310     (setq file-name (substring file-name (match-end 0))))
1311   (when (string-match "\\s-+\\'" file-name)
1312     (setq file-name (substring file-name 0 (match-beginning 0))))
1313   file-name)
1314
1315 (defun mm-file-name-collapse-whitespace (file-name)
1316   "Collapse multiple whitespace characters in FILE-NAME."
1317   (while (string-match "\\s-\\s-+" file-name)
1318     (setq file-name (replace-match " " t t file-name)))
1319   file-name)
1320
1321 (defun mm-file-name-replace-whitespace (file-name)
1322   "Replace whitespace characters in FILE-NAME with underscores.
1323 Set the option `mm-file-name-replace-whitespace' to any other
1324 string if you do not like underscores."
1325   (let ((s (or mm-file-name-replace-whitespace "_")))
1326     (while (string-match "\\s-" file-name)
1327       (setq file-name (replace-match s t t file-name))))
1328   file-name)
1329
1330 (defun mm-file-name-delete-control (filename)
1331   "Delete control characters from FILENAME."
1332   (gnus-replace-in-string filename "[\x00-\x1f\x7f]" ""))
1333
1334 (defun mm-file-name-delete-gotchas (filename)
1335   "Delete shell gotchas from FILENAME."
1336   (setq filename (gnus-replace-in-string filename "[<>|]" ""))
1337   (gnus-replace-in-string filename "^[.-]+" ""))
1338
1339 (defun mm-save-part (handle &optional prompt)
1340   "Write HANDLE to a file.
1341 PROMPT overrides the default one used to ask user for a file name."
1342   (let ((filename (or (mail-content-type-get
1343                        (mm-handle-disposition handle) 'filename)
1344                       (mail-content-type-get
1345                        (mm-handle-type handle) 'name)))
1346         file)
1347     (when filename
1348       (setq filename (gnus-map-function mm-file-name-rewrite-functions
1349                                         (file-name-nondirectory filename))))
1350     (while
1351         (progn
1352           (setq file
1353                 (read-file-name
1354                  (or prompt
1355                      (format "Save MIME part to (default %s): "
1356                              (or filename "")))
1357                  (or mm-default-directory default-directory)
1358                  (expand-file-name (or filename "")
1359                                    (or mm-default-directory default-directory))))
1360           (cond ((or (not file) (equal file ""))
1361                  (message "Please enter a file name")
1362                  t)
1363                 ((and (file-directory-p file)
1364                       (not filename))
1365                  (message "Please enter a non-directory file name")
1366                  t)
1367                 (t nil)))
1368       (sit-for 2)
1369       (discard-input))
1370     (if (file-directory-p file)
1371         (setq file (expand-file-name filename file))
1372       (setq file (expand-file-name
1373                   file (or mm-default-directory default-directory))))
1374     (setq mm-default-directory (file-name-directory file))
1375     (and (or (not (file-exists-p file))
1376              (yes-or-no-p (format "File %s already exists; overwrite? "
1377                                   file)))
1378          (progn
1379            (mm-save-part-to-file handle file)
1380            file))))
1381
1382 (defun mm-add-meta-html-tag (handle &optional charset force-charset)
1383   "Add meta html tag to specify CHARSET of HANDLE in the current buffer.
1384 CHARSET defaults to the one HANDLE specifies.  Existing meta tag that
1385 specifies charset will not be modified unless FORCE-CHARSET is non-nil.
1386 Return t if meta tag is added or replaced."
1387   (when (equal (mm-handle-media-type handle) "text/html")
1388     (when (or charset
1389               (setq charset (mail-content-type-get (mm-handle-type handle)
1390                                                    'charset)))
1391       (setq charset (format "\
1392 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">" charset))
1393       (let ((case-fold-search t))
1394         (goto-char (point-min))
1395         (if (re-search-forward "\
1396 <meta\\s-+http-equiv=[\"']?content-type[\"']?\\s-+content=[\"']\
1397 text/\\(\\sw+\\)\\(?:\;\\s-*charset=\\(.+\\)\\)?[\"'][^>]*>" nil t)
1398             (if (and (not force-charset)
1399                      (match-beginning 2)
1400                      (string-match "\\`html\\'" (match-string 1)))
1401                 ;; Don't modify existing meta tag.
1402                 nil
1403               ;; Replace it with the one specifying charset.
1404               (replace-match charset)
1405               t)
1406           (if (re-search-forward "<head>\\s-*" nil t)
1407               (insert charset "\n")
1408             (re-search-forward "<html\\(?:\\s-+[^>]+\\|\\s-*\\)>\\s-*" nil t)
1409             (insert "<head>\n" charset "\n</head>\n"))
1410           t)))))
1411
1412 (defun mm-save-part-to-file (handle file)
1413   (mm-with-unibyte-buffer
1414     (mm-insert-part handle)
1415     (mm-add-meta-html-tag handle)
1416     (let ((current-file-modes (default-file-modes)))
1417       (set-default-file-modes mm-attachment-file-modes)
1418       (unwind-protect
1419           ;; Don't re-compress .gz & al.  Arguably we should make
1420           ;; `file-name-handler-alist' nil, but that would chop
1421           ;; ange-ftp, which is reasonable to use here.
1422           (mm-write-region (point-min) (point-max) file nil nil nil 'binary t)
1423         (set-default-file-modes current-file-modes)))))
1424
1425 (defun mm-pipe-part (handle &optional cmd)
1426   "Pipe HANDLE to a process.
1427 Use CMD as the process."
1428   (let ((name (mail-content-type-get (mm-handle-type handle) 'name))
1429         (command (or cmd
1430                      (gnus-read-shell-command
1431                       "Shell command on MIME part: " mm-last-shell-command))))
1432     (mm-with-unibyte-buffer
1433       (mm-insert-part handle)
1434       (mm-add-meta-html-tag handle)
1435       (let ((coding-system-for-write 'binary))
1436         (shell-command-on-region (point-min) (point-max) command nil)))))
1437
1438 (autoload 'gnus-completing-read "gnus-util")
1439
1440 (defun mm-interactively-view-part (handle)
1441   "Display HANDLE using METHOD."
1442   (let* ((type (mm-handle-media-type handle))
1443          (methods
1444           (mapcar (lambda (i) (cdr (assoc 'viewer i)))
1445                   (mailcap-mime-info type 'all)))
1446          (method (let ((minibuffer-local-completion-map
1447                         mm-viewer-completion-map))
1448                    (completing-read "Viewer: " methods))))
1449     (when (string= method "")
1450       (error "No method given"))
1451     (if (string-match "^[^% \t]+$" method)
1452         (setq method (concat method " %s")))
1453     (mm-display-external handle method)))
1454
1455 (defun mm-preferred-alternative (handles &optional preferred)
1456   "Say which of HANDLES are preferred."
1457   (let ((prec (if preferred (list preferred)
1458                 (mm-preferred-alternative-precedence handles)))
1459         p h result type handle)
1460     (while (setq p (pop prec))
1461       (setq h handles)
1462       (while h
1463         (setq handle (car h))
1464         (setq type (mm-handle-media-type handle))
1465         (when (and (equal p type)
1466                    (mm-automatic-display-p handle)
1467                    (or (stringp (car handle))
1468                        (not (mm-handle-disposition handle))
1469                        (equal (car (mm-handle-disposition handle))
1470                               "inline")))
1471           (setq result handle
1472                 h nil
1473                 prec nil))
1474         (pop h)))
1475     result))
1476
1477 (defun mm-preferred-alternative-precedence (handles)
1478   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1479   (setq handles (reverse handles))
1480   (dolist (disc (reverse mm-discouraged-alternatives))
1481     (dolist (handle (copy-sequence handles))
1482       (when (string-match disc (mm-handle-media-type handle))
1483         (setq handles (nconc (delete handle handles) (list handle))))))
1484   ;; Remove empty parts.
1485   (dolist (handle (copy-sequence handles))
1486     (when (and (bufferp (mm-handle-buffer handle))
1487                (not (with-current-buffer (mm-handle-buffer handle)
1488                       (goto-char (point-min))
1489                       (re-search-forward "[^ \t\n]" nil t))))
1490       (setq handles (nconc (delete handle handles) (list handle)))))
1491   (mapcar #'mm-handle-media-type handles))
1492
1493 (defun mm-get-content-id (id)
1494   "Return the handle(s) referred to by ID."
1495   (cdr (assoc id mm-content-id-alist)))
1496
1497 (defconst mm-image-type-regexps
1498   '(("/\\*.*XPM.\\*/" . xpm)
1499     ("P[1-6]" . pbm)
1500     ("GIF8" . gif)
1501     ("\377\330" . jpeg)
1502     ("\211PNG\r\n" . png)
1503     ("#define" . xbm)
1504     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1505     ("%!PS" . postscript))
1506   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1507 When the first bytes of an image file match REGEXP, it is assumed to
1508 be of image type IMAGE-TYPE.")
1509
1510 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1511 (defun mm-image-type-from-buffer ()
1512   "Determine the image type from data in the current buffer.
1513 Value is a symbol specifying the image type or nil if type cannot
1514 be determined."
1515   (let ((types mm-image-type-regexps)
1516         type)
1517     (goto-char (point-min))
1518     (while (and types (null type))
1519       (let ((regexp (car (car types)))
1520             (image-type (cdr (car types))))
1521         (when (looking-at regexp)
1522           (setq type image-type))
1523         (setq types (cdr types))))
1524     type))
1525
1526 (defun mm-get-image (handle)
1527   "Return an image instance based on HANDLE."
1528   (let ((type (mm-handle-media-subtype handle))
1529         spec)
1530     ;; Allow some common translations.
1531     (setq type
1532           (cond
1533            ((equal type "x-pixmap")
1534             "xpm")
1535            ((equal type "x-xbitmap")
1536             "xbm")
1537            ((equal type "x-portable-bitmap")
1538             "pbm")
1539            (t type)))
1540     (or (mm-handle-cache handle)
1541         (mm-with-unibyte-buffer
1542           (mm-insert-part handle)
1543           (prog1
1544               (setq spec
1545                     (ignore-errors
1546                       ;; Avoid testing `make-glyph' since W3 may define
1547                       ;; a bogus version of it.
1548                       (if (fboundp 'create-image)
1549                           (create-image (buffer-string)
1550                                         (or (mm-image-type-from-buffer)
1551                                             (intern type))
1552                                         'data-p)
1553                         (mm-create-image-xemacs type))))
1554             (mm-handle-set-cache handle spec))))))
1555
1556 (defun mm-create-image-xemacs (type)
1557   (when (featurep 'xemacs)
1558     (cond
1559      ((equal type "xbm")
1560       ;; xbm images require special handling, since
1561       ;; the only way to create glyphs from these
1562       ;; (without a ton of work) is to write them
1563       ;; out to a file, and then create a file
1564       ;; specifier.
1565       (let ((file (mm-make-temp-file
1566                    (expand-file-name "emm" mm-tmp-directory)
1567                    nil ".xbm")))
1568         (unwind-protect
1569             (progn
1570               (write-region (point-min) (point-max) file)
1571               (make-glyph (list (cons 'x file))))
1572           (ignore-errors
1573             (delete-file file)))))
1574      (t
1575       (make-glyph
1576        (vector
1577         (or (mm-image-type-from-buffer)
1578             (intern type))
1579         :data (buffer-string)))))))
1580
1581 (declare-function image-size "image.c" (spec &optional pixels frame))
1582
1583 (defun mm-image-fit-p (handle)
1584   "Say whether the image in HANDLE will fit the current window."
1585   (let ((image (mm-get-image handle)))
1586     (or (not image)
1587         (if (featurep 'xemacs)
1588             ;; XEmacs's glyphs can actually tell us about their width, so
1589             ;; let's be nice and smart about them.
1590             (or mm-inline-large-images
1591                 (and (<= (glyph-width image) (window-pixel-width))
1592                      (<= (glyph-height image) (window-pixel-height))))
1593           (let* ((size (image-size image))
1594                  (w (car size))
1595                  (h (cdr size)))
1596             (or mm-inline-large-images
1597                 (and (<= h (1- (window-height))) ; Don't include mode line.
1598                      (<= w (window-width)))))))))
1599
1600 (defun mm-valid-image-format-p (format)
1601   "Say whether FORMAT can be displayed natively by Emacs."
1602   (cond
1603    ;; Handle XEmacs
1604    ((fboundp 'valid-image-instantiator-format-p)
1605     (valid-image-instantiator-format-p format))
1606    ;; Handle Emacs
1607    ((fboundp 'image-type-available-p)
1608     (and (display-graphic-p)
1609          (image-type-available-p format)))
1610    ;; Nobody else can do images yet.
1611    (t
1612     nil)))
1613
1614 (defun mm-valid-and-fit-image-p (format handle)
1615   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1616   (and (mm-valid-image-format-p format)
1617        (mm-image-fit-p handle)))
1618
1619 (defun mm-find-part-by-type (handles type &optional notp recursive)
1620   "Search in HANDLES for part with TYPE.
1621 If NOTP, returns first non-matching part.
1622 If RECURSIVE, search recursively."
1623   (let (handle)
1624     (while handles
1625       (if (and recursive (stringp (caar handles)))
1626           (if (setq handle (mm-find-part-by-type (cdar handles) type
1627                                                  notp recursive))
1628               (setq handles nil))
1629         (if (if notp
1630                 (not (equal (mm-handle-media-type (car handles)) type))
1631               (equal (mm-handle-media-type (car handles)) type))
1632             (setq handle (car handles)
1633                   handles nil)))
1634       (setq handles (cdr handles)))
1635     handle))
1636
1637 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1638   (goto-char (point-min))
1639   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1640                                                                    'boundary)))
1641          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1642          start
1643          (end (save-excursion
1644                 (goto-char (point-max))
1645                 (if (re-search-backward close-delimiter nil t)
1646                     (match-beginning 0)
1647                   (point-max))))
1648          result)
1649     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1650     (while (and (not result)
1651                 (re-search-forward boundary end t))
1652       (goto-char (match-beginning 0))
1653       (when start
1654         (save-excursion
1655           (save-restriction
1656             (narrow-to-region start (1- (point)))
1657             (when (let* ((ct (mail-fetch-field "content-type"))
1658                          (ctl (and ct (mail-header-parse-content-type ct))))
1659                     (if notp
1660                         (not (equal (car ctl) type))
1661                       (equal (car ctl) type)))
1662               (setq result (buffer-string))))))
1663       (forward-line 1)
1664       (setq start (point)))
1665     (when (and (not result) start)
1666       (save-excursion
1667         (save-restriction
1668           (narrow-to-region start end)
1669           (when (let* ((ct (mail-fetch-field "content-type"))
1670                        (ctl (and ct (mail-header-parse-content-type ct))))
1671                   (if notp
1672                       (not (equal (car ctl) type))
1673                     (equal (car ctl) type)))
1674             (setq result (buffer-string))))))
1675     result))
1676
1677 (defvar mm-security-handle nil)
1678
1679 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1680   ;; HANDLE could be a CTL.
1681   (when handle
1682     (put-text-property 0 (length (car handle)) parameter value
1683                        (car handle))))
1684
1685 (autoload 'mm-view-pkcs7 "mm-view")
1686
1687 (defun mm-possibly-verify-or-decrypt (parts ctl &optional from)
1688   (let ((type (car ctl))
1689         (subtype (cadr (split-string (car ctl) "/")))
1690         (mm-security-handle ctl) ;; (car CTL) is the type.
1691         protocol func functest)
1692     (cond
1693      ((or (equal type "application/x-pkcs7-mime")
1694           (equal type "application/pkcs7-mime"))
1695       (with-temp-buffer
1696         (when (and (cond
1697                     ((eq mm-decrypt-option 'never) nil)
1698                     ((eq mm-decrypt-option 'always) t)
1699                     ((eq mm-decrypt-option 'known) t)
1700                     (t (y-or-n-p
1701                         (format "Decrypt (S/MIME) part? "))))
1702                    (mm-view-pkcs7 parts from))
1703           (setq parts (mm-dissect-buffer t)))))
1704      ((equal subtype "signed")
1705       (unless (and (setq protocol
1706                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1707                    (not (equal protocol "multipart/mixed")))
1708         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1709         (let ((protocols mm-verify-function-alist))
1710           (while protocols
1711             (if (and (or (not (setq functest (nth 3 (car protocols))))
1712                          (funcall functest parts ctl))
1713                      (mm-find-part-by-type parts (caar protocols) nil t))
1714                 (setq protocol (caar protocols)
1715                       protocols nil)
1716               (setq protocols (cdr protocols))))))
1717       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1718       (when (cond
1719              ((eq mm-verify-option 'never) nil)
1720              ((eq mm-verify-option 'always) t)
1721              ((eq mm-verify-option 'known)
1722               (and func
1723                    (or (not (setq functest
1724                                   (nth 3 (assoc protocol
1725                                                 mm-verify-function-alist))))
1726                        (funcall functest parts ctl))))
1727              (t
1728               (y-or-n-p
1729                (format "Verify signed (%s) part? "
1730                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1731                            (format "protocol=%s" protocol))))))
1732         (save-excursion
1733           (if func
1734               (setq parts (funcall func parts ctl))
1735             (mm-set-handle-multipart-parameter
1736              mm-security-handle 'gnus-details
1737              (format "Unknown sign protocol (%s)" protocol))))))
1738      ((equal subtype "encrypted")
1739       (unless (setq protocol
1740                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1741         ;; The message is broken.
1742         (let ((parts parts))
1743           (while parts
1744             (if (assoc (mm-handle-media-type (car parts))
1745                        mm-decrypt-function-alist)
1746                 (setq protocol (mm-handle-media-type (car parts))
1747                       parts nil)
1748               (setq parts (cdr parts))))))
1749       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1750       (when (cond
1751              ((eq mm-decrypt-option 'never) nil)
1752              ((eq mm-decrypt-option 'always) t)
1753              ((eq mm-decrypt-option 'known)
1754               (and func
1755                    (or (not (setq functest
1756                                   (nth 3 (assoc protocol
1757                                                 mm-decrypt-function-alist))))
1758                        (funcall functest parts ctl))))
1759              (t
1760               (y-or-n-p
1761                (format "Decrypt (%s) part? "
1762                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1763                            (format "protocol=%s" protocol))))))
1764         (save-excursion
1765           (if func
1766               (setq parts (funcall func parts ctl))
1767             (mm-set-handle-multipart-parameter
1768              mm-security-handle 'gnus-details
1769              (format "Unknown encrypt protocol (%s)" protocol))))))
1770      (t nil))
1771     parts))
1772
1773 (defun mm-multiple-handles (handles)
1774   (and (listp handles)
1775        (> (length handles) 1)
1776        (or (listp (car handles))
1777            (stringp (car handles)))))
1778
1779 (defun mm-complicated-handles (handles)
1780   (and (listp (car handles))
1781        (> (length handles) 1)))
1782
1783 (defun mm-merge-handles (handles1 handles2)
1784   (append
1785    (if (listp (car handles1))
1786        handles1
1787      (list handles1))
1788    (if (listp (car handles2))
1789        handles2
1790      (list handles2))))
1791
1792 (defun mm-readable-p (handle)
1793   "Say whether the content of HANDLE is readable."
1794   (and (< (with-current-buffer (mm-handle-buffer handle)
1795             (buffer-size)) 10000)
1796        (mm-with-unibyte-buffer
1797          (mm-insert-part handle)
1798          (and (eq (mm-body-7-or-8) '7bit)
1799               (not (mm-long-lines-p 76))))))
1800
1801 (declare-function libxml-parse-html-region "xml.c"
1802                   (start end &optional base-url))
1803 (declare-function shr-insert-document "shr" (dom))
1804 (defvar shr-blocked-images)
1805 (defvar gnus-inhibit-images)
1806 (autoload 'gnus-blocked-images "gnus-art")
1807
1808 (defun mm-shr (handle)
1809   ;; Require since we bind its variables.
1810   (require 'shr)
1811   (let ((article-buffer (current-buffer))
1812         (shr-content-function (lambda (id)
1813                                 (let ((handle (mm-get-content-id id)))
1814                                   (when handle
1815                                     (mm-with-part handle
1816                                       (buffer-string))))))
1817         shr-inhibit-images shr-blocked-images charset char)
1818     (if (and (boundp 'gnus-summary-buffer)
1819              (bufferp gnus-summary-buffer)
1820              (buffer-name gnus-summary-buffer))
1821         (with-current-buffer gnus-summary-buffer
1822           (setq shr-inhibit-images gnus-inhibit-images
1823                 shr-blocked-images (gnus-blocked-images)))
1824       (setq shr-inhibit-images gnus-inhibit-images
1825             shr-blocked-images (gnus-blocked-images)))
1826     (unless handle
1827       (setq handle (mm-dissect-buffer t)))
1828     (setq charset (mail-content-type-get (mm-handle-type handle) 'charset))
1829     (save-restriction
1830       (narrow-to-region (point) (point))
1831       (shr-insert-document
1832        (mm-with-part handle
1833          (insert (prog1
1834                      (if (and charset
1835                               (setq charset
1836                                     (mm-charset-to-coding-system charset
1837                                                                  nil t))
1838                               (not (eq charset 'ascii)))
1839                          (mm-decode-coding-string (buffer-string) charset)
1840                        (mm-string-as-multibyte (buffer-string)))
1841                    (erase-buffer)
1842                    (mm-enable-multibyte)))
1843          (goto-char (point-min))
1844          (setq case-fold-search t)
1845          (while (re-search-forward
1846                  "&#\\(?:x\\([89][0-9a-f]\\)\\|\\(1[2-5][0-9]\\)\\);" nil t)
1847            (when (setq char
1848                        (cdr (assq (if (match-beginning 1)
1849                                       (string-to-number (match-string 1) 16)
1850                                     (string-to-number (match-string 2)))
1851                                   mm-extra-numeric-entities)))
1852              (replace-match (char-to-string char))))
1853          ;; Remove "soft hyphens".
1854          (goto-char (point-min))
1855          (while (search-forward "­" nil t)
1856            (replace-match "" t t))
1857          (libxml-parse-html-region (point-min) (point-max))))
1858       (unless (bobp)
1859         (insert "\n"))
1860       (mm-convert-shr-links)
1861       (mm-handle-set-undisplayer
1862        handle
1863        `(lambda ()
1864           (let ((inhibit-read-only t))
1865             (delete-region ,(point-min-marker)
1866                            ,(point-max-marker))))))))
1867
1868 (defvar shr-map)
1869
1870 (autoload 'widget-convert-button "wid-edit")
1871
1872 (defun mm-convert-shr-links ()
1873   (let ((start (point-min))
1874         end)
1875     (while (and start
1876                 (< start (point-max)))
1877       (when (setq start (text-property-not-all start (point-max) 'shr-url nil))
1878         (setq end (next-single-property-change start 'shr-url nil (point-max)))
1879         (widget-convert-button
1880          'url-link start end
1881          :help-echo (get-text-property start 'help-echo)
1882          :keymap shr-map
1883          (get-text-property start 'shr-url))
1884         (put-text-property start end 'local-map nil)
1885         (setq start end)))))
1886
1887 (defun mm-handle-filename (handle)
1888   "Return filename of HANDLE if any."
1889   (or (mail-content-type-get (mm-handle-type handle)
1890                              'name)
1891       (mail-content-type-get (mm-handle-disposition handle)
1892                              'filename)))
1893
1894 (provide 'mm-decode)
1895
1896 ;; Local Variables:
1897 ;; coding: utf-8
1898 ;; End:
1899
1900 ;;; mm-decode.el ends here