Importing Pterodactyl Gnus v0.91.
[elisp/gnus.git-] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30
31 ;;; Convenience macros.
32
33 (defmacro mm-handle-buffer (handle)
34   `(nth 0 ,handle))
35 (defmacro mm-handle-type (handle)
36   `(nth 1 ,handle))
37 (defmacro mm-handle-encoding (handle)
38   `(nth 2 ,handle))
39 (defmacro mm-handle-undisplayer (handle)
40   `(nth 3 ,handle))
41 (defmacro mm-handle-set-undisplayer (handle function)
42   `(setcar (nthcdr 3 ,handle) ,function))
43 (defmacro mm-handle-disposition (handle)
44   `(nth 4 ,handle))
45 (defmacro mm-handle-description (handle)
46   `(nth 5 ,handle))
47 (defmacro mm-handle-cache (handle)
48   `(nth 6 ,handle))
49 (defmacro mm-handle-set-cache (handle contents)
50   `(setcar (nthcdr 6 ,handle) ,contents))
51 (defmacro mm-handle-id (handle)
52   `(nth 7 ,handle))
53 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
54                                     disposition description cache
55                                     id)
56   `(list ,buffer ,type ,encoding ,undisplayer
57          ,disposition ,description ,cache ,id))
58
59 (defvar mm-inline-media-tests
60   '(("image/jpeg" mm-inline-image (mm-valid-and-fit-image-p 'jpeg handle))
61     ("image/png" mm-inline-image (mm-valid-and-fit-image-p 'png handle))
62     ("image/gif" mm-inline-image (mm-valid-and-fit-image-p 'gif handle))
63     ("image/tiff" mm-inline-image (mm-valid-and-fit-image-p 'tiff handle)) 
64     ("image/xbm" mm-inline-image (mm-valid-and-fit-image-p 'xbm handle))
65     ("image/x-xbitmap" mm-inline-image (mm-valid-and-fit-image-p 'xbm handle))
66     ("image/xpm" mm-inline-image (mm-valid-and-fit-image-p 'xpm handle))
67     ("image/x-pixmap" mm-inline-image (mm-valid-and-fit-image-p 'xpm handle))
68     ("image/bmp" mm-inline-image (mm-valid-and-fit-image-p 'bmp handle))
69     ("text/plain" mm-inline-text t)
70     ("text/enriched" mm-inline-text t)
71     ("text/richtext" mm-inline-text t)
72     ("text/html" mm-inline-text (locate-library "w3"))
73     ("text/x-vcard" mm-inline-text (locate-library "vcard"))
74     ("message/delivery-status" mm-inline-text t)
75     ("message/rfc822" mm-inline-message t)
76     ("text/.*" mm-inline-text t)
77     ("audio/wav" mm-inline-audio
78      (and (or (featurep 'nas-sound) (featurep 'native-sound))
79           (device-sound-enabled-p)))
80     ("audio/au" mm-inline-audio
81      (and (or (featurep 'nas-sound) (featurep 'native-sound))
82           (device-sound-enabled-p)))
83     ("multipart/alternative" ignore t)
84     ("multipart/mixed" ignore t)
85     ("multipart/related" ignore t))
86   "Alist of media types/test that say whether the media types can be displayed inline.")
87
88 (defvar mm-inlined-types
89   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822")
90   "List of media types that are to be displayed inline.")
91   
92 (defvar mm-automatic-display
93   '("text/plain" "text/enriched" "text/richtext" "text/html"
94     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
95     "message/rfc822")
96   "A list of MIME types to be displayed automatically.")
97
98 (defvar mm-attachment-override-types
99   '("text/plain" "text/x-vcard")
100   "Types that should have \"attachment\" ignored if they can be displayed inline.")
101
102 (defvar mm-automatic-external-display nil
103   "List of MIME type regexps that will be displayed externally automatically.")
104
105 (defvar mm-discouraged-alternatives nil
106   "List of MIME types that are discouraged when viewing multipart/alternative.
107 Viewing agents are supposed to view the last possible part of a message,
108 as that is supposed to be the richest.  However, users may prefer other
109 types instead, and this list says what types are most unwanted.  If,
110 for instance, text/html parts are very unwanted, and text/richtech are
111 somewhat unwanted, then the value of this variable should be set
112 to:
113
114  (\"text/html\" \"text/richtext\")")
115
116 (defvar mm-tmp-directory
117   (cond ((fboundp 'temp-directory) (temp-directory))
118         ((boundp 'temporary-file-directory) temporary-file-directory)
119         ("/tmp/"))
120   "Where mm will store its temporary files.")
121
122 (defvar mm-all-images-fit nil
123   "If non-nil, then all images fit in the buffer.")
124
125 ;;; Internal variables.
126
127 (defvar mm-dissection-list nil)
128 (defvar mm-last-shell-command "")
129 (defvar mm-content-id-alist nil)
130
131 ;;; The functions.
132
133 (defun mm-dissect-buffer (&optional no-strict-mime)
134   "Dissect the current buffer and return a list of MIME handles."
135   (save-excursion
136     (let (ct ctl type subtype cte cd description id result)
137       (save-restriction
138         (mail-narrow-to-head)
139         (when (or no-strict-mime
140                   (mail-fetch-field "mime-version"))
141           (setq ct (mail-fetch-field "content-type")
142                 ctl (ignore-errors (mail-header-parse-content-type ct))
143                 cte (mail-fetch-field "content-transfer-encoding")
144                 cd (mail-fetch-field "content-disposition")
145                 description (mail-fetch-field "content-description")
146                 id (mail-fetch-field "content-id"))))
147       (if (or (not ctl)
148               (not (string-match "/" (car ctl))))
149           (mm-dissect-singlepart
150            '("text/plain") nil no-strict-mime
151            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
152            description)
153         (setq type (split-string (car ctl) "/"))
154         (setq subtype (cadr type)
155               type (pop type))
156         (setq
157          result
158          (cond
159           ((equal type "multipart")
160            (cons (car ctl) (mm-dissect-multipart ctl)))
161           (t
162            (mm-dissect-singlepart
163             ctl
164             (and cte (intern (downcase (mail-header-remove-whitespace
165                                         (mail-header-remove-comments
166                                          cte)))))
167             no-strict-mime
168             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
169             description id))))
170         (when id
171           (when (string-match " *<\\(.*\\)> *" id)
172             (setq id (match-string 1 id)))
173           (push (cons id result) mm-content-id-alist))
174         result))))
175
176 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
177   (when (or force
178             (not (equal "text/plain" (car ctl))))
179     (let ((res (mm-make-handle
180                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
181       (push (car res) mm-dissection-list)
182       res)))
183
184 (defun mm-remove-all-parts ()
185   "Remove all MIME handles."
186   (interactive)
187   (mapcar 'mm-remove-part mm-dissection-list)
188   (setq mm-dissection-list nil))
189
190 (defun mm-dissect-multipart (ctl)
191   (goto-char (point-min))
192   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
193         (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
194         start parts
195         (end (save-excursion
196                (goto-char (point-max))
197                (if (re-search-backward close-delimiter nil t)
198                    (match-beginning 0)
199                  (point-max)))))
200     (while (search-forward boundary end t)
201       (goto-char (match-beginning 0))
202       (when start
203         (save-excursion
204           (save-restriction
205             (narrow-to-region start (point))
206             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
207       (forward-line 2)
208       (setq start (point)))
209     (when start
210       (save-excursion
211         (save-restriction
212           (narrow-to-region start end)
213           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
214     (nreverse parts)))
215
216 (defun mm-copy-to-buffer ()
217   "Copy the contents of the current buffer to a fresh buffer."
218   (save-excursion
219     (let ((obuf (current-buffer))
220           beg)
221       (goto-char (point-min))
222       (search-forward-regexp "^\n" nil t)
223       (setq beg (point))
224       (set-buffer (generate-new-buffer " *mm*"))
225       (insert-buffer-substring obuf beg)
226       (current-buffer))))
227
228 (defun mm-display-part (handle &optional no-default)
229   "Display the MIME part represented by HANDLE.
230 Returns nil if the part is removed; inline if displayed inline;
231 external if displayed external."
232   (save-excursion
233     (mailcap-parse-mailcaps)
234     (if (mm-handle-displayed-p handle)
235         (mm-remove-part handle)
236       (let* ((type (car (mm-handle-type handle)))
237              (method (mailcap-mime-info type)))
238         (if (mm-inlined-p type)
239             (progn
240               (forward-line 1)
241               (mm-display-inline handle)
242               'inline)
243           (when (or method
244                     (not no-default))
245             (if (and (not method)
246                      (equal "text" (car (split-string type))))
247                 (progn
248                   (forward-line 1)
249                   (mm-insert-inline handle (mm-get-part handle))
250                   'inline)
251               (mm-display-external
252                handle (or method 'mailcap-save-binary-file))
253               'external)))))))
254
255 (defun mm-display-external (handle method)
256   "Display HANDLE using METHOD."
257   (mm-with-unibyte-buffer
258     (if (functionp method)
259         (let ((cur (current-buffer)))
260           (if (eq method 'mailcap-save-binary-file)
261               (progn
262                 (set-buffer (generate-new-buffer "*mm*"))
263                 (setq method nil))
264             (mm-insert-part handle)
265             (let ((win (get-buffer-window cur t)))
266               (when win
267                 (select-window win)))
268             (switch-to-buffer (generate-new-buffer "*mm*")))
269           (buffer-disable-undo)
270           (mm-set-buffer-file-coding-system mm-binary-coding-system)
271           (insert-buffer-substring cur)
272           (message "Viewing with %s" method)
273           (let ((mm (current-buffer))
274                 (non-viewer (assoc "non-viewer"
275                                    (mailcap-mime-info
276                                     (car (mm-handle-type handle)) t))))
277             (unwind-protect
278                 (if method
279                     (funcall method)
280                   (mm-save-part handle))
281               (when (and (not non-viewer)
282                          method)
283                 (mm-handle-set-undisplayer handle mm)))))
284       ;; The function is a string to be executed.
285       (mm-insert-part handle)
286       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
287              (filename (mail-content-type-get
288                         (mm-handle-disposition handle) 'filename))
289              (needsterm (assoc "needsterm"
290                                (mailcap-mime-info
291                                 (car (mm-handle-type handle)) t)))
292              process file buffer)
293         ;; We create a private sub-directory where we store our files.
294         (make-directory dir)
295         (set-file-modes dir 448)
296         (if filename
297             (setq file (expand-file-name (file-name-nondirectory filename)
298                                          dir))
299           (setq file (make-temp-name (expand-file-name "mm." dir))))
300         (write-region (point-min) (point-max) file nil 'nomesg)
301         (message "Viewing with %s" method)
302         (unwind-protect
303             (setq process
304                   (if needsterm
305                       (start-process "*display*" nil
306                                      "xterm"
307                                      "-e" shell-file-name "-c"
308                                      (format method
309                                              (mm-quote-arg file)))
310                     (start-process "*display*"
311                                    (setq buffer (generate-new-buffer "*mm*"))
312                                    shell-file-name
313                                    "-c" (format method
314                                                 (mm-quote-arg file)))))
315           (mm-handle-set-undisplayer handle (cons file buffer)))
316         (message "Displaying %s..." (format method file))))))
317
318 (defun mm-remove-parts (handles)
319   "Remove the displayed MIME parts represented by HANDLE."
320   (if (and (listp handles)
321            (bufferp (car handles)))
322       (mm-remove-part handles)
323     (let (handle)
324       (while (setq handle (pop handles))
325         (cond
326          ((stringp handle)
327           )
328          ((and (listp handle)
329                (stringp (car handle)))
330           (mm-remove-parts (cdr handle)))
331          (t
332           (mm-remove-part handle)))))))
333
334 (defun mm-destroy-parts (handles)
335   "Remove the displayed MIME parts represented by HANDLE."
336   (if (and (listp handles)
337            (bufferp (car handles)))
338       (mm-destroy-part handles)
339     (let (handle)
340       (while (setq handle (pop handles))
341         (cond
342          ((stringp handle)
343           )
344          ((and (listp handle)
345                (stringp (car handle)))
346           (mm-destroy-parts (cdr handle)))
347          (t
348           (mm-destroy-part handle)))))))
349
350 (defun mm-remove-part (handle)
351   "Remove the displayed MIME part represented by HANDLE."
352   (when (listp handle)
353     (let ((object (mm-handle-undisplayer handle)))
354       (ignore-errors
355         (cond
356          ;; Internally displayed part.
357          ((mm-annotationp object)
358           (delete-annotation object))
359          ((or (functionp object)
360               (and (listp object)
361                    (eq (car object) 'lambda)))
362           (funcall object))
363          ;; Externally displayed part.
364          ((consp object)
365           (ignore-errors (delete-file (car object)))
366           (ignore-errors (delete-directory (file-name-directory (car object))))
367           (ignore-errors (kill-buffer (cdr object))))
368          ((bufferp object)
369           (when (buffer-live-p object)
370             (kill-buffer object)))))
371       (mm-handle-set-undisplayer handle nil))))
372
373 (defun mm-display-inline (handle)
374   (let* ((type (car (mm-handle-type handle)))
375          (function (cadr (assoc type mm-inline-media-tests))))
376     (funcall function handle)
377     (goto-char (point-min))))
378
379 (defun mm-inlinable-p (type)
380   "Say whether TYPE can be displayed inline."
381   (let ((alist mm-inline-media-tests)
382         test)
383     (while alist
384       (when (equal type (caar alist))
385         (setq test (caddar alist)
386               alist nil)
387         (setq test (eval test)))
388       (pop alist))
389     test))
390
391 (defun mm-automatic-display-p (type)
392   "Say whether the user wants TYPE to be displayed automatically."
393   (let ((methods mm-automatic-display)
394         method result)
395     (while (setq method (pop methods))
396       (when (and (string-match method type)
397                  (mm-inlinable-p type))
398         (setq result t
399               methods nil)))
400     result))
401
402 (defun mm-inlined-p (type)
403   "Say whether the user wants TYPE to be displayed automatically."
404   (let ((methods mm-inlined-types)
405         method result)
406     (while (setq method (pop methods))
407       (when (and (string-match method type)
408                  (mm-inlinable-p type))
409         (setq result t
410               methods nil)))
411     result))
412
413 (defun mm-attachment-override-p (type)
414   "Say whether TYPE should have attachment behavior overridden."
415   (let ((types mm-attachment-override-types)
416         ty)
417     (catch 'found
418       (while (setq ty (pop types))
419         (when (and (string-match ty type)
420                    (mm-inlinable-p type))
421           (throw 'found t))))))
422
423 (defun mm-automatic-external-display-p (type)
424   "Return the user-defined method for TYPE."
425   (let ((methods mm-automatic-external-display)
426         method result)
427     (while (setq method (pop methods))
428       (when (string-match method type)
429         (setq result t
430               methods nil)))
431     result))
432
433 (defun mm-destroy-part (handle)
434   "Destroy the data structures connected to HANDLE."
435   (when (listp handle)
436     (mm-remove-part handle)
437     (when (buffer-live-p (mm-handle-buffer handle))
438       (kill-buffer (mm-handle-buffer handle)))))
439
440 (defun mm-handle-displayed-p (handle)
441   "Say whether HANDLE is displayed or not."
442   (mm-handle-undisplayer handle))
443
444 ;;;
445 ;;; Functions for outputting parts
446 ;;;
447
448 (defun mm-get-part (handle)
449   "Return the contents of HANDLE as a string."
450   (mm-with-unibyte-buffer
451     (mm-insert-part handle)
452     (buffer-string)))
453
454 (defun mm-insert-part (handle)
455   "Insert the contents of HANDLE in the current buffer."
456   (let ((cur (current-buffer)))
457     (save-excursion
458       (if (member (car (split-string (car (mm-handle-type handle)) "/"))
459                   '("text" "message"))
460           (with-temp-buffer
461             (insert-buffer-substring (mm-handle-buffer handle))
462             (mm-decode-content-transfer-encoding
463              (mm-handle-encoding handle)
464              (car (mm-handle-type handle)))
465             (let ((temp (current-buffer)))
466               (set-buffer cur)
467               (insert-buffer-substring temp)))
468         (mm-with-unibyte-buffer
469           (insert-buffer-substring (mm-handle-buffer handle))
470           (mm-decode-content-transfer-encoding
471            (mm-handle-encoding handle)
472            (car (mm-handle-type handle)))
473           (let ((temp (current-buffer)))
474             (set-buffer cur)
475             (insert-buffer-substring temp)))))))
476
477 (defvar mm-default-directory nil)
478
479 (defun mm-save-part (handle)
480   "Write HANDLE to a file."
481   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
482          (filename (mail-content-type-get
483                     (mm-handle-disposition handle) 'filename))
484          file)
485     (when filename
486       (setq filename (file-name-nondirectory filename)))
487     (setq file
488           (read-file-name "Save MIME part to: "
489                           (expand-file-name
490                            (or filename name "")
491                            (or mm-default-directory default-directory))))
492     (setq mm-default-directory (file-name-directory file))
493     (when (or (not (file-exists-p file))
494               (yes-or-no-p (format "File %s already exists; overwrite? "
495                                    file)))
496       (mm-save-part-to-file handle file))))
497
498 (defun mm-save-part-to-file (handle file)
499   (mm-with-unibyte-buffer
500     (mm-insert-part handle)
501     ;; Now every coding system is 100% binary within mm-with-unibyte-buffer
502     ;; Is text still special?
503     (let ((coding-system-for-write
504            (if (equal "text" (car (split-string
505                                    (car (mm-handle-type handle)) "/")))
506                buffer-file-coding-system
507              'binary))
508           ;; Don't re-compress .gz & al.  Arguably we should make
509           ;; `file-name-handler-alist' nil, but that would chop
510           ;; ange-ftp which it's reasonable to use here.
511           (inhibit-file-name-operation 'write-region)
512           (inhibit-file-name-handlers
513            (if (equal (car (mm-handle-type handle))
514                       "application/octet-stream")
515                (cons 'jka-compr-handler inhibit-file-name-handlers)
516              inhibit-file-name-handlers)))
517       (write-region (point-min) (point-max) file))))
518
519 (defun mm-pipe-part (handle)
520   "Pipe HANDLE to a process."
521   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
522          (command
523           (read-string "Shell command on MIME part: " mm-last-shell-command)))
524     (mm-with-unibyte-buffer
525       (mm-insert-part handle)
526       (shell-command-on-region (point-min) (point-max) command nil))))
527
528 (defun mm-interactively-view-part (handle)
529   "Display HANDLE using METHOD."
530   (let* ((type (car (mm-handle-type handle)))
531          (methods
532           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
533                   (mailcap-mime-info type 'all)))
534          (method (completing-read "Viewer: " methods)))
535     (mm-display-external (copy-sequence handle) method)))
536
537 (defun mm-preferred-alternative (handles &optional preferred)
538   "Say which of HANDLES are preferred."
539   (let ((prec (if preferred (list preferred)
540                 (mm-preferred-alternative-precedence handles)))
541         p h result type handle)
542     (while (setq p (pop prec))
543       (setq h handles)
544       (while h
545         (setq type
546               (if (stringp (caar h))
547                   (caar h)
548                 (car (mm-handle-type (car h)))))
549         (setq handle (car h))
550         (when (and (equal p type)
551                    (mm-automatic-display-p type)
552                    (or (stringp (caar h))
553                        (not (mm-handle-disposition (car h)))
554                        (equal (car (mm-handle-disposition (car h)))
555                               "inline")))
556           (setq result (car h)
557                 h nil
558                 prec nil))
559         (pop h)))
560     result))
561
562 (defun mm-preferred-alternative-precedence (handles)
563   "Return the precedence based on HANDLES and mm-discouraged-alternatives."
564   (let ((seq (nreverse (mapcar (lambda (h)
565                                  (car (mm-handle-type h))) handles))))
566     (dolist (disc (reverse mm-discouraged-alternatives))
567       (dolist (elem (copy-sequence seq))
568         (when (string-match disc elem)
569           (setq seq (nconc (delete elem seq) (list elem))))))
570     seq))
571
572 (defun mm-get-content-id (id)
573   "Return the handle(s) referred to by ID."
574   (cdr (assoc id mm-content-id-alist)))
575
576 (defun mm-get-image (handle)
577   "Return an image instance based on HANDLE."
578   (let ((type (cadr (split-string (car (mm-handle-type handle)) "/")))
579         spec)
580     ;; Allow some common translations.
581     (setq type
582           (cond
583            ((equal type "x-pixmap")
584             "xpm")
585            ((equal type "x-xbitmap")
586             "xbm")
587            (t type)))
588     (or (mm-handle-cache handle)
589         (mm-with-unibyte-buffer
590           (mm-insert-part handle)
591           (prog1
592               (setq spec
593                     (ignore-errors
594                       (cond
595                        ((equal type "xbm")
596                         ;; xbm images require special handling, since
597                         ;; the only way to create glyphs from these
598                         ;; (without a ton of work) is to write them
599                         ;; out to a file, and then create a file
600                         ;; specifier.
601                         (let ((file (make-temp-name
602                                      (expand-file-name "emm.xbm"
603                                                        mm-tmp-directory))))
604                           (unwind-protect
605                               (progn
606                                 (write-region (point-min) (point-max) file)
607                                 (make-glyph (list (cons 'x file))))
608                             (ignore-errors
609                               (delete-file file)))))
610                        (t
611                         (make-glyph
612                          (vector (intern type) :data (buffer-string)))))))
613             (mm-handle-set-cache handle spec))))))
614
615 (defun mm-image-fit-p (handle)
616   "Say whether the image in HANDLE will fit the current window."
617   (let ((image (mm-get-image handle)))
618     (or mm-all-images-fit
619         (and (< (glyph-width image) (window-pixel-width))
620              (< (glyph-height image) (window-pixel-height))))))
621
622 (defun mm-valid-image-format-p (format)
623   "Say whether FORMAT can be displayed natively by Emacs."
624   (and (fboundp 'valid-image-instantiator-format-p)
625        (valid-image-instantiator-format-p format)))
626
627 (defun mm-valid-and-fit-image-p (format handle)
628   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
629   (and window-system
630        (mm-valid-image-format-p format)
631        (mm-image-fit-p handle)))
632
633 (provide 'mm-decode)
634
635 ;; mm-decode.el ends here