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