*** empty log message ***
[gnus] / 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     ("text/x-vcard" mm-inline-text (locate-library "vcard"))
85     ("message/delivery-status" mm-inline-text t)
86     ("text/.*" mm-inline-text t)
87     ("audio/wav" mm-inline-audio
88      (and (or (featurep 'nas-sound) (featurep 'native-sound))
89           (device-sound-enabled-p)))
90     ("audio/au" mm-inline-audio
91      (and (or (featurep 'nas-sound) (featurep 'native-sound))
92           (device-sound-enabled-p)))
93     ("multipart/alternative" ignore t)
94     ("multipart/mixed" ignore t)
95     ("multipart/related" ignore t))
96   "Alist of media types/test that say whether the media types can be displayed inline.")
97
98 (defvar mm-user-display-methods
99   '(("image/.*" . inline)
100     ("text/.*" . inline)
101     ("message/delivery-status" . inline)))
102
103 (defvar mm-user-automatic-display
104   '("text/plain" "text/enriched" "text/richtext" "text/html"
105     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"))
106
107 (defvar mm-attachment-override-types
108   '("text/plain" "text/x-vcard")
109   "Types that should have \"attachment\" ignored if they can be displayed inline.")
110
111 (defvar mm-user-automatic-external-display nil
112   "List of MIME type regexps that will be displayed externally automatically.")
113
114 (defvar mm-alternative-precedence
115   '("multipart/related" "multipart/mixed" "multipart/alternative"
116     "image/jpeg" "image/gif" "text/html" "text/enriched"
117     "text/richtext" "text/plain")
118   "List that describes the precedence of alternative parts.")
119
120 (defvar mm-tmp-directory
121   (cond ((fboundp 'temp-directory) (temp-directory))
122         ((boundp 'temporary-file-directory) temporary-file-directory)
123         ("/tmp/"))
124   "Where mm will store its temporary files.")
125
126 (defvar mm-all-images-fit nil
127   "If non-nil, then all images fit in the buffer.")
128
129 ;;; Internal variables.
130
131 (defvar mm-dissection-list nil)
132 (defvar mm-last-shell-command "")
133 (defvar mm-content-id-alist nil)
134
135 ;;; The functions.
136
137 (defun mm-dissect-buffer (&optional no-strict-mime)
138   "Dissect the current buffer and return a list of MIME handles."
139   (save-excursion
140     (let (ct ctl type subtype cte cd description id result)
141       (save-restriction
142         (mail-narrow-to-head)
143         (when (or no-strict-mime
144                   (mail-fetch-field "mime-version"))
145           (setq ct (mail-fetch-field "content-type")
146                 ctl (ignore-errors (mail-header-parse-content-type ct))
147                 cte (mail-fetch-field "content-transfer-encoding")
148                 cd (mail-fetch-field "content-disposition")
149                 description (mail-fetch-field "content-description")
150                 id (mail-fetch-field "content-id"))))
151       (if (or (not ctl)
152               (not (string-match "/" (car ctl))))
153           (mm-dissect-singlepart
154            '("text/plain") nil no-strict-mime
155            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
156            description)
157         (setq type (split-string (car ctl) "/"))
158         (setq subtype (cadr type)
159               type (pop type))
160         (setq
161          result
162          (cond
163           ((equal type "multipart")
164            (cons (car ctl) (mm-dissect-multipart ctl)))
165           (t
166            (mm-dissect-singlepart
167             ctl
168             (and cte (intern (downcase (mail-header-remove-whitespace
169                                         (mail-header-remove-comments
170                                          cte)))))
171             no-strict-mime
172             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
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               (when (and (not non-viewer)
294                          method)
295                 (mm-handle-set-undisplayer handle mm)))))
296       ;; The function is a string to be executed.
297       (mm-insert-part handle)
298       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
299              (filename (mail-content-type-get
300                         (mm-handle-disposition handle) 'filename))
301              (needsterm (assoc "needsterm"
302                                (mailcap-mime-info
303                                 (car (mm-handle-type handle)) t)))
304              process file buffer)
305         ;; We create a private sub-directory where we store our files.
306         (make-directory dir)
307         (set-file-modes dir 448)
308         (if filename
309             (setq file (expand-file-name (file-name-nondirectory filename)
310                                          dir))
311           (setq file (make-temp-name (expand-file-name "mm." dir))))
312         (write-region (point-min) (point-max) file nil 'nomesg)
313         (message "Viewing with %s" method)
314         (unwind-protect
315             (setq process
316                   (if needsterm
317                       (start-process "*display*" nil
318                                      "xterm"
319                                      "-e" shell-file-name "-c"
320                                      (format method
321                                              (mm-quote-arg file)))
322                     (start-process "*display*"
323                                    (setq buffer (generate-new-buffer "*mm*"))
324                                    shell-file-name
325                                    "-c" (format method
326                                                 (mm-quote-arg file)))))
327           (mm-handle-set-undisplayer handle (cons file buffer)))
328         (message "Displaying %s..." (format method file))))))
329
330 (defun mm-remove-parts (handles)
331   "Remove the displayed MIME parts represented by HANDLE."
332   (if (and (listp handles)
333            (bufferp (car handles)))
334       (mm-remove-part handles)
335     (let (handle)
336       (while (setq handle (pop handles))
337         (cond
338          ((stringp handle)
339           )
340          ((and (listp handle)
341                (stringp (car handle)))
342           (mm-remove-parts (cdr handle)))
343          (t
344           (mm-remove-part handle)))))))
345
346 (defun mm-destroy-parts (handles)
347   "Remove the displayed MIME parts represented by HANDLE."
348   (if (and (listp handles)
349            (bufferp (car handles)))
350       (mm-destroy-part handles)
351     (let (handle)
352       (while (setq handle (pop handles))
353         (cond
354          ((stringp handle)
355           )
356          ((and (listp handle)
357                (stringp (car handle)))
358           (mm-destroy-parts (cdr handle)))
359          (t
360           (mm-destroy-part handle)))))))
361
362 (defun mm-remove-part (handle)
363   "Remove the displayed MIME part represented by HANDLE."
364   (when (listp handle)
365     (let ((object (mm-handle-undisplayer handle)))
366       (ignore-errors
367         (cond
368          ;; Internally displayed part.
369          ((mm-annotationp object)
370           (delete-annotation object))
371          ((or (functionp object)
372               (and (listp object)
373                    (eq (car object) 'lambda)))
374           (funcall object))
375          ;; Externally displayed part.
376          ((consp object)
377           (ignore-errors (delete-file (car object)))
378           (ignore-errors (delete-directory (file-name-directory (car object))))
379           (ignore-errors (kill-buffer (cdr object))))
380          ((bufferp object)
381           (when (buffer-live-p object)
382             (kill-buffer object)))))
383       (mm-handle-set-undisplayer handle nil))))
384
385 (defun mm-display-inline (handle)
386   (let* ((type (car (mm-handle-type handle)))
387          (function (cadr (assoc type mm-inline-media-tests))))
388     (funcall function handle)
389     (goto-char (point-min))))
390
391 (defun mm-inlinable-p (type)
392   "Say whether TYPE can be displayed inline."
393   (let ((alist mm-inline-media-tests)
394         test)
395     (while alist
396       (when (equal type (caar alist))
397         (setq test (caddar alist)
398               alist nil)
399         (setq test (eval test)))
400       (pop alist))
401     test))
402
403 (defun mm-user-method (type)
404   "Return the user-defined method for TYPE."
405   (let ((methods mm-user-display-methods)
406         method result)
407     (while (setq method (pop methods))
408       (when (string-match (car method) type)
409         (when (or (not (eq (cdr method) 'inline))
410                   (mm-inlinable-p type))
411           (setq result (cdr method)
412                 methods nil))))
413     result))
414
415 (defun mm-automatic-display-p (type)
416   "Return the user-defined method for TYPE."
417   (let ((methods mm-user-automatic-display)
418         method result)
419     (while (setq method (pop methods))
420       (when (and (string-match method type)
421                  (mm-inlinable-p type))
422         (setq result t
423               methods nil)))
424     result))
425
426 (defun mm-attachment-override-p (type)
427   "Say whether TYPE should have attachment behavior overridden."
428   (let ((types mm-attachment-override-types)
429         ty)
430     (catch 'found
431       (while (setq ty (pop types))
432         (when (and (string-match ty type)
433                    (mm-inlinable-p type))
434           (throw 'found t))))))
435
436 (defun mm-automatic-external-display-p (type)
437   "Return the user-defined method for TYPE."
438   (let ((methods mm-user-automatic-external-display)
439         method result)
440     (while (setq method (pop methods))
441       (when (string-match method type)
442         (setq result t
443               methods nil)))
444     result))
445
446 (defun add-mime-display-method (type method)
447   "Make parts of TYPE be displayed with METHOD.
448 This overrides entries in the mailcap file."
449   (push (cons type method) mm-user-display-methods))
450
451 (defun mm-destroy-part (handle)
452   "Destroy the data structures connected to HANDLE."
453   (when (listp handle)
454     (mm-remove-part handle)
455     (when (buffer-live-p (mm-handle-buffer handle))
456       (kill-buffer (mm-handle-buffer handle)))))
457
458 (defun mm-handle-displayed-p (handle)
459   "Say whether HANDLE is displayed or not."
460   (mm-handle-undisplayer handle))
461
462 (defun mm-quote-arg (arg)
463   "Return a version of ARG that is safe to evaluate in a shell."
464   (let ((pos 0) new-pos accum)
465     ;; *** bug: we don't handle newline characters properly
466     (while (setq new-pos (string-match "[;!`\"$\\& \t{} |()<>]" arg pos))
467       (push (substring arg pos new-pos) accum)
468       (push "\\" accum)
469       (push (list (aref arg new-pos)) accum)
470       (setq pos (1+ new-pos)))
471     (if (= pos 0)
472         arg
473       (apply 'concat (nconc (nreverse accum) (list (substring arg pos)))))))
474
475 ;;;
476 ;;; Functions for outputting parts
477 ;;;
478
479 (defun mm-get-part (handle)
480   "Return the contents of HANDLE as a string."
481   (mm-with-unibyte-buffer
482     (mm-insert-part handle)
483     (buffer-string)))
484
485 (defun mm-insert-part (handle)
486   "Insert the contents of HANDLE in the current buffer."
487   (let ((cur (current-buffer)))
488     (save-excursion
489       (mm-with-unibyte-buffer
490         (insert-buffer-substring (mm-handle-buffer handle))
491         (mm-decode-content-transfer-encoding
492          (mm-handle-encoding handle)
493          (car (mm-handle-type handle)))
494         (let ((temp (current-buffer)))
495           (set-buffer cur)
496           (insert-buffer-substring temp))))))
497
498 (defvar mm-default-directory nil)
499
500 (defun mm-save-part (handle)
501   "Write HANDLE to a file."
502   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
503          (filename (mail-content-type-get
504                     (mm-handle-disposition handle) 'filename))
505          file)
506     (when filename
507       (setq filename (file-name-nondirectory filename)))
508     (setq file
509           (read-file-name "Save MIME part to: "
510                           (expand-file-name
511                            (or filename name "")
512                            (or mm-default-directory default-directory))))
513     (setq mm-default-directory (file-name-directory file))
514     (mm-with-unibyte-buffer
515       (mm-insert-part handle)
516       (when (or (not (file-exists-p file))
517                 (yes-or-no-p (format "File %s already exists; overwrite? "
518                                      file)))
519         ;; Now every coding system is 100% binary within mm-with-unibyte-buffer
520         ;; Is text still special?
521       (let ((coding-system-for-write
522              (if (equal "text" (car (split-string
523                                      (car (mm-handle-type handle)) "/")))
524                  buffer-file-coding-system
525                'binary))
526             ;; Don't re-compress .gz & al.  Arguably we should make
527             ;; `file-name-handler-alist' nil, but that would chop
528             ;; ange-ftp which it's reasonable to use here.
529             (inhibit-file-name-operation 'write-region)
530             (inhibit-file-name-handlers
531              (if (equal (car (mm-handle-type handle))
532                         "application/octet-stream")
533                  (cons 'jka-compr-handler inhibit-file-name-handlers)
534                inhibit-file-name-handlers)))
535         (write-region (point-min) (point-max) file))))))
536
537 (defun mm-pipe-part (handle)
538   "Pipe HANDLE to a process."
539   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
540          (command
541           (read-string "Shell command on MIME part: " mm-last-shell-command)))
542     (mm-with-unibyte-buffer
543       (mm-insert-part handle)
544       (shell-command-on-region (point-min) (point-max) command nil))))
545
546 (defun mm-interactively-view-part (handle)
547   "Display HANDLE using METHOD."
548   (let* ((type (car (mm-handle-type handle)))
549          (methods
550           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
551                   (mailcap-mime-info type 'all)))
552          (method (completing-read "Viewer: " methods)))
553     (mm-display-external (copy-sequence handle) method)))
554
555 (defun mm-preferred-alternative (handles &optional preferred)
556   "Say which of HANDLES are preferred."
557   (let ((prec (if preferred (list preferred) mm-alternative-precedence))
558         p h result type handle)
559     (while (setq p (pop prec))
560       (setq h handles)
561       (while h
562         (setq type
563               (if (stringp (caar h))
564                   (caar h)
565                 (car (mm-handle-type (car h)))))
566         (setq handle (car h))
567         (when (and (equal p type)
568                    (mm-automatic-display-p type)
569                    (or (stringp (caar h))
570                        (not (mm-handle-disposition (car h)))
571                        (equal (car (mm-handle-disposition (car h)))
572                               "inline")))
573           (setq result (car h)
574                 h nil
575                 prec nil))
576         (pop h)))
577     result))
578
579 (defun mm-get-content-id (id)
580   "Return the handle(s) referred to by ID."
581   (cdr (assoc id mm-content-id-alist)))
582
583 (defun mm-get-image (handle)
584   "Return an image instance based on HANDLE."
585   (let ((type (cadr (split-string (car (mm-handle-type handle)) "/")))
586         spec)
587     ;; Allow some common translations.
588     (setq type
589           (cond
590            ((equal type "x-pixmap")
591             "xpm")
592            ((equal type "x-xbitmap")
593             "xbm")
594            (t type)))
595     (or (mm-handle-cache handle)
596         (mm-with-unibyte-buffer
597           (mm-insert-part handle)
598           (prog1
599               (setq spec
600                     (make-glyph `[,(intern type) :data ,(buffer-string)]))
601             (mm-handle-set-cache handle spec))))))
602
603 (defun mm-image-fit-p (handle)
604   "Say whether the image in HANDLE will fit the current window."
605   (let ((image (mm-get-image handle)))
606     (or mm-all-images-fit
607         (and (< (glyph-width image) (window-pixel-width))
608              (< (glyph-height image) (window-pixel-height))))))
609
610 (provide 'mm-decode)
611
612 ;; mm-decode.el ends here