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