(nnimap-open-connection): Give an error if nnimap-stream is unknown.
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 ;; For Emacs < 22.2.
28 (eval-and-compile
29   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
30
31 (require 'mail-parse)
32 (require '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) 'mm-shr)
109         ((executable-find "w3m") 'gnus-article-html)
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 `gnus-article-html' : use Gnus renderer based on w3m;
119 `w3m'  : use emacs-w3m;
120 `w3m-standalone': use w3m;
121 `links': use links;
122 `lynx' : use lynx;
123 `w3'   : use Emacs/W3;
124 `html2text' : use html2text;
125 nil    : use external viewer (default web browser)."
126   :version "24.1"
127   :type '(choice (const gnus-article-html)
128                  (const w3)
129                  (const w3m :tag "emacs-w3m")
130                  (const w3m-standalone :tag "standalone w3m" )
131                  (const links)
132                  (const lynx)
133                  (const html2text)
134                  (const nil :tag "External viewer")
135                  (function))
136   :group 'mime-display)
137
138 (defvar mm-inline-text-html-renderer nil
139   "Function used for rendering inline HTML contents.
140 It is suggested to customize `mm-text-html-renderer' instead.")
141
142 (defcustom mm-inline-text-html-with-images nil
143   "If non-nil, Gnus will allow retrieving images in HTML contents with
144 the <img> tags.  It has no effect on Emacs/w3.  See also the
145 documentation for the `mm-w3m-safe-url-regexp' variable."
146   :version "22.1"
147   :type 'boolean
148   :group 'mime-display)
149
150 (defcustom mm-w3m-safe-url-regexp "\\`cid:"
151   "Regexp matching URLs which are considered to be safe.
152 Some HTML mails might contain a nasty trick used by spammers, using
153 the <img> tag which is far more evil than the [Click Here!] button.
154 It is most likely intended to check whether the ominous spam mail has
155 reached your eyes or not, in which case the spammer knows for sure
156 that your email address is valid.  It is done by embedding an
157 identifier string into a URL that you might automatically retrieve
158 when displaying the image.  The default value is \"\\\\`cid:\" which only
159 matches parts embedded to the Multipart/Related type MIME contents and
160 Gnus will never connect to the spammer's site arbitrarily.  You may
161 set this variable to nil if you consider all urls to be safe."
162   :version "22.1"
163   :type '(choice (regexp :tag "Regexp")
164                  (const :tag "All URLs are safe" nil))
165   :group 'mime-display)
166
167 (defcustom mm-inline-text-html-with-w3m-keymap t
168   "If non-nil, use emacs-w3m command keys in the article buffer."
169   :version "22.1"
170   :type 'boolean
171   :group 'mime-display)
172
173 (defcustom mm-enable-external t
174   "Indicate whether external MIME handlers should be used.
175
176 If t, all defined external MIME handlers are used.  If nil, files are saved by
177 `mailcap-save-binary-file'.  If it is the symbol `ask', you are prompted
178 before the external MIME handler is invoked."
179   :version "22.1"
180   :type '(choice (const :tag "Always" t)
181                  (const :tag "Never" nil)
182                  (const :tag "Ask" ask))
183   :group 'mime-display)
184
185 (defcustom mm-inline-media-tests
186   '(("image/p?jpeg"
187      mm-inline-image
188      (lambda (handle)
189        (mm-valid-and-fit-image-p 'jpeg handle)))
190     ("image/png"
191      mm-inline-image
192      (lambda (handle)
193        (mm-valid-and-fit-image-p 'png handle)))
194     ("image/gif"
195      mm-inline-image
196      (lambda (handle)
197        (mm-valid-and-fit-image-p 'gif handle)))
198     ("image/tiff"
199      mm-inline-image
200      (lambda (handle)
201        (mm-valid-and-fit-image-p 'tiff handle)) )
202     ("image/xbm"
203      mm-inline-image
204      (lambda (handle)
205        (mm-valid-and-fit-image-p 'xbm handle)))
206     ("image/x-xbitmap"
207      mm-inline-image
208      (lambda (handle)
209        (mm-valid-and-fit-image-p 'xbm handle)))
210     ("image/xpm"
211      mm-inline-image
212      (lambda (handle)
213        (mm-valid-and-fit-image-p 'xpm handle)))
214     ("image/x-xpixmap"
215      mm-inline-image
216      (lambda (handle)
217        (mm-valid-and-fit-image-p 'xpm handle)))
218     ("image/bmp"
219      mm-inline-image
220      (lambda (handle)
221        (mm-valid-and-fit-image-p 'bmp handle)))
222     ("image/x-portable-bitmap"
223      mm-inline-image
224      (lambda (handle)
225        (mm-valid-and-fit-image-p 'pbm handle)))
226     ("text/plain" mm-inline-text identity)
227     ("text/enriched" mm-inline-text identity)
228     ("text/richtext" mm-inline-text identity)
229     ("text/x-patch" mm-display-patch-inline
230      (lambda (handle)
231        ;; If the diff-mode.el package is installed, the function is
232        ;; autoloaded.  Checking (locate-library "diff-mode") would be trying
233        ;; to cater to broken installations.  OTOH checking the function
234        ;; makes it possible to install another package which provides an
235        ;; alternative implementation of diff-mode.  --Stef
236        (fboundp 'diff-mode)))
237     ;; In case mime.types uses x-diff (as does Debian's mime-support-3.40).
238     ("text/x-diff" mm-display-patch-inline
239      (lambda (handle) (fboundp 'diff-mode)))
240     ("application/emacs-lisp" mm-display-elisp-inline identity)
241     ("application/x-emacs-lisp" mm-display-elisp-inline identity)
242     ("text/dns" mm-display-dns-inline identity)
243     ("text/html"
244      mm-inline-text-html
245      (lambda (handle)
246        (or mm-inline-text-html-renderer
247            mm-text-html-renderer)))
248     ("text/x-vcard"
249      mm-inline-text-vcard
250      (lambda (handle)
251        (or (featurep 'vcard)
252            (locate-library "vcard"))))
253     ("message/delivery-status" mm-inline-text identity)
254     ("message/rfc822" mm-inline-message identity)
255     ("message/partial" mm-inline-partial identity)
256     ("message/external-body" mm-inline-external-body identity)
257     ("text/.*" mm-inline-text identity)
258     ("audio/wav" mm-inline-audio
259      (lambda (handle)
260        (and (or (featurep 'nas-sound) (featurep 'native-sound))
261             (device-sound-enabled-p))))
262     ("audio/au"
263      mm-inline-audio
264      (lambda (handle)
265        (and (or (featurep 'nas-sound) (featurep 'native-sound))
266             (device-sound-enabled-p))))
267     ("application/pgp-signature" ignore identity)
268     ("application/x-pkcs7-signature" ignore identity)
269     ("application/pkcs7-signature" ignore identity)
270     ("application/x-pkcs7-mime" ignore identity)
271     ("application/pkcs7-mime" ignore identity)
272     ("multipart/alternative" ignore identity)
273     ("multipart/mixed" ignore identity)
274     ("multipart/related" ignore identity)
275     ;; Disable audio and image
276     ("audio/.*" ignore ignore)
277     ("image/.*" ignore ignore)
278     ;; Default to displaying as text
279     (".*" mm-inline-text mm-readable-p))
280   "Alist of media types/tests saying whether types can be displayed inline."
281   :type '(repeat (list (regexp :tag "MIME type")
282                        (function :tag "Display function")
283                        (function :tag "Display test")))
284   :group 'mime-display)
285
286 (defcustom mm-inlined-types
287   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
288     "message/partial" "message/external-body" "application/emacs-lisp"
289     "application/x-emacs-lisp"
290     "application/pgp-signature" "application/x-pkcs7-signature"
291     "application/pkcs7-signature" "application/x-pkcs7-mime"
292     "application/pkcs7-mime"
293     ;; Mutt still uses this even though it has already been withdrawn.
294     "application/pgp")
295   "List of media types that are to be displayed inline.
296 See also `mm-inline-media-tests', which says how to display a media
297 type inline."
298   :type '(repeat regexp)
299   :group 'mime-display)
300
301 (defcustom mm-keep-viewer-alive-types
302   '("application/postscript" "application/msword" "application/vnd.ms-excel"
303     "application/pdf" "application/x-dvi")
304   "List of media types for which the external viewer will not be killed
305 when selecting a different article."
306   :version "22.1"
307   :type '(repeat regexp)
308   :group 'mime-display)
309
310 (defcustom mm-automatic-display
311   '("text/plain" "text/enriched" "text/richtext" "text/html" "text/x-verbatim"
312     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
313     "message/rfc822" "text/x-patch" "text/dns" "application/pgp-signature"
314     "application/emacs-lisp" "application/x-emacs-lisp"
315     "application/x-pkcs7-signature"
316     "application/pkcs7-signature" "application/x-pkcs7-mime"
317     "application/pkcs7-mime"
318     ;; Mutt still uses this even though it has already been withdrawn.
319     "application/pgp\\'")
320   "A list of MIME types to be displayed automatically."
321   :type '(repeat regexp)
322   :group 'mime-display)
323
324 (defcustom mm-attachment-override-types '("text/x-vcard"
325                                           "application/pkcs7-mime"
326                                           "application/x-pkcs7-mime"
327                                           "application/pkcs7-signature"
328                                           "application/x-pkcs7-signature")
329   "Types to have \"attachment\" ignored if they can be displayed inline."
330   :type '(repeat regexp)
331   :group 'mime-display)
332
333 (defcustom mm-inline-override-types nil
334   "Types to be treated as attachments even if they can be displayed inline."
335   :type '(repeat regexp)
336   :group 'mime-display)
337
338 (defcustom mm-automatic-external-display nil
339   "List of MIME type regexps that will be displayed externally automatically."
340   :type '(repeat regexp)
341   :group 'mime-display)
342
343 (defcustom mm-discouraged-alternatives nil
344   "List of MIME types that are discouraged when viewing multipart/alternative.
345 Viewing agents are supposed to view the last possible part of a message,
346 as that is supposed to be the richest.  However, users may prefer other
347 types instead, and this list says what types are most unwanted.  If,
348 for instance, text/html parts are very unwanted, and text/richtext are
349 somewhat unwanted, then the value of this variable should be set
350 to:
351
352  (\"text/html\" \"text/richtext\")
353
354 Adding \"image/.*\" might also be useful.  Spammers use it as the
355 prefered part of multipart/alternative messages.  See also
356 `gnus-buttonized-mime-types', to which adding \"multipart/alternative\"
357 enables you to choose manually one of two types those mails include."
358   :type '(repeat regexp) ;; See `mm-preferred-alternative-precedence'.
359   :group 'mime-display)
360
361 (defcustom mm-tmp-directory
362   (if (fboundp 'temp-directory)
363       (temp-directory)
364     (if (boundp 'temporary-file-directory)
365         temporary-file-directory
366       "/tmp/"))
367   "Where mm will store its temporary files."
368   :type 'directory
369   :group 'mime-display)
370
371 (defcustom mm-inline-large-images nil
372   "If t, then all images fit in the buffer.
373 If 'resize, try to resize the images so they fit."
374   :type '(radio
375           (const :tag "Inline large images as they are." t)
376           (const :tag "Resize large images." resize)
377           (const :tag "Do not inline large images." nil))
378   :group 'mime-display)
379
380 (defcustom mm-file-name-rewrite-functions
381   '(mm-file-name-delete-control mm-file-name-delete-gotchas)
382   "List of functions used for rewriting file names of MIME parts.
383 Each function takes a file name as input and returns a file name.
384
385 Ready-made functions include `mm-file-name-delete-control',
386 `mm-file-name-delete-gotchas' (you should not remove these two
387 functions), `mm-file-name-delete-whitespace',
388 `mm-file-name-trim-whitespace', `mm-file-name-collapse-whitespace',
389 `mm-file-name-replace-whitespace', `capitalize', `downcase',
390 `upcase', and `upcase-initials'."
391   :type '(list (set :inline t
392                     (const mm-file-name-delete-control)
393                     (const mm-file-name-delete-gotchas)
394                     (const mm-file-name-delete-whitespace)
395                     (const mm-file-name-trim-whitespace)
396                     (const mm-file-name-collapse-whitespace)
397                     (const mm-file-name-replace-whitespace)
398                     (const capitalize)
399                     (const downcase)
400                     (const upcase)
401                     (const upcase-initials)
402                (repeat :inline t
403                        :tag "Function"
404                        function)))
405   :version "23.1" ;; No Gnus
406   :group 'mime-display)
407
408
409 (defvar mm-path-name-rewrite-functions nil
410   "*List of functions for rewriting the full file names of MIME parts.
411 This is used when viewing parts externally, and is meant for
412 transforming the absolute name so that non-compliant programs can find
413 the file where it's saved.
414
415 Each function takes a file name as input and returns a file name.")
416
417 (defvar mm-file-name-replace-whitespace nil
418   "String used for replacing whitespace characters; default is `\"_\"'.")
419
420 (defcustom mm-default-directory nil
421   "The default directory where mm will save files.
422 If not set, `default-directory' will be used."
423   :type '(choice directory (const :tag "Default" nil))
424   :group 'mime-display)
425
426 (defcustom mm-attachment-file-modes 384
427   "Set the mode bits of saved attachments to this integer."
428   :version "22.1"
429   :type 'integer
430   :group 'mime-display)
431
432 (defcustom mm-external-terminal-program "xterm"
433   "The program to start an external terminal."
434   :version "22.1"
435   :type 'string
436   :group 'mime-display)
437
438 ;;; Internal variables.
439
440 (defvar mm-last-shell-command "")
441 (defvar mm-content-id-alist nil)
442 (defvar mm-postponed-undisplay-list nil)
443
444 ;; According to RFC2046, in particular, in a digest, the default
445 ;; Content-Type value for a body part is changed from "text/plain" to
446 ;; "message/rfc822".
447 (defvar mm-dissect-default-type "text/plain")
448
449 (autoload 'mml2015-verify "mml2015")
450 (autoload 'mml2015-verify-test "mml2015")
451 (autoload 'mml-smime-verify "mml-smime")
452 (autoload 'mml-smime-verify-test "mml-smime")
453
454 (defvar mm-verify-function-alist
455   '(("application/pgp-signature" mml2015-verify "PGP" mml2015-verify-test)
456     ("application/x-gnus-pgp-signature" mm-uu-pgp-signed-extract-1 "PGP"
457      mm-uu-pgp-signed-test)
458     ("application/pkcs7-signature" mml-smime-verify "S/MIME"
459      mml-smime-verify-test)
460     ("application/x-pkcs7-signature" mml-smime-verify "S/MIME"
461      mml-smime-verify-test)))
462
463 (defcustom mm-verify-option 'never
464   "Option of verifying signed parts.
465 `never', not verify; `always', always verify;
466 `known', only verify known protocols.  Otherwise, ask user.
467
468 When set to `always' or `known', you should add
469 \"multipart/signed\" to `gnus-buttonized-mime-types' to see
470 result of the verification."
471   :version "22.1"
472   :type '(choice (item always)
473                  (item never)
474                  (item :tag "only known protocols" known)
475                  (item :tag "ask" nil))
476   :group 'mime-security)
477
478 (autoload 'mml2015-decrypt "mml2015")
479 (autoload 'mml2015-decrypt-test "mml2015")
480
481 (defvar mm-decrypt-function-alist
482   '(("application/pgp-encrypted" mml2015-decrypt "PGP" mml2015-decrypt-test)
483     ("application/x-gnus-pgp-encrypted" mm-uu-pgp-encrypted-extract-1 "PGP"
484      mm-uu-pgp-encrypted-test)))
485
486 (defcustom mm-decrypt-option nil
487   "Option of decrypting encrypted parts.
488 `never', not decrypt; `always', always decrypt;
489 `known', only decrypt known protocols.  Otherwise, ask user."
490   :version "22.1"
491   :type '(choice (item always)
492                  (item never)
493                  (item :tag "only known protocols" known)
494                  (item :tag "ask" nil))
495   :group 'mime-security)
496
497 (defvar mm-viewer-completion-map
498   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
499     (set-keymap-parent map minibuffer-local-completion-map)
500     ;; Should we bind other key to minibuffer-complete-word?
501     (define-key map " " 'self-insert-command)
502     map)
503   "Keymap for input viewer with completion.")
504
505 (defvar mm-viewer-completion-map
506   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
507     (set-keymap-parent map minibuffer-local-completion-map)
508     ;; Should we bind other key to minibuffer-complete-word?
509     (define-key map " " 'self-insert-command)
510     map)
511   "Keymap for input viewer with completion.")
512
513 ;;; The functions.
514
515 (defun mm-alist-to-plist (alist)
516   "Convert association list ALIST into the equivalent property-list form.
517 The plist is returned.  This converts from
518
519 \((a . 1) (b . 2) (c . 3))
520
521 into
522
523 \(a 1 b 2 c 3)
524
525 The original alist is not modified.  See also `destructive-alist-to-plist'."
526   (let (plist)
527     (while alist
528       (let ((el (car alist)))
529         (setq plist (cons (cdr el) (cons (car el) plist))))
530       (setq alist (cdr alist)))
531     (nreverse plist)))
532
533 (defun mm-keep-viewer-alive-p (handle)
534   "Say whether external viewer for HANDLE should stay alive."
535   (let ((types mm-keep-viewer-alive-types)
536         (type (mm-handle-media-type handle))
537         ty)
538     (catch 'found
539       (while (setq ty (pop types))
540         (when (string-match ty type)
541           (throw 'found t))))))
542
543 (defun mm-handle-set-external-undisplayer (handle function)
544   "Set the undisplayer for HANDLE to FUNCTION.
545 Postpone undisplaying of viewers for types in
546 `mm-keep-viewer-alive-types'."
547   (if (mm-keep-viewer-alive-p handle)
548       (let ((new-handle (copy-sequence handle)))
549         (mm-handle-set-undisplayer new-handle function)
550         (mm-handle-set-undisplayer handle nil)
551         (push new-handle mm-postponed-undisplay-list))
552     (mm-handle-set-undisplayer handle function)))
553
554 (defun mm-destroy-postponed-undisplay-list ()
555   (when mm-postponed-undisplay-list
556     (message "Destroying external MIME viewers")
557     (mm-destroy-parts mm-postponed-undisplay-list)))
558
559 (autoload 'message-fetch-field "message")
560
561 (defun mm-dissect-buffer (&optional no-strict-mime loose-mime from)
562   "Dissect the current buffer and return a list of MIME handles."
563   (save-excursion
564     (let (ct ctl type subtype cte cd description id result)
565       (save-restriction
566         (mail-narrow-to-head)
567         (when (or no-strict-mime
568                   loose-mime
569                   (mail-fetch-field "mime-version"))
570           (setq ct (mail-fetch-field "content-type")
571                 ctl (and ct (mail-header-parse-content-type ct))
572                 cte (mail-fetch-field "content-transfer-encoding")
573                 cd (mail-fetch-field "content-disposition")
574                 ;; Newlines in description should be stripped so as
575                 ;; not to break the MIME tag into two or more lines.
576                 description (message-fetch-field "content-description")
577                 id (mail-fetch-field "content-id"))
578           (unless from
579             (setq from (mail-fetch-field "from")))
580           ;; FIXME: In some circumstances, this code is running within
581           ;; an unibyte macro.  mail-extract-address-components
582           ;; creates unibyte buffers. This `if', though not a perfect
583           ;; solution, avoids most of them.
584           (if from
585               (setq from (cadr (mail-extract-address-components from))))
586           (if description
587               (setq description (mail-decode-encoded-word-string
588                                  description)))))
589       (if (or (not ctl)
590               (not (string-match "/" (car ctl))))
591           (mm-dissect-singlepart
592            (list mm-dissect-default-type)
593            (and cte (intern (downcase (mail-header-strip cte))))
594            no-strict-mime
595            (and cd (mail-header-parse-content-disposition cd))
596            description)
597         (setq type (split-string (car ctl) "/"))
598         (setq subtype (cadr type)
599               type (car type))
600         (setq
601          result
602          (cond
603           ((equal type "multipart")
604            (let ((mm-dissect-default-type (if (equal subtype "digest")
605                                               "message/rfc822"
606                                             "text/plain"))
607                  (start (cdr (assq 'start (cdr ctl)))))
608              (add-text-properties 0 (length (car ctl))
609                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
610
611              ;; what really needs to be done here is a way to link a
612              ;; MIME handle back to it's parent MIME handle (in a multilevel
613              ;; MIME article).  That would probably require changing
614              ;; the mm-handle API so we simply store the multipart buffer
615              ;; name as a text property of the "multipart/whatever" string.
616              (add-text-properties 0 (length (car ctl))
617                                   (list 'buffer (mm-copy-to-buffer)
618                                         'from from
619                                         'start start)
620                                   (car ctl))
621              (cons (car ctl) (mm-dissect-multipart ctl from))))
622           (t
623            (mm-possibly-verify-or-decrypt
624             (mm-dissect-singlepart
625              ctl
626              (and cte (intern (downcase (mail-header-strip cte))))
627              no-strict-mime
628              (and cd (mail-header-parse-content-disposition cd))
629              description id)
630             ctl))))
631         (when id
632           (when (string-match " *<\\(.*\\)> *" id)
633             (setq id (match-string 1 id)))
634           (push (cons id result) mm-content-id-alist))
635         result))))
636
637 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
638   (when (or force
639             (if (equal "text/plain" (car ctl))
640                 (assoc 'format ctl)
641               t))
642     (mm-make-handle
643      (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
644
645 (defun mm-dissect-multipart (ctl from)
646   (goto-char (point-min))
647   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
648          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
649          start parts
650          (end (save-excursion
651                 (goto-char (point-max))
652                 (if (re-search-backward close-delimiter nil t)
653                     (match-beginning 0)
654                   (point-max)))))
655     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
656     (while (and (< (point) end) (re-search-forward boundary end t))
657       (goto-char (match-beginning 0))
658       (when start
659         (save-excursion
660           (save-restriction
661             (narrow-to-region start (point))
662             (setq parts (nconc (list (mm-dissect-buffer t nil from)) parts)))))
663       (end-of-line 2)
664       (or (looking-at boundary)
665           (forward-line 1))
666       (setq start (point)))
667     (when (and start (< start end))
668       (save-excursion
669         (save-restriction
670           (narrow-to-region start end)
671           (setq parts (nconc (list (mm-dissect-buffer t nil from)) parts)))))
672     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
673
674 (defun mm-copy-to-buffer ()
675   "Copy the contents of the current buffer to a fresh buffer."
676   (let ((obuf (current-buffer))
677         (mb (mm-multibyte-p))
678         beg)
679     (goto-char (point-min))
680     (search-forward-regexp "^\n" nil t)
681     (setq beg (point))
682     (with-current-buffer
683           (generate-new-buffer " *mm*")
684       ;; Preserve the data's unibyteness (for url-insert-file-contents).
685       (mm-set-buffer-multibyte mb)
686       (insert-buffer-substring obuf beg)
687       (current-buffer))))
688
689 (defun mm-display-parts (handle &optional no-default)
690   (if (stringp (car handle))
691       (mapcar 'mm-display-parts (cdr handle))
692     (if (bufferp (car handle))
693         (save-restriction
694           (narrow-to-region (point) (point))
695           (mm-display-part handle)
696           (goto-char (point-max)))
697       (mapcar 'mm-display-parts handle))))
698
699 (autoload 'mailcap-parse-mailcaps "mailcap")
700 (autoload 'mailcap-mime-info "mailcap")
701
702 (defun mm-display-part (handle &optional no-default)
703   "Display the MIME part represented by HANDLE.
704 Returns nil if the part is removed; inline if displayed inline;
705 external if displayed external."
706   (save-excursion
707     (mailcap-parse-mailcaps)
708     (if (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 (or prompt
1257                               (format "Save MIME part to (default %s): "
1258                                       (or filename "")))
1259                           (or mm-default-directory default-directory)
1260                           (or filename "")))
1261     (when (file-directory-p file)
1262       (setq file (expand-file-name filename file)))
1263     (setq mm-default-directory (file-name-directory file))
1264     (and (or (not (file-exists-p file))
1265              (yes-or-no-p (format "File %s already exists; overwrite? "
1266                                   file)))
1267          (progn
1268            (mm-save-part-to-file handle file)
1269            file))))
1270
1271 (defun mm-add-meta-html-tag (handle &optional charset force-charset)
1272   "Add meta html tag to specify CHARSET of HANDLE in the current buffer.
1273 CHARSET defaults to the one HANDLE specifies.  Existing meta tag that
1274 specifies charset will not be modified unless FORCE-CHARSET is non-nil.
1275 Return t if meta tag is added or replaced."
1276   (when (equal (mm-handle-media-type handle) "text/html")
1277     (when (or charset
1278               (setq charset (mail-content-type-get (mm-handle-type handle)
1279                                                    'charset)))
1280       (setq charset (format "\
1281 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">" charset))
1282       (let ((case-fold-search t))
1283         (goto-char (point-min))
1284         (if (re-search-forward "\
1285 <meta\\s-+http-equiv=[\"']?content-type[\"']?\\s-+content=[\"']\
1286 text/\\(\\sw+\\)\\(?:\;\\s-*charset=\\(.+\\)\\)?[\"'][^>]*>" nil t)
1287             (if (and (not force-charset)
1288                      (match-beginning 2)
1289                      (string-match "\\`html\\'" (match-string 1)))
1290                 ;; Don't modify existing meta tag.
1291                 nil
1292               ;; Replace it with the one specifying charset.
1293               (replace-match charset)
1294               t)
1295           (if (re-search-forward "<head>\\s-*" nil t)
1296               (insert charset "\n")
1297             (re-search-forward "<html\\(?:\\s-+[^>]+\\|\\s-*\\)>\\s-*" nil t)
1298             (insert "<head>\n" charset "\n</head>\n"))
1299           t)))))
1300
1301 (defun mm-save-part-to-file (handle file)
1302   (mm-with-unibyte-buffer
1303     (mm-insert-part handle)
1304     (mm-add-meta-html-tag handle)
1305     (let ((current-file-modes (default-file-modes)))
1306       (set-default-file-modes mm-attachment-file-modes)
1307       (unwind-protect
1308           ;; Don't re-compress .gz & al.  Arguably we should make
1309           ;; `file-name-handler-alist' nil, but that would chop
1310           ;; ange-ftp, which is reasonable to use here.
1311           (mm-write-region (point-min) (point-max) file nil nil nil 'binary t)
1312         (set-default-file-modes current-file-modes)))))
1313
1314 (defun mm-pipe-part (handle &optional cmd)
1315   "Pipe HANDLE to a process.
1316 Use CMD as the process."
1317   (let ((name (mail-content-type-get (mm-handle-type handle) 'name))
1318         (command (or cmd
1319                      (gnus-read-shell-command
1320                       "Shell command on MIME part: " mm-last-shell-command))))
1321     (mm-with-unibyte-buffer
1322       (mm-insert-part handle)
1323       (mm-add-meta-html-tag handle)
1324       (let ((coding-system-for-write 'binary))
1325         (shell-command-on-region (point-min) (point-max) command nil)))))
1326
1327 (defun mm-interactively-view-part (handle)
1328   "Display HANDLE using METHOD."
1329   (let* ((type (mm-handle-media-type handle))
1330          (methods
1331           (mapcar (lambda (i) (cdr (assoc 'viewer i)))
1332                   (mailcap-mime-info type 'all)))
1333          (method (let ((minibuffer-local-completion-map
1334                         mm-viewer-completion-map))
1335                    (gnus-completing-read "Viewer" methods))))
1336     (when (string= method "")
1337       (error "No method given"))
1338     (if (string-match "^[^% \t]+$" method)
1339         (setq method (concat method " %s")))
1340     (mm-display-external handle method)))
1341
1342 (defun mm-preferred-alternative (handles &optional preferred)
1343   "Say which of HANDLES are preferred."
1344   (let ((prec (if preferred (list preferred)
1345                 (mm-preferred-alternative-precedence handles)))
1346         p h result type handle)
1347     (while (setq p (pop prec))
1348       (setq h handles)
1349       (while h
1350         (setq handle (car h))
1351         (setq type (mm-handle-media-type handle))
1352         (when (and (equal p type)
1353                    (mm-automatic-display-p handle)
1354                    (or (stringp (car handle))
1355                        (not (mm-handle-disposition handle))
1356                        (equal (car (mm-handle-disposition handle))
1357                               "inline")))
1358           (setq result handle
1359                 h nil
1360                 prec nil))
1361         (pop h)))
1362     result))
1363
1364 (defun mm-preferred-alternative-precedence (handles)
1365   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1366   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1367                                handles))))
1368     (dolist (disc (reverse mm-discouraged-alternatives))
1369       (dolist (elem (copy-sequence seq))
1370         (when (string-match disc elem)
1371           (setq seq (nconc (delete elem seq) (list elem))))))
1372     seq))
1373
1374 (defun mm-get-content-id (id)
1375   "Return the handle(s) referred to by ID."
1376   (cdr (assoc id mm-content-id-alist)))
1377
1378 (defconst mm-image-type-regexps
1379   '(("/\\*.*XPM.\\*/" . xpm)
1380     ("P[1-6]" . pbm)
1381     ("GIF8" . gif)
1382     ("\377\330" . jpeg)
1383     ("\211PNG\r\n" . png)
1384     ("#define" . xbm)
1385     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1386     ("%!PS" . postscript))
1387   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1388 When the first bytes of an image file match REGEXP, it is assumed to
1389 be of image type IMAGE-TYPE.")
1390
1391 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1392 (defun mm-image-type-from-buffer ()
1393   "Determine the image type from data in the current buffer.
1394 Value is a symbol specifying the image type or nil if type cannot
1395 be determined."
1396   (let ((types mm-image-type-regexps)
1397         type)
1398     (goto-char (point-min))
1399     (while (and types (null type))
1400       (let ((regexp (car (car types)))
1401             (image-type (cdr (car types))))
1402         (when (looking-at regexp)
1403           (setq type image-type))
1404         (setq types (cdr types))))
1405     type))
1406
1407 (defun mm-get-image (handle)
1408   "Return an image instance based on HANDLE."
1409   (let ((type (mm-handle-media-subtype handle))
1410         spec)
1411     ;; Allow some common translations.
1412     (setq type
1413           (cond
1414            ((equal type "x-pixmap")
1415             "xpm")
1416            ((equal type "x-xbitmap")
1417             "xbm")
1418            ((equal type "x-portable-bitmap")
1419             "pbm")
1420            (t type)))
1421     (or (mm-handle-cache handle)
1422         (mm-with-unibyte-buffer
1423           (mm-insert-part handle)
1424           (prog1
1425               (setq spec
1426                     (ignore-errors
1427                       ;; Avoid testing `make-glyph' since W3 may define
1428                       ;; a bogus version of it.
1429                       (if (fboundp 'create-image)
1430                           (create-image (buffer-string)
1431                                         (or (mm-image-type-from-buffer)
1432                                             (intern type))
1433                                         'data-p)
1434                         (mm-create-image-xemacs type))))
1435             (mm-handle-set-cache handle spec))))))
1436
1437 (defun mm-create-image-xemacs (type)
1438   (when (featurep 'xemacs)
1439     (cond
1440      ((equal type "xbm")
1441       ;; xbm images require special handling, since
1442       ;; the only way to create glyphs from these
1443       ;; (without a ton of work) is to write them
1444       ;; out to a file, and then create a file
1445       ;; specifier.
1446       (let ((file (mm-make-temp-file
1447                    (expand-file-name "emm" mm-tmp-directory)
1448                    nil ".xbm")))
1449         (unwind-protect
1450             (progn
1451               (write-region (point-min) (point-max) file)
1452               (make-glyph (list (cons 'x file))))
1453           (ignore-errors
1454             (delete-file file)))))
1455      (t
1456       (make-glyph
1457        (vector
1458         (or (mm-image-type-from-buffer)
1459             (intern type))
1460         :data (buffer-string)))))))
1461
1462 (declare-function image-size "image.c" (spec &optional pixels frame))
1463
1464 (defun mm-image-fit-p (handle)
1465   "Say whether the image in HANDLE will fit the current window."
1466   (let ((image (mm-get-image handle)))
1467     (or (not image)
1468         (if (featurep 'xemacs)
1469             ;; XEmacs' glyphs can actually tell us about their width, so
1470             ;; lets be nice and smart about them.
1471             (or mm-inline-large-images
1472                 (and (<= (glyph-width image) (window-pixel-width))
1473                      (<= (glyph-height image) (window-pixel-height))))
1474           (let* ((size (image-size image))
1475                  (w (car size))
1476                  (h (cdr size)))
1477             (or mm-inline-large-images
1478                 (and (<= h (1- (window-height))) ; Don't include mode line.
1479                      (<= w (window-width)))))))))
1480
1481 (defun mm-valid-image-format-p (format)
1482   "Say whether FORMAT can be displayed natively by Emacs."
1483   (cond
1484    ;; Handle XEmacs
1485    ((fboundp 'valid-image-instantiator-format-p)
1486     (valid-image-instantiator-format-p format))
1487    ;; Handle Emacs
1488    ((fboundp 'image-type-available-p)
1489     (and (display-graphic-p)
1490          (image-type-available-p format)))
1491    ;; Nobody else can do images yet.
1492    (t
1493     nil)))
1494
1495 (defun mm-valid-and-fit-image-p (format handle)
1496   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1497   (and (mm-valid-image-format-p format)
1498        (mm-image-fit-p handle)))
1499
1500 (defun mm-find-part-by-type (handles type &optional notp recursive)
1501   "Search in HANDLES for part with TYPE.
1502 If NOTP, returns first non-matching part.
1503 If RECURSIVE, search recursively."
1504   (let (handle)
1505     (while handles
1506       (if (and recursive (stringp (caar handles)))
1507           (if (setq handle (mm-find-part-by-type (cdar handles) type
1508                                                  notp recursive))
1509               (setq handles nil))
1510         (if (if notp
1511                 (not (equal (mm-handle-media-type (car handles)) type))
1512               (equal (mm-handle-media-type (car handles)) type))
1513             (setq handle (car handles)
1514                   handles nil)))
1515       (setq handles (cdr handles)))
1516     handle))
1517
1518 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1519   (goto-char (point-min))
1520   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1521                                                                    'boundary)))
1522          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1523          start
1524          (end (save-excursion
1525                 (goto-char (point-max))
1526                 (if (re-search-backward close-delimiter nil t)
1527                     (match-beginning 0)
1528                   (point-max))))
1529          result)
1530     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1531     (while (and (not result)
1532                 (re-search-forward boundary end t))
1533       (goto-char (match-beginning 0))
1534       (when start
1535         (save-excursion
1536           (save-restriction
1537             (narrow-to-region start (1- (point)))
1538             (when (let* ((ct (mail-fetch-field "content-type"))
1539                          (ctl (and ct (mail-header-parse-content-type ct))))
1540                     (if notp
1541                         (not (equal (car ctl) type))
1542                       (equal (car ctl) type)))
1543               (setq result (buffer-string))))))
1544       (forward-line 1)
1545       (setq start (point)))
1546     (when (and (not result) start)
1547       (save-excursion
1548         (save-restriction
1549           (narrow-to-region start end)
1550           (when (let* ((ct (mail-fetch-field "content-type"))
1551                        (ctl (and ct (mail-header-parse-content-type ct))))
1552                   (if notp
1553                       (not (equal (car ctl) type))
1554                     (equal (car ctl) type)))
1555             (setq result (buffer-string))))))
1556     result))
1557
1558 (defvar mm-security-handle nil)
1559
1560 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1561   ;; HANDLE could be a CTL.
1562   (when handle
1563     (put-text-property 0 (length (car handle)) parameter value
1564                        (car handle))))
1565
1566 (autoload 'mm-view-pkcs7 "mm-view")
1567
1568 (defun mm-possibly-verify-or-decrypt (parts ctl)
1569   (let ((type (car ctl))
1570         (subtype (cadr (split-string (car ctl) "/")))
1571         (mm-security-handle ctl) ;; (car CTL) is the type.
1572         protocol func functest)
1573     (cond
1574      ((or (equal type "application/x-pkcs7-mime")
1575           (equal type "application/pkcs7-mime"))
1576       (with-temp-buffer
1577         (when (and (cond
1578                     ((eq mm-decrypt-option 'never) nil)
1579                     ((eq mm-decrypt-option 'always) t)
1580                     ((eq mm-decrypt-option 'known) t)
1581                     (t (y-or-n-p
1582                         (format "Decrypt (S/MIME) part? "))))
1583                    (mm-view-pkcs7 parts))
1584           (setq parts (mm-dissect-buffer t)))))
1585      ((equal subtype "signed")
1586       (unless (and (setq protocol
1587                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1588                    (not (equal protocol "multipart/mixed")))
1589         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1590         (let ((protocols mm-verify-function-alist))
1591           (while protocols
1592             (if (and (or (not (setq functest (nth 3 (car protocols))))
1593                          (funcall functest parts ctl))
1594                      (mm-find-part-by-type parts (caar protocols) nil t))
1595                 (setq protocol (caar protocols)
1596                       protocols nil)
1597               (setq protocols (cdr protocols))))))
1598       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1599       (when (cond
1600              ((eq mm-verify-option 'never) nil)
1601              ((eq mm-verify-option 'always) t)
1602              ((eq mm-verify-option 'known)
1603               (and func
1604                    (or (not (setq functest
1605                                   (nth 3 (assoc protocol
1606                                                 mm-verify-function-alist))))
1607                        (funcall functest parts ctl))))
1608              (t
1609               (y-or-n-p
1610                (format "Verify signed (%s) part? "
1611                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1612                            (format "protocol=%s" protocol))))))
1613         (save-excursion
1614           (if func
1615               (setq parts (funcall func parts ctl))
1616             (mm-set-handle-multipart-parameter
1617              mm-security-handle 'gnus-details
1618              (format "Unknown sign protocol (%s)" protocol))))))
1619      ((equal subtype "encrypted")
1620       (unless (setq protocol
1621                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1622         ;; The message is broken.
1623         (let ((parts parts))
1624           (while parts
1625             (if (assoc (mm-handle-media-type (car parts))
1626                        mm-decrypt-function-alist)
1627                 (setq protocol (mm-handle-media-type (car parts))
1628                       parts nil)
1629               (setq parts (cdr parts))))))
1630       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1631       (when (cond
1632              ((eq mm-decrypt-option 'never) nil)
1633              ((eq mm-decrypt-option 'always) t)
1634              ((eq mm-decrypt-option 'known)
1635               (and func
1636                    (or (not (setq functest
1637                                   (nth 3 (assoc protocol
1638                                                 mm-decrypt-function-alist))))
1639                        (funcall functest parts ctl))))
1640              (t
1641               (y-or-n-p
1642                (format "Decrypt (%s) part? "
1643                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1644                            (format "protocol=%s" protocol))))))
1645         (save-excursion
1646           (if func
1647               (setq parts (funcall func parts ctl))
1648             (mm-set-handle-multipart-parameter
1649              mm-security-handle 'gnus-details
1650              (format "Unknown encrypt protocol (%s)" protocol))))))
1651      (t nil))
1652     parts))
1653
1654 (defun mm-multiple-handles (handles)
1655   (and (listp handles)
1656        (> (length handles) 1)
1657        (or (listp (car handles))
1658            (stringp (car handles)))))
1659
1660 (defun mm-complicated-handles (handles)
1661   (and (listp (car handles))
1662        (> (length handles) 1)))
1663
1664 (defun mm-merge-handles (handles1 handles2)
1665   (append
1666    (if (listp (car handles1))
1667        handles1
1668      (list handles1))
1669    (if (listp (car handles2))
1670        handles2
1671      (list handles2))))
1672
1673 (defun mm-readable-p (handle)
1674   "Say whether the content of HANDLE is readable."
1675   (and (< (with-current-buffer (mm-handle-buffer handle)
1676             (buffer-size)) 10000)
1677        (mm-with-unibyte-buffer
1678          (mm-insert-part handle)
1679          (and (eq (mm-body-7-or-8) '7bit)
1680               (not (mm-long-lines-p 76))))))
1681
1682 (defun mm-shr (handle)
1683   (let ((article-buffer (current-buffer)))
1684     (unless handle
1685       (setq handle (mm-dissect-buffer t)))
1686     (save-restriction
1687       (narrow-to-region (point) (point))
1688       (shr-insert-document
1689        (mm-with-part handle
1690          (libxml-parse-html-region (point-min) (point-max)))))))
1691
1692 (provide 'mm-decode)
1693
1694 ;;; mm-decode.el ends here