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