750240d892b6c8874c205c2315e3dd8a3b5c2048
[gnus] / lisp / mm-encode.el
1 ;;; mm-encode.el --- Functions for encoding MIME things
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (eval-when-compile (require 'cl))
28 (require 'mail-parse)
29 (require 'mailcap)
30 (eval-and-compile
31   (autoload 'mm-body-7-or-8 "mm-bodies")
32   (autoload 'mm-long-lines-p "mm-bodies"))
33
34 (defcustom mm-content-transfer-encoding-defaults
35   '(("text/x-patch" 8bit)
36     ("text/.*" qp-or-base64)
37     ("message/rfc822" 8bit)
38     ("application/emacs-lisp" qp-or-base64)
39     ("application/x-emacs-lisp" qp-or-base64)
40     ("application/x-patch" qp-or-base64)
41     (".*" base64))
42   "Alist of regexps that match MIME types and their encodings.
43 If the encoding is `qp-or-base64', then either quoted-printable
44 or base64 will be used, depending on what is more efficient.
45
46 `qp-or-base64' has another effect.  It will fold long lines so that
47 MIME parts may not be broken by MTA.  So do `quoted-printable' and
48 `base64'.
49
50 Note: It affects body encoding only when a part is a raw forwarded
51 message (which will be made by `gnus-summary-mail-forward' with the
52 arg 2 for example) or is neither the text/* type nor the message/*
53 type.  Even though in those cases, you can use the `encoding' MML tag
54 to specify encoding of non-ASCII MIME parts."
55   :type '(repeat (list (regexp :tag "MIME type")
56                        (choice :tag "encoding"
57                                (const 7bit)
58                                (const 8bit)
59                                (const qp-or-base64)
60                                (const quoted-printable)
61                                (const base64))))
62   :group 'mime)
63
64 (defvar mm-use-ultra-safe-encoding nil
65   "If non-nil, use encodings aimed at Procrustean bed survival.
66
67 This means that textual parts are encoded as quoted-printable if they
68 contain lines longer than 76 characters or starting with \"From \" in
69 the body.  Non-7bit encodings (8bit, binary) are generally disallowed.
70 This is to reduce the probability that a broken MTA or MDA changes the
71 message.
72
73 This variable should never be set directly, but bound before a call to
74 `mml-generate-mime' or similar functions.")
75
76 (defun mm-insert-rfc822-headers (charset encoding)
77   "Insert text/plain headers with CHARSET and ENCODING."
78   (insert "MIME-Version: 1.0\n")
79   (insert "Content-Type: text/plain; charset="
80           (mail-quote-string (downcase (symbol-name charset))) "\n")
81   (insert "Content-Transfer-Encoding: "
82           (downcase (symbol-name encoding)) "\n"))
83
84 (defun mm-insert-multipart-headers ()
85   "Insert multipart/mixed headers."
86   (let ((boundary "=-=-="))
87     (insert "MIME-Version: 1.0\n")
88     (insert "Content-Type: multipart/mixed; boundary=\"" boundary "\"\n")
89     boundary))
90
91 (defun mm-default-file-encoding (file)
92   "Return a default encoding for FILE."
93   (if (not (string-match "\\.[^.]+$" file))
94       "application/octet-stream"
95     (mailcap-extension-to-mime (match-string 0 file))))
96
97 (defun mm-safer-encoding (encoding &optional type)
98   "Return an encoding similar to ENCODING but safer than it."
99   (cond
100    ((eq encoding '7bit) '7bit) ;; 7bit is considered safe.
101    ((memq encoding '(8bit quoted-printable))
102     ;; According to RFC2046, 5.2.1, RFC822 Subtype, "quoted-printable" is not
103     ;; a valid encoding for message/rfc822:
104     ;; No encoding other than "7bit", "8bit", or "binary" is permitted for the
105     ;; body of a "message/rfc822" entity.
106     (if (string= type "message/rfc822") '8bit 'quoted-printable))
107    ;; The remaining encodings are binary and base64 (and perhaps some
108    ;; non-standard ones), which are both turned into base64.
109    (t (if (string= type "message/rfc822") 'binary 'base64))))
110
111 (defun mm-encode-content-transfer-encoding (encoding &optional type)
112   "Encode the current buffer with ENCODING for MIME type TYPE.
113 ENCODING can be: nil (do nothing); one of `quoted-printable', `base64';
114 `7bit', `8bit' or `binary' (all do nothing); a function to do the encoding."
115   (cond
116    ((eq encoding 'quoted-printable)
117     ;; This used to try to make a multibyte buffer unibyte.  That's
118     ;; completely wrong, since you'd get QP-encoded emacs-mule.  If
119     ;; this gets run on multibyte text it's an error that needs
120     ;; fixing, and the encoding function will signal an error.
121     ;; Likewise base64 below.
122     (quoted-printable-encode-region (point-min) (point-max) t))
123    ((eq encoding 'base64)
124     (when (string-match "\\`text/" type)
125       (goto-char (point-min))
126       (while (search-forward "\n" nil t)
127         (replace-match "\r\n" t t)))
128     (base64-encode-region (point-min) (point-max)))
129    ((memq encoding '(7bit 8bit binary))
130     ;; Do nothing.
131     )
132    ((null encoding)
133     ;; Do nothing.
134     )
135    ;; Fixme: Ignoring errors here looks bogus.
136    ((functionp encoding)
137     (ignore-errors (funcall encoding (point-min) (point-max))))
138    (t
139     (error "Unknown encoding %s" encoding))))
140
141 (defun mm-encode-buffer (type)
142   "Encode the buffer which contains data of MIME type TYPE.
143 TYPE is a string or a list of the components.
144 The encoding used is returned."
145   (let* ((mime-type (if (stringp type) type (car type)))
146          (encoding
147           (or (and (listp type)
148                    (cadr (assq 'encoding type)))
149               (mm-content-transfer-encoding mime-type)))
150          (bits (mm-body-7-or-8)))
151     ;; We force buffers that are 7bit to be unencoded, no matter
152     ;; what the preferred encoding is.
153     ;; Only if the buffers don't contain lone lines.
154     (when (and (eq bits '7bit) (not (mm-long-lines-p 76)))
155       (setq encoding bits))
156     (mm-encode-content-transfer-encoding encoding mime-type)
157     encoding))
158
159 (defun mm-insert-headers (type encoding &optional file)
160   "Insert headers for TYPE."
161   (insert "Content-Type: " type)
162   (when file
163     (insert ";\n\tname=\"" (file-name-nondirectory file) "\""))
164   (insert "\n")
165   (insert (format "Content-Transfer-Encoding: %s\n" encoding))
166   (insert "Content-Disposition: inline")
167   (when file
168     (insert ";\n\tfilename=\"" (file-name-nondirectory file) "\""))
169   (insert "\n")
170   (insert "\n"))
171
172 (defun mm-content-transfer-encoding (type)
173   "Return a CTE suitable for TYPE to encode the current buffer."
174   (let ((rules mm-content-transfer-encoding-defaults))
175     (catch 'found
176       (while rules
177         (when (string-match (caar rules) type)
178           (throw 'found
179                  (let ((encoding
180                         (if (eq (cadr (car rules)) 'qp-or-base64)
181                             (mm-qp-or-base64)
182                           (cadr (car rules)))))
183                    (if mm-use-ultra-safe-encoding
184                        (mm-safer-encoding encoding type)
185                      encoding))))
186         (pop rules)))))
187
188 (defun mm-qp-or-base64 ()
189   "Return the type with which to encode the buffer.
190 This is either `base64' or `quoted-printable'."
191   (if (equal mm-use-ultra-safe-encoding '(sign . "pgp"))
192       ;; perhaps not always accurate?
193       'quoted-printable
194     (save-excursion
195       (let ((limit (min (point-max) (+ 2000 (point-min))))
196             (n8bit 0))
197         (goto-char (point-min))
198         (skip-chars-forward "\x20-\x7f\r\n\t" limit)
199         (while (< (point) limit)
200           (incf n8bit)
201           (forward-char 1)
202           (skip-chars-forward "\x20-\x7f\r\n\t" limit))
203         (if (or (< (* 6 n8bit) (- limit (point-min)))
204                 ;; Don't base64, say, a short line with a single
205                 ;; non-ASCII char when splitting parts by charset.
206                 (= n8bit 1))
207             'quoted-printable
208           'base64)))))
209
210 (provide 'mm-encode)
211
212 ;; arch-tag: 7d01bba4-d469-4851-952b-dc863f84ed66
213 ;;; mm-encode.el ends here