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