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