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