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