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