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