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