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