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