3d16ff373a43f7d12ce97dc495545fae15209925
[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 (defgroup mime-display ()
32     "Display of MIME in mail and news articles."
33   :link '(custom-manual "(emacs-mime)Customization")
34   :group 'mail
35   :group 'news)
36
37 ;;; Convenience macros.
38
39 (defmacro mm-handle-buffer (handle)
40   `(nth 0 ,handle))
41 (defmacro mm-handle-type (handle)
42   `(nth 1 ,handle))
43 (defsubst mm-handle-media-type (handle)
44   (if (stringp (car handle))
45       (car handle)
46     (car (mm-handle-type handle))))
47 (defsubst mm-handle-media-supertype (handle)
48   (car (split-string (mm-handle-media-type handle) "/")))
49 (defsubst mm-handle-media-subtype (handle)
50   (cadr (split-string (mm-handle-media-type handle) "/")))
51 (defmacro mm-handle-encoding (handle)
52   `(nth 2 ,handle))
53 (defmacro mm-handle-undisplayer (handle)
54   `(nth 3 ,handle))
55 (defmacro mm-handle-set-undisplayer (handle function)
56   `(setcar (nthcdr 3 ,handle) ,function))
57 (defmacro mm-handle-disposition (handle)
58   `(nth 4 ,handle))
59 (defmacro mm-handle-description (handle)
60   `(nth 5 ,handle))
61 (defmacro mm-handle-cache (handle)
62   `(nth 6 ,handle))
63 (defmacro mm-handle-set-cache (handle contents)
64   `(setcar (nthcdr 6 ,handle) ,contents))
65 (defmacro mm-handle-id (handle)
66   `(nth 7 ,handle))
67 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
68                                     disposition description cache
69                                     id)
70   `(list ,buffer ,type ,encoding ,undisplayer
71          ,disposition ,description ,cache ,id))
72
73 (defcustom mm-inline-media-tests
74   '(("image/jpeg"
75      mm-inline-image
76      (lambda (handle)
77        (mm-valid-and-fit-image-p 'jpeg handle)))
78     ("image/png"
79      mm-inline-image
80      (lambda (handle)
81        (mm-valid-and-fit-image-p 'png handle)))
82     ("image/gif"
83      mm-inline-image
84      (lambda (handle)
85        (mm-valid-and-fit-image-p 'gif handle)))
86     ("image/tiff"
87      mm-inline-image
88      (lambda (handle)
89        (mm-valid-and-fit-image-p 'tiff handle)) )
90     ("image/xbm"
91      mm-inline-image
92      (lambda (handle)
93        (mm-valid-and-fit-image-p 'xbm handle)))
94     ("image/x-xbitmap"
95      mm-inline-image
96      (lambda (handle)
97        (mm-valid-and-fit-image-p 'xbm handle)))
98     ("image/xpm"
99      mm-inline-image
100      (lambda (handle)
101        (mm-valid-and-fit-image-p 'xpm handle)))
102     ("image/x-pixmap"
103      mm-inline-image
104      (lambda (handle)
105        (mm-valid-and-fit-image-p 'xpm handle)))
106     ("image/bmp"
107      mm-inline-image
108      (lambda (handle)
109        (mm-valid-and-fit-image-p 'bmp handle)))
110     ("text/plain" mm-inline-text identity)
111     ("text/enriched" mm-inline-text identity)
112     ("text/richtext" mm-inline-text identity)
113     ("text/x-patch" mm-display-patch-inline
114      (lambda (handle)
115        (locate-library "diff-mode")))
116     ("text/html"
117      mm-inline-text
118      (lambda (handle)
119        (locate-library "w3")))
120     ("text/x-vcard"
121      mm-inline-text
122      (lambda (handle)
123        (or (featurep 'vcard)
124            (locate-library "vcard"))))
125     ("message/delivery-status" mm-inline-text identity)
126     ("message/rfc822" mm-inline-message identity)
127     ("text/.*" mm-inline-text identity)
128     ("audio/wav" mm-inline-audio
129      (lambda (handle)
130        (and (or (featurep 'nas-sound) (featurep 'native-sound))
131             (device-sound-enabled-p))))
132     ("audio/au"
133      mm-inline-audio
134      (lambda (handle)
135        (and (or (featurep 'nas-sound) (featurep 'native-sound))
136             (device-sound-enabled-p))))
137     ("application/pgp-signature" ignore identity)
138     ("multipart/alternative" ignore identity)
139     ("multipart/mixed" ignore identity)
140     ("multipart/related" ignore identity))
141   "Alist of media types/tests saying whether types can be displayed inline."
142   :type '(repeat (list (string :tag "MIME type")
143                        (function :tag "Display function")
144                        (function :tag "Display test")))
145   :group 'mime-display)
146
147 (defcustom mm-inlined-types
148   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
149     "application/pgp-signature")
150   "List of media types that are to be displayed inline."
151   :type '(repeat string)
152   :group 'mime-display)
153   
154 (defcustom mm-automatic-display
155   '("text/plain" "text/enriched" "text/richtext" "text/html"
156     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
157     "message/rfc822" "text/x-patch" "application/pgp-signature")
158   "A list of MIME types to be displayed automatically."
159   :type '(repeat string)
160   :group 'mime-display)
161
162 (defcustom mm-attachment-override-types '("text/x-vcard")
163   "Types to have \"attachment\" ignored if they can be displayed inline."
164   :type '(repeat string)
165   :group 'mime-display)
166
167 (defcustom mm-inline-override-types nil
168   "Types to be treated as attachments even if they can be displayed inline."
169   :type '(repeat string)
170   :group 'mime-display)
171
172 (defcustom mm-inline-override-types nil
173   "Types to be treated as attachments even if they can be displayed inline."
174   :type '(repeat string)
175   :group 'mime-display)
176
177 (defcustom mm-automatic-external-display nil
178   "List of MIME type regexps that will be displayed externally automatically."
179   :type '(repeat string)
180   :group 'mime-display)
181
182 (defcustom mm-discouraged-alternatives nil
183   "List of MIME types that are discouraged when viewing multipart/alternative.
184 Viewing agents are supposed to view the last possible part of a message,
185 as that is supposed to be the richest.  However, users may prefer other
186 types instead, and this list says what types are most unwanted.  If,
187 for instance, text/html parts are very unwanted, and text/richtech are
188 somewhat unwanted, then the value of this variable should be set
189 to:
190
191  (\"text/html\" \"text/richtext\")"
192   :type '(repeat string)
193   :group 'mime-display)
194
195 (defvar mm-tmp-directory
196   (cond ((fboundp 'temp-directory) (temp-directory))
197         ((boundp 'temporary-file-directory) temporary-file-directory)
198         ("/tmp/"))
199   "Where mm will store its temporary files.")
200
201 (defcustom mm-inline-large-images nil
202   "If non-nil, then all images fit in the buffer."
203   :type 'boolean
204   :group 'mime-display)
205
206 ;;; Internal variables.
207
208 (defvar mm-dissection-list nil)
209 (defvar mm-last-shell-command "")
210 (defvar mm-content-id-alist nil)
211
212 ;;; The functions.
213
214 (defun mm-dissect-buffer (&optional no-strict-mime)
215   "Dissect the current buffer and return a list of MIME handles."
216   (save-excursion
217     (let (ct ctl type subtype cte cd description id result)
218       (save-restriction
219         (mail-narrow-to-head)
220         (when (or no-strict-mime
221                   (mail-fetch-field "mime-version"))
222           (setq ct (mail-fetch-field "content-type")
223                 ctl (ignore-errors (mail-header-parse-content-type ct))
224                 cte (mail-fetch-field "content-transfer-encoding")
225                 cd (mail-fetch-field "content-disposition")
226                 description (mail-fetch-field "content-description")
227                 id (mail-fetch-field "content-id"))))
228       (if (or (not ctl)
229               (not (string-match "/" (car ctl))))
230           (mm-dissect-singlepart
231            '("text/plain") 
232            (and cte (intern (downcase (mail-header-remove-whitespace
233                                        (mail-header-remove-comments
234                                         cte)))))
235            no-strict-mime
236            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
237            description)
238         (setq type (split-string (car ctl) "/"))
239         (setq subtype (cadr type)
240               type (pop type))
241         (setq
242          result
243          (cond
244           ((equal type "multipart")
245            (cons (car ctl) (mm-dissect-multipart ctl)))
246           (t
247            (mm-dissect-singlepart
248             ctl
249             (and cte (intern (downcase (mail-header-remove-whitespace
250                                         (mail-header-remove-comments
251                                          cte)))))
252             no-strict-mime
253             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
254             description id))))
255         (when id
256           (when (string-match " *<\\(.*\\)> *" id)
257             (setq id (match-string 1 id)))
258           (push (cons id result) mm-content-id-alist))
259         result))))
260
261 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
262   (when (or force
263             (not (equal "text/plain" (car ctl))))
264     (let ((res (mm-make-handle
265                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
266       (push (car res) mm-dissection-list)
267       res)))
268
269 (defun mm-remove-all-parts ()
270   "Remove all MIME handles."
271   (interactive)
272   (mapcar 'mm-remove-part mm-dissection-list)
273   (setq mm-dissection-list nil))
274
275 (defun mm-dissect-multipart (ctl)
276   (goto-char (point-min))
277   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
278         (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
279         start parts
280         (end (save-excursion
281                (goto-char (point-max))
282                (if (re-search-backward close-delimiter nil t)
283                    (match-beginning 0)
284                  (point-max)))))
285     (while (search-forward boundary end t)
286       (goto-char (match-beginning 0))
287       (when start
288         (save-excursion
289           (save-restriction
290             (narrow-to-region start (point))
291             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
292       (forward-line 2)
293       (setq start (point)))
294     (when start
295       (save-excursion
296         (save-restriction
297           (narrow-to-region start end)
298           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
299     (nreverse parts)))
300
301 (defun mm-copy-to-buffer ()
302   "Copy the contents of the current buffer to a fresh buffer."
303   (save-excursion
304     (let ((obuf (current-buffer))
305           beg)
306       (goto-char (point-min))
307       (search-forward-regexp "^\n" nil t)
308       (setq beg (point))
309       (set-buffer (generate-new-buffer " *mm*"))
310       (insert-buffer-substring obuf beg)
311       (current-buffer))))
312
313 (defun mm-display-part (handle &optional no-default)
314   "Display the MIME part represented by HANDLE.
315 Returns nil if the part is removed; inline if displayed inline;
316 external if displayed external."
317   (save-excursion
318     (mailcap-parse-mailcaps)
319     (if (mm-handle-displayed-p handle)
320         (mm-remove-part handle)
321       (let* ((type (mm-handle-media-type handle))
322              (method (mailcap-mime-info type)))
323         (if (mm-inlined-p handle)
324             (progn
325               (forward-line 1)
326               (mm-display-inline handle)
327               'inline)
328           (when (or method
329                     (not no-default))
330             (if (and (not method)
331                      (equal "text" (car (split-string type))))
332                 (progn
333                   (forward-line 1)
334                   (mm-insert-inline handle (mm-get-part handle))
335                   'inline)
336               (mm-display-external
337                handle (or method 'mailcap-save-binary-file))
338               'external)))))))
339
340 (defun mm-display-external (handle method)
341   "Display HANDLE using METHOD."
342   (mm-with-unibyte-buffer
343     (if (functionp method)
344         (let ((cur (current-buffer)))
345           (if (eq method 'mailcap-save-binary-file)
346               (progn
347                 (set-buffer (generate-new-buffer "*mm*"))
348                 (setq method nil))
349             (mm-insert-part handle)
350             (let ((win (get-buffer-window cur t)))
351               (when win
352                 (select-window win)))
353             (switch-to-buffer (generate-new-buffer "*mm*")))
354           (buffer-disable-undo)
355           (mm-set-buffer-file-coding-system mm-binary-coding-system)
356           (insert-buffer-substring cur)
357           (message "Viewing with %s" method)
358           (let ((mm (current-buffer))
359                 (non-viewer (assq 'non-viewer
360                                   (mailcap-mime-info
361                                    (mm-handle-media-type handle) t))))
362             (unwind-protect
363                 (if method
364                     (funcall method)
365                   (mm-save-part handle))
366               (when (and (not non-viewer)
367                          method)
368                 (mm-handle-set-undisplayer handle mm)))))
369       ;; The function is a string to be executed.
370       (mm-insert-part handle)
371       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
372              (filename (mail-content-type-get
373                         (mm-handle-disposition handle) 'filename))
374              (mime-info (mailcap-mime-info
375                          (mm-handle-media-type handle) t))
376              (needsterm (or (assoc "needsterm" mime-info)
377                             (assoc "needsterminal" mime-info)))
378              (copiousoutput (assoc "copiousoutput" mime-info))
379              process file buffer)
380         ;; We create a private sub-directory where we store our files.
381         (make-directory dir)
382         (set-file-modes dir 448)
383         (if filename
384             (setq file (expand-file-name (file-name-nondirectory filename)
385                                          dir))
386           (setq file (make-temp-name (expand-file-name "mm." dir))))
387         (let ((coding-system-for-write mm-binary-coding-system))
388           (write-region (point-min) (point-max) file nil 'nomesg))
389         (message "Viewing with %s" method)
390         (unwind-protect
391             (setq process
392                   (cond (needsterm
393                          (start-process "*display*" nil
394                                         "xterm"
395                                         "-e" shell-file-name 
396                                         shell-command-switch
397                                         (mm-mailcap-command
398                                          method file (mm-handle-type handle))))
399                         (copiousoutput
400                          (start-process "*display*"
401                                         (setq buffer 
402                                               (generate-new-buffer "*mm*"))
403                                         shell-file-name
404                                         shell-command-switch
405                                         (mm-mailcap-command
406                                          method file (mm-handle-type handle)))
407                          (switch-to-buffer buffer))
408                         (t
409                          (start-process "*display*"
410                                         (setq buffer
411                                               (generate-new-buffer "*mm*"))
412                                         shell-file-name
413                                         shell-command-switch
414                                         (mm-mailcap-command
415                                          method file (mm-handle-type handle))))))
416           (mm-handle-set-undisplayer handle (cons file buffer)))
417         (message "Displaying %s..." (format method file))))))
418
419 (defun mm-mailcap-command (method file type-list)
420   (let ((ctl (cdr type-list))
421         (beg 0)
422         out sub total)
423     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t" method beg)
424       (push (substring method beg (match-beginning 0)) out)
425       (setq beg (match-end 0)
426             total (match-string 0 method)
427             sub (match-string 1 method))
428       (cond
429        ((string= total "%s")
430         (push (mm-quote-arg file) out))
431        ((string= total "%t")
432         (push (mm-quote-arg (car type-list)) out))
433        (t
434         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
435     (push (substring method beg (length method)) out)
436     (mapconcat 'identity (nreverse out) "")))
437     
438 (defun mm-remove-parts (handles)
439   "Remove the displayed MIME parts represented by HANDLE."
440   (if (and (listp handles)
441            (bufferp (car handles)))
442       (mm-remove-part handles)
443     (let (handle)
444       (while (setq handle (pop handles))
445         (cond
446          ((stringp handle)
447           )
448          ((and (listp handle)
449                (stringp (car handle)))
450           (mm-remove-parts (cdr handle)))
451          (t
452           (mm-remove-part handle)))))))
453
454 (defun mm-destroy-parts (handles)
455   "Remove the displayed MIME parts represented by HANDLE."
456   (if (and (listp handles)
457            (bufferp (car handles)))
458       (mm-destroy-part handles)
459     (let (handle)
460       (while (setq handle (pop handles))
461         (cond
462          ((stringp handle)
463           )
464          ((and (listp handle)
465                (stringp (car handle)))
466           (mm-destroy-parts (cdr handle)))
467          (t
468           (mm-destroy-part handle)))))))
469
470 (defun mm-remove-part (handle)
471   "Remove the displayed MIME part represented by HANDLE."
472   (when (listp handle)
473     (let ((object (mm-handle-undisplayer handle)))
474       (ignore-errors
475         (cond
476          ;; Internally displayed part.
477          ((mm-annotationp object)
478           (delete-annotation object))
479          ((or (functionp object)
480               (and (listp object)
481                    (eq (car object) 'lambda)))
482           (funcall object))
483          ;; Externally displayed part.
484          ((consp object)
485           (ignore-errors (delete-file (car object)))
486           (ignore-errors (delete-directory (file-name-directory (car object))))
487           (ignore-errors (kill-buffer (cdr object))))
488          ((bufferp object)
489           (when (buffer-live-p object)
490             (kill-buffer object)))))
491       (mm-handle-set-undisplayer handle nil))))
492
493 (defun mm-display-inline (handle)
494   (let* ((type (mm-handle-media-type handle))
495          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
496     (funcall function handle)
497     (goto-char (point-min))))
498
499 (defun mm-assoc-string-match (alist type)
500   (dolist (elem alist)
501     (when (string-match (car elem) type)
502       (return elem))))
503
504 (defun mm-inlinable-p (handle)
505   "Say whether HANDLE can be displayed inline."
506   (let ((alist mm-inline-media-tests)
507         (type (mm-handle-media-type handle))
508         test)
509     (while alist
510       (when (string-match (caar alist) type)
511         (setq test (caddar alist)
512               alist nil)
513         (setq test (funcall test handle)))
514       (pop alist))
515     test))
516
517 (defun mm-automatic-display-p (handle)
518   "Say whether the user wants HANDLE to be displayed automatically."
519   (let ((methods mm-automatic-display)
520         (type (mm-handle-media-type handle))
521         method result)
522     (while (setq method (pop methods))
523       (when (and (not (mm-inline-override-p handle))
524                  (string-match method type)
525                  (mm-inlinable-p handle))
526         (setq result t
527               methods nil)))
528     result))
529
530 (defun mm-inlined-p (handle)
531   "Say whether the user wants HANDLE to be displayed automatically."
532   (let ((methods mm-inlined-types)
533         (type (mm-handle-media-type handle))
534         method result)
535     (while (setq method (pop methods))
536       (when (and (not (mm-inline-override-p handle))
537                  (string-match method type)
538                  (mm-inlinable-p handle))
539         (setq result t
540               methods nil)))
541     result))
542
543 (defun mm-attachment-override-p (handle)
544   "Say whether HANDLE should have attachment behavior overridden."
545   (let ((types mm-attachment-override-types)
546         (type (mm-handle-media-type handle))
547         ty)
548     (catch 'found
549       (while (setq ty (pop types))
550         (when (and (string-match ty type)
551                    (mm-inlinable-p handle))
552           (throw 'found t))))))
553
554 (defun mm-inline-override-p (handle)
555   "Say whether HANDLE should have inline behavior overridden."
556   (let ((types mm-inline-override-types)
557         (type (mm-handle-media-type handle))
558         ty)
559     (catch 'found
560       (while (setq ty (pop types))
561         (when (string-match ty type)
562           (throw 'found t))))))
563
564 (defun mm-automatic-external-display-p (type)
565   "Return the user-defined method for TYPE."
566   (let ((methods mm-automatic-external-display)
567         method result)
568     (while (setq method (pop methods))
569       (when (string-match method type)
570         (setq result t
571               methods nil)))
572     result))
573
574 (defun mm-destroy-part (handle)
575   "Destroy the data structures connected to HANDLE."
576   (when (listp handle)
577     (mm-remove-part handle)
578     (when (buffer-live-p (mm-handle-buffer handle))
579       (kill-buffer (mm-handle-buffer handle)))))
580
581 (defun mm-handle-displayed-p (handle)
582   "Say whether HANDLE is displayed or not."
583   (mm-handle-undisplayer handle))
584
585 ;;;
586 ;;; Functions for outputting parts
587 ;;;
588
589 (defun mm-get-part (handle)
590   "Return the contents of HANDLE as a string."
591   (mm-with-unibyte-buffer
592     (mm-insert-part handle)
593     (buffer-string)))
594
595 (defun mm-insert-part (handle)
596   "Insert the contents of HANDLE in the current buffer."
597   (let ((cur (current-buffer)))
598     (save-excursion
599       (if (member (mm-handle-media-supertype handle) '("text" "message"))
600           (with-temp-buffer
601             (insert-buffer-substring (mm-handle-buffer handle))
602             (mm-decode-content-transfer-encoding
603              (mm-handle-encoding handle)
604              (mm-handle-media-type handle))
605             (let ((temp (current-buffer)))
606               (set-buffer cur)
607               (insert-buffer-substring temp)))
608         (mm-with-unibyte-buffer
609           (insert-buffer-substring (mm-handle-buffer handle))
610           (mm-decode-content-transfer-encoding
611            (mm-handle-encoding handle)
612            (mm-handle-media-type handle))
613           (let ((temp (current-buffer)))
614             (set-buffer cur)
615             (insert-buffer-substring temp)))))))
616
617 (defvar mm-default-directory nil)
618
619 (defun mm-save-part (handle)
620   "Write HANDLE to a file."
621   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
622          (filename (mail-content-type-get
623                     (mm-handle-disposition handle) 'filename))
624          file)
625     (when filename
626       (setq filename (file-name-nondirectory filename)))
627     (setq file
628           (read-file-name "Save MIME part to: "
629                           (expand-file-name
630                            (or filename name "")
631                            (or mm-default-directory default-directory))))
632     (setq mm-default-directory (file-name-directory file))
633     (when (or (not (file-exists-p file))
634               (yes-or-no-p (format "File %s already exists; overwrite? "
635                                    file)))
636       (mm-save-part-to-file handle file))))
637
638 (defun mm-save-part-to-file (handle file)
639   (mm-with-unibyte-buffer
640     (mm-insert-part handle)
641     (let ((coding-system-for-write 'binary)
642           ;; Don't re-compress .gz & al.  Arguably we should make
643           ;; `file-name-handler-alist' nil, but that would chop
644           ;; ange-ftp, which is reasonable to use here.
645           (inhibit-file-name-operation 'write-region)
646           (inhibit-file-name-handlers
647            (cons 'jka-compr-handler inhibit-file-name-handlers)))
648       (write-region (point-min) (point-max) file))))
649
650 (defun mm-pipe-part (handle)
651   "Pipe HANDLE to a process."
652   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
653          (command
654           (read-string "Shell command on MIME part: " mm-last-shell-command)))
655     (mm-with-unibyte-buffer
656       (mm-insert-part handle)
657       (shell-command-on-region (point-min) (point-max) command nil))))
658
659 (defun mm-interactively-view-part (handle)
660   "Display HANDLE using METHOD."
661   (let* ((type (mm-handle-media-type handle))
662          (methods
663           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
664                   (mailcap-mime-info type 'all)))
665          (method (completing-read "Viewer: " methods)))
666     (mm-display-external (copy-sequence handle) method)))
667
668 (defun mm-preferred-alternative (handles &optional preferred)
669   "Say which of HANDLES are preferred."
670   (let ((prec (if preferred (list preferred)
671                 (mm-preferred-alternative-precedence handles)))
672         p h result type handle)
673     (while (setq p (pop prec))
674       (setq h handles)
675       (while h
676         (setq handle (car h))
677         (setq type (mm-handle-media-type handle))
678         (when (and (equal p type)
679                    (mm-automatic-display-p handle)
680                    (or (stringp (car handle))
681                        (not (mm-handle-disposition handle))
682                        (equal (car (mm-handle-disposition handle))
683                               "inline")))
684           (setq result handle
685                 h nil
686                 prec nil))
687         (pop h)))
688     result))
689
690 (defun mm-preferred-alternative-precedence (handles)
691   "Return the precedence based on HANDLES and mm-discouraged-alternatives."
692   (let ((seq (nreverse (mapcar (lambda (h)
693                                  (mm-handle-media-type h))
694                                handles))))
695     (dolist (disc (reverse mm-discouraged-alternatives))
696       (dolist (elem (copy-sequence seq))
697         (when (string-match disc elem)
698           (setq seq (nconc (delete elem seq) (list elem))))))
699     seq))
700
701 (defun mm-get-content-id (id)
702   "Return the handle(s) referred to by ID."
703   (cdr (assoc id mm-content-id-alist)))
704
705 (defun mm-get-image (handle)
706   "Return an image instance based on HANDLE."
707   (let ((type (mm-handle-media-subtype handle))
708         spec)
709     ;; Allow some common translations.
710     (setq type
711           (cond
712            ((equal type "x-pixmap")
713             "xpm")
714            ((equal type "x-xbitmap")
715             "xbm")
716            (t type)))
717     (or (mm-handle-cache handle)
718         (mm-with-unibyte-buffer
719           (mm-insert-part handle)
720           (prog1
721               (setq spec
722                     (ignore-errors
723                       (cond
724                        ((equal type "xbm")
725                         ;; xbm images require special handling, since
726                         ;; the only way to create glyphs from these
727                         ;; (without a ton of work) is to write them
728                         ;; out to a file, and then create a file
729                         ;; specifier.
730                         (let ((file (make-temp-name
731                                      (expand-file-name "emm.xbm"
732                                                        mm-tmp-directory))))
733                           (unwind-protect
734                               (progn
735                                 (write-region (point-min) (point-max) file)
736                                 (make-glyph (list (cons 'x file))))
737                             (ignore-errors
738                               (delete-file file)))))
739                        (t
740                         (make-glyph
741                          (vector (intern type) :data (buffer-string)))))))
742             (mm-handle-set-cache handle spec))))))
743
744 (defun mm-image-fit-p (handle)
745   "Say whether the image in HANDLE will fit the current window."
746   (let ((image (mm-get-image handle)))
747     (or mm-inline-large-images
748         (and (< (glyph-width image) (window-pixel-width))
749              (< (glyph-height image) (window-pixel-height))))))
750
751 (defun mm-valid-image-format-p (format)
752   "Say whether FORMAT can be displayed natively by Emacs."
753   (and (fboundp 'valid-image-instantiator-format-p)
754        (valid-image-instantiator-format-p format)))
755
756 (defun mm-valid-and-fit-image-p (format handle)
757   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
758   (and window-system
759        (mm-valid-image-format-p format)
760        (mm-image-fit-p handle)))
761
762 (provide 'mm-decode)
763
764 ;; mm-decode.el ends here