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