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