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