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