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