*** 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 (defvar mm-inline-media-tests
32   '(("image/jpeg" mm-inline-image (featurep 'jpeg))
33     ("image/png" mm-inline-image (featurep 'png))
34     ("image/gif" mm-inline-image (featurep 'gif))
35     ("image/tiff" mm-inline-image (featurep 'tiff))
36     ("image/xbm" mm-inline-image (eq (device-type) 'x))
37     ("image/xpm" mm-inline-image (featurep 'xpm))
38     ("image/bmp" mm-inline-image (featurep 'bmp))
39     ("text/plain" mm-inline-text t)
40     ("text/enriched" mm-inline-text t)
41     ("text/richtext" mm-inline-text t)
42     ("text/html" mm-inline-text (featurep 'w3))
43     ("message/delivery-status" mm-inline-text t)
44     ("audio/wav" mm-inline-audio
45      (and (or (featurep 'nas-sound) (featurep 'native-sound))
46           (device-sound-enabled-p)))
47     ("audio/au" mm-inline-audio
48      (and (or (featurep 'nas-sound) (featurep 'native-sound))
49           (device-sound-enabled-p))))
50   "Alist of media types/test that say whether the media types can be displayed inline.")
51
52 (defvar mm-user-display-methods
53   '(("image/.*" . inline)
54     ("text/.*" . inline)))
55
56 (defvar mm-user-automatic-display
57   '("text/plain" "text/enriched" "text/richtext" "text/html" "image/gif"))
58
59 (defvar mm-alternative-precedence
60   '("text/plain" "text/enriched" "text/richtext" "text/html")
61   "List that describes the precedence of alternative parts.")
62
63 (defvar mm-tmp-directory "/tmp/"
64   "Where mm will store its temporary files.")
65
66 ;;; Internal variables.
67
68 (defvar mm-dissection-list nil)
69 (defvar mm-last-shell-command "")
70 (defvar mm-content-id-alist nil)
71
72 ;;; Convenience macros.
73
74 (defmacro mm-handle-buffer (handle)
75   `(nth 0 ,handle))
76 (defmacro mm-handle-type (handle)
77   `(nth 1 ,handle))
78 (defmacro mm-handle-encoding (handle)
79   `(nth 2 ,handle))
80 (defmacro mm-handle-undisplayer (handle)
81   `(nth 3 ,handle))
82 (defmacro mm-handle-set-undisplayer (handle function)
83   `(setcar (nthcdr 3 ,handle) ,function))
84 (defmacro mm-handle-disposition (handle)
85   `(nth 4 ,handle))
86 (defmacro mm-handle-description (handle)
87   `(nth 5 ,handle))
88
89 ;;; The functions.
90
91 (defun mm-dissect-buffer (&optional no-strict-mime)
92   "Dissect the current buffer and return a list of MIME handles."
93   (save-excursion
94     (let (ct ctl type subtype cte cd description id result)
95       (save-restriction
96         (mail-narrow-to-head)
97         (when (and (or no-strict-mime
98                        (mail-fetch-field "mime-version"))
99                    (setq ct (mail-fetch-field "content-type")))
100           (setq ctl (condition-case () (mail-header-parse-content-type ct)
101                       (error nil))
102                 cte (mail-fetch-field "content-transfer-encoding")
103                 cd (mail-fetch-field "content-disposition")
104                 description (mail-fetch-field "content-description")
105                 id (mail-fetch-field "content-id"))))
106       (if (not ctl)
107           (mm-dissect-singlepart '("text/plain") nil no-strict-mime nil nil)
108         (setq type (split-string (car ctl) "/"))
109         (setq subtype (cadr type)
110               type (pop type))
111         (setq
112          result
113          (cond
114           ((equal type "multipart")
115            (mm-dissect-multipart ctl))
116           (t
117            (mm-dissect-singlepart
118             ctl
119             (and cte (intern (downcase (mail-header-remove-whitespace
120                                         (mail-header-remove-comments
121                                          cte)))))
122             no-strict-mime
123             (and cd (condition-case ()
124                         (mail-header-parse-content-disposition cd)
125                       (error nil)))))))
126         (when id
127           (push (cons id result) mm-content-id-alist))
128         result))))
129
130 (defun mm-dissect-singlepart (ctl cte &optional force cdl description)
131   (when (or force
132             (not (equal "text/plain" (car ctl))))
133     (let ((res (list (list (mm-copy-to-buffer) ctl cte nil cdl description))))
134       (push (car res) mm-dissection-list)
135       res)))
136
137 (defun mm-remove-all-parts ()
138   "Remove all MIME handles."
139   (interactive)
140   (mapcar 'mm-remove-part mm-dissection-list)
141   (setq mm-dissection-list nil))
142
143 (defun mm-dissect-multipart (ctl)
144   (goto-char (point-min))
145   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
146         (close-delimiter (concat boundary "--[ \t]*$"))
147         start parts 
148         (end (save-excursion    
149                (goto-char (point-max))
150                (if (re-search-backward close-delimiter nil t)
151                    (match-beginning 0)
152                  (point-max)))))
153     (while (search-forward boundary end t)
154       (goto-char (match-beginning 0))
155       (when start
156         (save-excursion
157           (save-restriction
158             (narrow-to-region start (point))
159             (setq parts (nconc (mm-dissect-buffer t) parts)))))
160       (forward-line 2)
161       (setq start (point)))
162     (when start
163       (save-excursion
164         (save-restriction
165           (narrow-to-region start end)
166           (setq parts (nconc (mm-dissect-buffer t) parts)))))
167     (nreverse parts)))
168
169 (defun mm-copy-to-buffer ()
170   "Copy the contents of the current buffer to a fresh buffer."
171   (save-excursion
172     (let ((obuf (current-buffer))
173           beg)
174       (goto-char (point-min))
175       (search-forward "\n\n" nil t)
176       (setq beg (point))
177       (set-buffer (generate-new-buffer " *mm*"))
178       (insert-buffer-substring obuf beg)
179       (current-buffer))))
180
181 (defun mm-inlinable-part-p (type)
182   "Say whether TYPE can be displayed inline."
183   (eq (mm-user-method type) 'inline))
184
185 (defun mm-display-part (handle &optional no-default)
186   "Display the MIME part represented by HANDLE."
187   (save-excursion
188     (mailcap-parse-mailcaps)
189     (if (mm-handle-undisplayer handle)
190         (mm-remove-part handle)
191       (let* ((type (car (mm-handle-type handle)))
192              (method (mailcap-mime-info type))
193              (user-method (mm-user-method type)))
194         (if (eq user-method 'inline)
195             (progn
196               (forward-line 1)
197               (mm-display-inline handle))
198           (when (or user-method
199                     method
200                     (not no-default))
201             (mm-display-external
202              handle (or user-method method 'mailcap-save-binary-file))))))))
203
204 (defun mm-display-external (handle method)
205   "Display HANDLE using METHOD."
206   (mm-with-unibyte-buffer
207     (insert-buffer-substring (mm-handle-buffer handle))
208     (mm-decode-content-transfer-encoding
209      (mm-handle-encoding handle) (car (mm-handle-type handle)))
210     (if (functionp method)
211         (let ((cur (current-buffer)))
212           (switch-to-buffer (generate-new-buffer "*mm*"))
213           (buffer-disable-undo)
214           (mm-set-buffer-file-coding-system 'no-conversion)
215           (insert-buffer-substring cur)
216           (funcall method)
217           (mm-handle-set-undisplayer handle (current-buffer)))
218       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
219              (filename (mail-content-type-get
220                         (mm-handle-disposition handle) 'filename))
221              (needsterm (assoc "needsterm"
222                                (mailcap-mime-info
223                                 (car (mm-handle-type handle)) t)))
224              process file)
225         ;; We create a private sub-directory where we store our files.
226         (make-directory dir)
227         (set-file-modes dir 448)
228         (if filename
229             (setq file (expand-file-name (file-name-nondirectory filename)
230                                          dir))
231           (setq file (make-temp-name (expand-file-name "mm." dir))))
232         (write-region (point-min) (point-max)
233                       file nil 'nomesg nil 'no-conversion)
234         (setq process
235               (if needsterm
236                   (start-process "*display*" nil
237                                  "xterm"
238                                  "-e" shell-file-name "-c"
239                                  (format method
240                                          (mm-quote-arg file)))
241                 (start-process "*display*" (generate-new-buffer "*mm*")
242                                shell-file-name
243                                "-c" (format method
244                                             (mm-quote-arg file)))))
245         (mm-handle-set-undisplayer handle (cons file process))
246         (message "Displaying %s..." (format method file))))))
247
248 (defun mm-remove-part (handle)
249   "Remove the displayed MIME part represented by HANDLE."
250   (let ((object (mm-handle-undisplayer handle)))
251     (condition-case ()
252         (cond
253          ;; Internally displayed part.
254          ((mm-annotationp object)
255           (delete-annotation object))
256          ((or (functionp object)
257               (and (listp object)
258                    (eq (car object) 'lambda)))
259           (funcall object))
260          ;; Externally displayed part.
261          ((consp object)
262           (condition-case ()
263               (delete-file (car object))
264             (error nil))
265           (condition-case ()
266               (delete-directory (file-name-directory (car object)))
267             (error nil))
268           (condition-case ()
269               (kill-process (cdr object))
270             (error nil)))
271          ((bufferp object)
272           (when (buffer-live-p object)
273             (kill-buffer object))))
274       (error nil))
275     (mm-handle-set-undisplayer handle nil)))
276
277 (defun mm-display-inline (handle)
278   (let* ((type (car (mm-handle-type handle)))
279          (function (cadr (assoc type mm-inline-media-tests))))
280     (funcall function handle)))
281
282 (defun mm-inlinable-p (type)
283   "Say whether TYPE can be displayed inline."
284   (let ((alist mm-inline-media-tests)
285         test)
286     (while alist
287       (when (equal type (caar alist))
288         (setq test (caddar alist)
289               alist nil)
290         (setq test (eval test)))
291       (pop alist))
292     test))
293
294 (defun mm-user-method (type)
295   "Return the user-defined method for TYPE."
296   (let ((methods mm-user-display-methods)
297         method result)
298     (while (setq method (pop methods))
299       (when (string-match (car method) type)
300         (when (or (not (eq (cdr method) 'inline))
301                   (mm-inlinable-p type))
302           (setq result (cdr method)
303                 methods nil))))
304     result))
305
306 (defun mm-automatic-display-p (type)
307   "Return the user-defined method for TYPE."
308   (let ((methods mm-user-automatic-display)
309         method result)
310     (while (setq method (pop methods))
311       (when (string-match method type)
312         (setq result t
313               methods nil)))
314     result))
315
316 (defun add-mime-display-method (type method)
317   "Make parts of TYPE be displayed with METHOD.
318 This overrides entries in the mailcap file."
319   (push (cons type method) mm-user-display-methods))
320
321 (defun mm-destroy-part (handle)
322   "Destroy the data structures connected to HANDLE."
323   (mm-remove-part handle)
324   (when (buffer-live-p (mm-handle-buffer handle))
325     (kill-buffer (mm-handle-buffer handle))))
326
327 (defun mm-quote-arg (arg)
328   "Return a version of ARG that is safe to evaluate in a shell."
329   (let ((pos 0) new-pos accum)
330     ;; *** bug: we don't handle newline characters properly
331     (while (setq new-pos (string-match "[!`\"$\\& \t{} ]" arg pos))
332       (push (substring arg pos new-pos) accum)
333       (push "\\" accum)
334       (push (list (aref arg new-pos)) accum)
335       (setq pos (1+ new-pos)))
336     (if (= pos 0)
337         arg
338       (apply 'concat (nconc (nreverse accum) (list (substring arg pos)))))))
339
340 ;;;
341 ;;; Functions for outputting parts
342 ;;;
343
344 (defun mm-get-part (handle)
345   "Return the contents of HANDLE as a string."
346   (mm-with-unibyte-buffer
347     (insert-buffer-substring (mm-handle-buffer handle))
348     (mm-decode-content-transfer-encoding
349      (mm-handle-encoding handle)
350      (car (mm-handle-type handle)))
351     (buffer-string)))
352
353 (defvar mm-default-directory nil)
354
355 (defun mm-save-part (handle)
356   "Write HANDLE to a file."
357   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
358          (filename (mail-content-type-get
359                     (mm-handle-disposition handle) 'filename))
360          file)
361     (when filename
362       (setq filename (file-name-nondirectory filename)))
363     (setq file
364           (read-file-name "Save MIME part to: "
365                           (expand-file-name
366                            (or filename name "")
367                            (or mm-default-directory default-directory))))
368     (setq mm-default-directory (file-name-directory file))
369     (mm-with-unibyte-buffer
370       (insert-buffer-substring (mm-handle-buffer handle))
371       (mm-decode-content-transfer-encoding
372        (mm-handle-encoding handle)
373        (car (mm-handle-type handle)))
374       (when (or (not (file-exists-p file))
375                 (yes-or-no-p (format "File %s already exists; overwrite? "
376                                      file)))
377         (write-region (point-min) (point-max) file)))))
378
379 (defun mm-pipe-part (handle)
380   "Pipe HANDLE to a process."
381   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
382          (command
383           (read-string "Shell command on MIME part: " mm-last-shell-command)))
384     (mm-with-unibyte-buffer
385       (insert-buffer-substring (mm-handle-buffer handle))
386       (mm-decode-content-transfer-encoding
387        (mm-handle-encoding handle)
388        (car (mm-handle-type handle)))
389       (shell-command-on-region (point-min) (point-max) command nil))))
390
391 (defun mm-interactively-view-part (handle)
392   "Display HANDLE using METHOD."
393   (let* ((type (car (mm-handle-type handle)))
394          (methods
395           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
396                   (mailcap-mime-info type 'all)))
397          (method (completing-read "Viewer: " methods)))
398     (mm-display-external (copy-sequence handle) method)))
399
400 (defun mm-preferred-alternative (handles &optional preferred)
401   "Say which of HANDLES are preferred."
402   (let ((prec (if preferred (list preferred) mm-alternative-precedence))
403         p h result type)
404     (while (setq p (pop prec))
405       (setq h handles)
406       (while h
407         (setq type (car (mm-handle-type (car h))))
408         (when (and (equal p type)
409                    (mm-automatic-display-p type)
410                    (or (not (mm-handle-disposition (car h)))
411                        (equal (car (mm-handle-disposition (car h)))
412                               "inline")))
413           (setq result (car h)
414                 h nil
415                 prec nil))
416         (pop h)))
417     result))
418
419 (defun mm-get-content-id (id)
420   "Return the handle(s) referred to by ID."
421   (cdr (assoc id mm-content-id-alist)))
422
423 (provide 'mm-decode)
424
425 ;; mm-decode.el ends here