*** empty log message ***
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998 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
61      (and window-system (featurep 'jpeg) (mm-image-fit-p handle)))
62     ("image/png" mm-inline-image
63      (and window-system (featurep 'png) (mm-image-fit-p handle)))
64     ("image/gif" mm-inline-image
65      (and window-system (featurep 'gif) (mm-image-fit-p handle)))
66     ("image/tiff" mm-inline-image
67      (and window-system (featurep 'tiff) (mm-image-fit-p handle)))
68     ("image/xbm" mm-inline-image
69      (and window-system (fboundp 'device-type)
70           (eq (device-type) 'x)))
71     ("image/x-xbitmap" mm-inline-image
72      (and window-system (fboundp 'device-type)
73           (eq (device-type) 'x)))
74     ("image/xpm" mm-inline-image
75      (and window-system (featurep 'xpm)))
76     ("image/x-pixmap" mm-inline-image
77      (and window-system (featurep 'xpm)))
78     ("image/bmp" mm-inline-image
79      (and window-system (featurep 'bmp)))
80     ("text/plain" mm-inline-text t)
81     ("text/enriched" mm-inline-text t)
82     ("text/richtext" mm-inline-text t)
83     ("text/html" mm-inline-text (locate-library "w3"))
84     ("message/delivery-status" mm-inline-text t)
85     ("audio/wav" mm-inline-audio
86      (and (or (featurep 'nas-sound) (featurep 'native-sound))
87           (device-sound-enabled-p)))
88     ("audio/au" mm-inline-audio
89      (and (or (featurep 'nas-sound) (featurep 'native-sound))
90           (device-sound-enabled-p)))
91     ("multipart/alternative" ignore t)
92     ("multipart/mixed" ignore t)
93     ("multipart/related" ignore t))
94   "Alist of media types/test that say whether the media types can be displayed inline.")
95
96 (defvar mm-user-display-methods
97   '(("image/.*" . inline)
98     ("text/.*" . inline)
99     ("message/delivery-status" . inline)))
100
101 (defvar mm-user-automatic-display
102   '("text/plain" "text/enriched" "text/richtext" "text/html" 
103     "image/.*" "message/delivery-status" "multipart/.*"))
104
105 (defvar mm-user-automatic-external-display nil
106   "List of MIME type regexps that will be displayed externally automatically.")
107
108 (defvar mm-alternative-precedence
109   '("multipart/related" "multipart/mixed" "multipart/alternative"
110     "image/jpeg" "image/gif" "text/html" "text/enriched"
111     "text/richtext" "text/plain")
112   "List that describes the precedence of alternative parts.")
113
114 (defvar mm-tmp-directory
115   (cond ((fboundp 'temp-directory) (temp-directory))
116         ((boundp 'temporary-file-directory) temporary-file-directory)
117         ("/tmp/"))
118   "Where mm will store its temporary files.")
119
120 (defvar mm-all-images-fit nil
121   "If non-nil, then all images fit in the buffer.")
122
123 ;;; Internal variables.
124
125 (defvar mm-dissection-list nil)
126 (defvar mm-last-shell-command "")
127 (defvar mm-content-id-alist nil)
128
129 ;;; The functions.
130
131 (defun mm-dissect-buffer (&optional no-strict-mime)
132   "Dissect the current buffer and return a list of MIME handles."
133   (save-excursion
134     (let (ct ctl type subtype cte cd description id result)
135       (save-restriction
136         (mail-narrow-to-head)
137         (when (or no-strict-mime
138                   (mail-fetch-field "mime-version"))
139           (setq ct (mail-fetch-field "content-type")
140                 ctl (condition-case () (mail-header-parse-content-type ct)
141                       (error nil))
142                 cte (mail-fetch-field "content-transfer-encoding")
143                 cd (mail-fetch-field "content-disposition")
144                 description (mail-fetch-field "content-description")
145                 id (mail-fetch-field "content-id"))))
146       (if (or (not ctl)
147               (not (string-match "/" (car ctl))))
148           (mm-dissect-singlepart
149            '("text/plain") nil no-strict-mime
150            (and cd (condition-case ()
151                        (mail-header-parse-content-disposition cd)
152                      (error nil)))
153            description)
154         (setq type (split-string (car ctl) "/"))
155         (setq subtype (cadr type)
156               type (pop type))
157         (setq
158          result
159          (cond
160           ((equal type "multipart")
161            (cons (car ctl) (mm-dissect-multipart ctl)))
162           (t
163            (mm-dissect-singlepart
164             ctl
165             (and cte (intern (downcase (mail-header-remove-whitespace
166                                         (mail-header-remove-comments
167                                          cte)))))
168             no-strict-mime
169             (and cd (condition-case ()
170                         (mail-header-parse-content-disposition cd)
171                       (error nil)))
172             description id))))
173         (when id
174           (when (string-match " *<\\(.*\\)> *" id)
175             (setq id (match-string 1 id)))
176           (push (cons id result) mm-content-id-alist))
177         result))))
178
179 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
180   (when (or force
181             (not (equal "text/plain" (car ctl))))
182     (let ((res (mm-make-handle
183                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
184       (push (car res) mm-dissection-list)
185       res)))
186
187 (defun mm-remove-all-parts ()
188   "Remove all MIME handles."
189   (interactive)
190   (mapcar 'mm-remove-part mm-dissection-list)
191   (setq mm-dissection-list nil))
192
193 (defun mm-dissect-multipart (ctl)
194   (goto-char (point-min))
195   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
196         (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
197         start parts 
198         (end (save-excursion    
199                (goto-char (point-max))
200                (if (re-search-backward close-delimiter nil t)
201                    (match-beginning 0)
202                  (point-max)))))
203     (while (search-forward boundary end t)
204       (goto-char (match-beginning 0))
205       (when start
206         (save-excursion
207           (save-restriction
208             (narrow-to-region start (point))
209             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
210       (forward-line 2)
211       (setq start (point)))
212     (when start
213       (save-excursion
214         (save-restriction
215           (narrow-to-region start end)
216           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
217     (nreverse parts)))
218
219 (defun mm-copy-to-buffer ()
220   "Copy the contents of the current buffer to a fresh buffer."
221   (save-excursion
222     (let ((obuf (current-buffer))
223           beg)
224       (goto-char (point-min))
225       (search-forward-regexp "^\n" nil t)
226       (setq beg (point))
227       (set-buffer (generate-new-buffer " *mm*"))
228       (insert-buffer-substring obuf beg)
229       (current-buffer))))
230
231 (defun mm-inlinable-part-p (type)
232   "Say whether TYPE can be displayed inline."
233   (eq (mm-user-method type) 'inline))
234
235 (defun mm-display-part (handle &optional no-default)
236   "Display the MIME part represented by HANDLE.
237 Returns nil if the part is removed; inline if displayed inline;
238 external if displayed external."
239   (save-excursion
240     (mailcap-parse-mailcaps)
241     (if (mm-handle-displayed-p handle)
242         (mm-remove-part handle)
243       (let* ((type (car (mm-handle-type handle)))
244              (method (mailcap-mime-info type))
245              (user-method (mm-user-method type)))
246         (if (eq user-method 'inline)
247             (progn
248               (forward-line 1)
249               (mm-display-inline handle)
250               'inline)
251           (when (or user-method
252                     method
253                     (not no-default))
254             (if (and (not user-method)
255                      (not method)
256                      (equal "text" (car (split-string type))))
257                 (progn
258                   (forward-line 1)
259                   (mm-insert-inline handle (mm-get-part handle))
260                   'inline)
261               (mm-display-external
262                handle (or user-method method
263                           'mailcap-save-binary-file))
264               'external)))))))
265
266 (defun mm-display-external (handle method)
267   "Display HANDLE using METHOD."
268   (mm-with-unibyte-buffer
269     (if (functionp method)
270         (let ((cur (current-buffer)))
271           (if (eq method 'mailcap-save-binary-file)
272               (progn
273                 (set-buffer (generate-new-buffer "*mm*"))
274                 (setq method nil))
275             (insert-buffer-substring (mm-handle-buffer handle))
276             (mm-decode-content-transfer-encoding
277              (mm-handle-encoding handle) (car (mm-handle-type handle)))
278             (let ((win (get-buffer-window cur t)))
279               (when win
280                 (select-window win)))
281             (switch-to-buffer (generate-new-buffer "*mm*")))
282           (buffer-disable-undo)
283           (mm-set-buffer-file-coding-system mm-binary-coding-system)
284           (insert-buffer-substring cur)
285           (message "Viewing with %s" method)
286           (let ((mm (current-buffer)))
287             (unwind-protect
288                 (if method
289                     (funcall method)
290                   (mm-save-part handle))
291               (mm-handle-set-undisplayer handle mm))))
292       ;; The function is a string to be executed.
293       (insert-buffer-substring (mm-handle-buffer handle))
294       (mm-decode-content-transfer-encoding
295        (mm-handle-encoding handle) (car (mm-handle-type handle)))
296       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
297              (filename (mail-content-type-get
298                         (mm-handle-disposition handle) 'filename))
299              (needsterm (assoc "needsterm"
300                                (mailcap-mime-info
301                                 (car (mm-handle-type handle)) t)))
302              process file)
303         ;; We create a private sub-directory where we store our files.
304         (make-directory dir)
305         (set-file-modes dir 448)
306         (if filename
307             (setq file (expand-file-name (file-name-nondirectory filename)
308                                          dir))
309           (setq file (make-temp-name (expand-file-name "mm." dir))))
310         (write-region (point-min) (point-max) file nil 'nomesg)
311         (message "Viewing with %s" method)
312         (unwind-protect
313             (setq process
314                   (if needsterm
315                       (start-process "*display*" nil
316                                      "xterm"
317                                      "-e" shell-file-name "-c"
318                                      (format method
319                                              (mm-quote-arg file)))
320                     (start-process "*display*" (generate-new-buffer "*mm*")
321                                    shell-file-name
322                                    "-c" (format method
323                                                 (mm-quote-arg file)))))
324           (mm-handle-set-undisplayer handle (cons file process)))
325         (message "Displaying %s..." (format method file))))))
326
327 (defun mm-remove-parts (handles)
328   "Remove the displayed MIME parts represented by HANDLE."
329   (if (and (listp handles)
330            (bufferp (car handles)))
331       (mm-remove-part handles)
332     (let (handle)
333       (while (setq handle (pop handles))
334         (cond
335          ((stringp handle)
336           )
337          ((and (listp handle)
338                (stringp (car handle)))
339           (mm-remove-parts (cdr handle)))
340          (t
341           (mm-remove-part handle)))))))
342
343 (defun mm-destroy-parts (handles)
344   "Remove the displayed MIME parts represented by HANDLE."
345   (if (and (listp handles)
346            (bufferp (car handles)))
347       (mm-destroy-part handles)
348     (let (handle)
349       (while (setq handle (pop handles))
350         (cond
351          ((stringp handle)
352           )
353          ((and (listp handle)
354                (stringp (car handle)))
355           (mm-destroy-parts (cdr handle)))
356          (t
357           (mm-destroy-part handle)))))))
358
359 (defun mm-remove-part (handle)
360   "Remove the displayed MIME part represented by HANDLE."
361   (when (listp handle)
362     (let ((object (mm-handle-undisplayer handle)))
363       (condition-case ()
364           (cond
365            ;; Internally displayed part.
366            ((mm-annotationp object)
367             (delete-annotation object))
368            ((or (functionp object)
369                 (and (listp object)
370                      (eq (car object) 'lambda)))
371             (funcall object))
372            ;; Externally displayed part.
373            ((consp object)
374             (condition-case ()
375                 (delete-file (car object))
376               (error nil))
377             (condition-case ()
378                 (delete-directory (file-name-directory (car object)))
379               (error nil))
380             (condition-case ()
381                 (kill-process (cdr object))
382               (error nil)))
383            ((bufferp object)
384             (when (buffer-live-p object)
385               (kill-buffer object))))
386         (error nil))
387       (mm-handle-set-undisplayer handle nil))))
388
389 (defun mm-display-inline (handle)
390   (let* ((type (car (mm-handle-type handle)))
391          (function (cadr (assoc type mm-inline-media-tests))))
392     (funcall function handle)
393     (goto-char (point-min))))
394
395 (defun mm-inlinable-p (type)
396   "Say whether TYPE can be displayed inline."
397   (let ((alist mm-inline-media-tests)
398         test)
399     (while alist
400       (when (equal type (caar alist))
401         (setq test (caddar alist)
402               alist nil)
403         (setq test (eval test)))
404       (pop alist))
405     test))
406
407 (defun mm-user-method (type)
408   "Return the user-defined method for TYPE."
409   (let ((methods mm-user-display-methods)
410         method result)
411     (while (setq method (pop methods))
412       (when (string-match (car method) type)
413         (when (or (not (eq (cdr method) 'inline))
414                   (mm-inlinable-p type))
415           (setq result (cdr method)
416                 methods nil))))
417     result))
418
419 (defun mm-automatic-display-p (type)
420   "Return the user-defined method for TYPE."
421   (let ((methods mm-user-automatic-display)
422         method result)
423     (while (setq method (pop methods))
424       (when (and (string-match method type)
425                  (mm-inlinable-p type))
426         (setq result t
427               methods nil)))
428     result))
429
430 (defun mm-automatic-external-display-p (type)
431   "Return the user-defined method for TYPE."
432   (let ((methods mm-user-automatic-external-display)
433         method result)
434     (while (setq method (pop methods))
435       (when (string-match method type)
436         (setq result t
437               methods nil)))
438     result))
439
440 (defun add-mime-display-method (type method)
441   "Make parts of TYPE be displayed with METHOD.
442 This overrides entries in the mailcap file."
443   (push (cons type method) mm-user-display-methods))
444
445 (defun mm-destroy-part (handle)
446   "Destroy the data structures connected to HANDLE."
447   (when (listp handle)
448     (mm-remove-part handle)
449     (when (buffer-live-p (mm-handle-buffer handle))
450       (kill-buffer (mm-handle-buffer handle)))))
451
452 (defun mm-handle-displayed-p (handle)
453   "Say whether HANDLE is displayed or not."
454   (mm-handle-undisplayer handle))
455   
456 (defun mm-quote-arg (arg)
457   "Return a version of ARG that is safe to evaluate in a shell."
458   (let ((pos 0) new-pos accum)
459     ;; *** bug: we don't handle newline characters properly
460     (while (setq new-pos (string-match "[;!`\"$\\& \t{} |()<>]" arg pos))
461       (push (substring arg pos new-pos) accum)
462       (push "\\" accum)
463       (push (list (aref arg new-pos)) accum)
464       (setq pos (1+ new-pos)))
465     (if (= pos 0)
466         arg
467       (apply 'concat (nconc (nreverse accum) (list (substring arg pos)))))))
468
469 ;;;
470 ;;; Functions for outputting parts
471 ;;;
472
473 (defun mm-get-part (handle)
474   "Return the contents of HANDLE as a string."
475   (mm-with-unibyte-buffer
476     (insert-buffer-substring (mm-handle-buffer handle))
477     (mm-decode-content-transfer-encoding
478      (mm-handle-encoding handle)
479      (car (mm-handle-type handle)))
480     (buffer-string)))
481
482 (defvar mm-default-directory nil)
483
484 (defun mm-save-part (handle)
485   "Write HANDLE to a file."
486   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
487          (filename (mail-content-type-get
488                     (mm-handle-disposition handle) 'filename))
489          file)
490     (when filename
491       (setq filename (file-name-nondirectory filename)))
492     (setq file
493           (read-file-name "Save MIME part to: "
494                           (expand-file-name
495                            (or filename name "")
496                            (or mm-default-directory default-directory))))
497     (setq mm-default-directory (file-name-directory file))
498     (mm-with-unibyte-buffer
499       (insert-buffer-substring (mm-handle-buffer handle))
500       (mm-decode-content-transfer-encoding
501        (mm-handle-encoding handle)
502        (car (mm-handle-type handle)))
503       (when (or (not (file-exists-p file))
504                 (yes-or-no-p (format "File %s already exists; overwrite? "
505                                      file)))
506         ;; Now every coding system is 100% binary within mm-with-unibyte-buffer
507         ;; Is text still special?
508       (let ((coding-system-for-write
509              (if (equal "text" (car (split-string
510                                      (car (mm-handle-type handle)) "/")))
511                  buffer-file-coding-system
512                'binary)))
513         (write-region (point-min) (point-max) file))))))
514
515 (defun mm-pipe-part (handle)
516   "Pipe HANDLE to a process."
517   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
518          (command
519           (read-string "Shell command on MIME part: " mm-last-shell-command)))
520     (mm-with-unibyte-buffer
521       (insert-buffer-substring (mm-handle-buffer handle))
522       (mm-decode-content-transfer-encoding
523        (mm-handle-encoding handle)
524        (car (mm-handle-type handle)))
525       (shell-command-on-region (point-min) (point-max) command nil))))
526
527 (defun mm-interactively-view-part (handle)
528   "Display HANDLE using METHOD."
529   (let* ((type (car (mm-handle-type handle)))
530          (methods
531           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
532                   (mailcap-mime-info type 'all)))
533          (method (completing-read "Viewer: " methods)))
534     (mm-display-external (copy-sequence handle) method)))
535
536 (defun mm-preferred-alternative (handles &optional preferred)
537   "Say which of HANDLES are preferred."
538   (let ((prec (if preferred (list preferred) mm-alternative-precedence))
539         p h result type handle)
540     (while (setq p (pop prec))
541       (setq h handles)
542       (while h
543         (setq type
544               (if (stringp (caar h))
545                   (caar h)
546                 (car (mm-handle-type (car h)))))
547         (setq handle (car h))
548         (when (and (equal p type)
549                    (mm-automatic-display-p type)
550                    (or (stringp (caar h))
551                        (not (mm-handle-disposition (car h)))
552                        (equal (car (mm-handle-disposition (car h)))
553                               "inline")))
554           (setq result (car h)
555                 h nil
556                 prec nil))
557         (pop h)))
558     result))
559
560 (defun mm-get-content-id (id)
561   "Return the handle(s) referred to by ID."
562   (cdr (assoc id mm-content-id-alist)))
563
564 (defun mm-get-image (handle)
565   "Return an image instance based on HANDLE."
566   (let ((type (cadr (split-string (car (mm-handle-type handle)) "/")))
567         spec)
568     ;; Allow some common translations.
569     (setq type
570           (cond
571            ((equal type "x-pixmap")
572             "xpm")
573            ((equal type "x-xbitmap")
574             "xbm")
575            (t type)))
576     (or (mm-handle-cache handle)
577         (mm-with-unibyte-buffer
578           (insert-buffer-substring (mm-handle-buffer handle))
579           (mm-decode-content-transfer-encoding
580            (mm-handle-encoding handle)
581            (car (mm-handle-type handle)))
582           (prog1
583               (setq spec
584                     (make-glyph `[,(intern type) :data ,(buffer-string)]))
585             (mm-handle-set-cache handle spec))))))
586
587 (defun mm-image-fit-p (handle)
588   "Say whether the image in HANDLE will fit the current window."
589   (let ((image (mm-get-image handle)))
590     (or mm-all-images-fit
591         (and (< (glyph-width image) (window-pixel-width))
592              (< (glyph-height image) (window-pixel-height))))))
593
594 (provide 'mm-decode)
595
596 ;; mm-decode.el ends here