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