a85f6a5fcaf348ef2026e4ab9482a540571237d7
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
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 'base64)
28 (require 'qp)
29 (require 'mm-util)
30
31 (defvar rfc2047-unencoded-charsets '(ascii latin-iso8859-1)
32   "List of MULE charsets not to encode.")
33
34 (defvar rfc2047-header-encoding-alist
35   '(("Newsgroups" . nil)
36     ("Message-ID" . nil)
37     (t . mime))
38   "*Header/encoding method alist.
39 The list is traversed sequentially.  The keys can either be
40 header regexps or `t'.
41
42 The values can be:
43
44 1) nil, in which case no encoding is done;
45 2) `mime', in which case the header will be encoded according to RFC2047;
46 3) a charset, in which case it will be encoded as that charse;
47 4) `default', in which case the field will be encoded as the rest
48    of the article.")
49
50 (defvar rfc2047-charset-encoding-alist
51   '((us-ascii . nil)
52     (iso-8859-1 . Q)
53     (iso-8859-2 . Q)
54     (iso-8859-3 . Q)
55     (iso-8859-4 . Q)
56     (iso-8859-5 . Q)
57     (koi8-r . Q)
58     (iso-8859-7 . Q)
59     (iso-8859-8 . Q)
60     (iso-8859-9 . Q)
61     (iso-2022-jp . B)
62     (iso-2022-kr . B)
63     (gb2312 . B)
64     (cn-gb . B)
65     (cn-gb-2312 . B)
66     (euc-kr . B)
67     (iso-2022-jp-2 . B)
68     (iso-2022-int-1 . B))
69   "Alist of MIME charsets to RFC2047 encodings.
70 Valid encodings are nil, `Q' and `B'.")
71
72 (defvar rfc2047-encoding-function-alist
73   '((Q . rfc2047-q-encode-region)
74     (B . base64-encode-region)
75     (nil . ignore))
76   "Alist of RFC2047 encodings to encoding functions.")
77
78 (defvar rfc2047-q-encoding-alist
79   '(("\\(From\\|Cc\\|To\\|Bcc\||Reply-To\\):" . "[^-A-Za-z0-9!*+/=_]")
80     ("." . "[\000-\007\013\015-\037\200-\377=_?]"))
81   "Alist of header regexps and valid Q characters.")
82
83 ;;;
84 ;;; Functions for encoding RFC2047 messages
85 ;;;
86
87 (defun rfc2047-narrow-to-field ()
88   "Narrow the buffer to the header on the current line."
89   (beginning-of-line)
90   (narrow-to-region
91    (point)
92    (progn
93      (forward-line 1)
94      (if (re-search-forward "^[^ \n\t]" nil t)
95          (progn
96            (beginning-of-line)
97            (point))
98        (point-max))))
99   (goto-char (point-min)))
100
101 ;;;###autoload
102 (defun rfc2047-encode-message-header ()
103   "Encode the message header according to `rfc2047-header-encoding-alist'.
104 Should be called narrowed to the head of the message."
105   (interactive "*")
106   (when (featurep 'mule)
107     (save-excursion
108       (let ((alist rfc2047-header-encoding-alist)
109             elem method)
110         (while (not (eobp))
111           (save-restriction
112             (rfc2047-narrow-to-field)
113             (when (rfc2047-encodable-p)
114               ;; We found something that may perhaps be encoded.
115               (while (setq elem (pop alist))
116                 (when (or (and (stringp (car elem))
117                                (looking-at (car elem)))
118                           (eq (car elem) t))
119                   (setq alist nil
120                         method (cdr elem))))
121               (when method
122                 (cond
123                  ((eq method 'mime)
124                   (rfc2047-encode-region (point-min) (point-max)))
125                  ;; Hm.
126                  (t))))
127             (goto-char (point-max))))))))
128
129 (defun rfc2047-encodable-p ()
130   "Say whether the current (narrowed) buffer contains characters that need encoding."
131   (let ((charsets (find-charset-region (point-min) (point-max)))
132         (cs rfc2047-unencoded-charsets)
133         found)
134     (while charsets
135       (unless (memq (pop charsets) cs)
136         (setq found t)))
137     found))
138
139 (defun rfc2047-encode-region (b e)
140   "Encode all encodable words in REGION."
141   (let (prev c start qstart qprev qend)
142     (save-excursion
143       (goto-char b)
144       (while (re-search-forward "[^ \t\n]+" nil t)
145         (save-restriction
146           (narrow-to-region (match-beginning 0) (match-end 0))
147           (goto-char (setq start (point-min)))
148           (setq prev nil)
149           (while (not (eobp))
150             (unless (eq (setq c (char-charset (following-char))) 'ascii)
151               (cond
152                ((eq c prev)
153                 )
154                ((null prev)
155                 (setq qstart (or qstart start)
156                       qend (point-max)
157                       qprev c)
158                 (setq prev c))
159                (t
160                 ;(rfc2047-encode start (setq start (point)) prev)
161                 (setq prev c))))
162             (forward-char 1)))
163         (when (and (not prev) qstart)
164           (rfc2047-encode qstart qend qprev)
165           (setq qstart nil)))
166       (when qstart
167         (rfc2047-encode qstart qend qprev)
168         (setq qstart nil)))))
169
170 (defun rfc2047-encode-string (string)
171   "Encode words in STRING."
172   (with-temp-buffer
173     (insert string)
174     (rfc2047-encode-region (point-min) (point-max))
175     (buffer-string)))
176
177 (defun rfc2047-encode (b e charset)
178   "Encode the word in the region with CHARSET."
179   (let* ((mime-charset (mm-mule-charset-to-mime-charset charset))
180          (encoding (cdr (assq mime-charset
181                               rfc2047-charset-encoding-alist)))
182          (start (concat
183                  "=?" (downcase (symbol-name mime-charset)) "?"
184                  (downcase (symbol-name encoding)) "?")))
185     (save-restriction
186       (narrow-to-region b e)
187       (mm-encode-coding-region b e mime-charset)
188       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
189                (point-min) (point-max))
190       (goto-char (point-min))
191       (insert start)
192       (goto-char (point-max))
193       (insert "?=")
194       ;; Encoded words can't be more than 75 chars long, so we have to
195       ;; split the long ones up.
196       (end-of-line)
197       (while (> (current-column) 74)
198         (beginning-of-line)
199         (forward-char 73)
200         (insert "?=\n " start)
201         (end-of-line)))))
202
203 (defun rfc2047-q-encode-region (b e)
204   "Encode the header contained in REGION with the Q encoding."
205   (save-excursion
206     (save-restriction
207       (narrow-to-region (goto-char b) e)
208       (let ((alist rfc2047-q-encoding-alist))
209         (while alist
210           (when (looking-at (caar alist))
211             (quoted-printable-encode-region b e nil (cdar alist))
212             (subst-char-in-region (point-min) (point-max) ?  ?_))
213           (pop alist))))))
214
215 ;;;
216 ;;; Functions for decoding RFC2047 messages
217 ;;;
218
219 (defvar rfc2047-encoded-word-regexp
220   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~]+\\)\\?=")
221
222 ;;;###autoload
223 (defun rfc2047-decode-region (start end)
224   "Decode MIME-encoded words in region between START and END."
225   (interactive "r")
226   (save-excursion
227     (save-restriction
228       (narrow-to-region start end)
229       (goto-char (point-min))
230       ;; Remove whitespace between encoded words.
231       (while (re-search-forward
232               (concat "\\(" rfc2047-encoded-word-regexp "\\)"
233                       "\\(\n?[ \t]\\)+"
234                       "\\(" rfc2047-encoded-word-regexp "\\)")
235               nil t)
236         (delete-region (goto-char (match-end 1)) (match-beginning 6)))
237       ;; Decode the encoded words.
238       (goto-char (point-min))
239       (while (re-search-forward rfc2047-encoded-word-regexp nil t)
240         (insert (rfc2047-parse-and-decode
241                  (prog1
242                      (match-string 0)
243                    (delete-region (match-beginning 0) (match-end 0)))))))))
244
245 ;;;###autoload
246 (defun rfc2047-decode-string (string)
247  "Decode the quoted-printable-encoded STRING and return the results."
248  (with-temp-buffer
249    (mm-enable-multibyte)
250    (insert string)
251    (inline
252      (rfc2047-decode-region (point-min) (point-max)))
253    (buffer-string)))
254
255 (defun rfc2047-parse-and-decode (word)
256   "Decode WORD and return it if it is an encoded word.
257 Return WORD if not."
258   (if (not (string-match rfc2047-encoded-word-regexp word))
259       word
260     (or
261      (condition-case nil
262          (rfc2047-decode
263           (match-string 1 word)
264           (upcase (match-string 2 word))
265           (match-string 3 word))
266        (error word))
267      word)))
268
269 (defun rfc2047-decode (charset encoding string)
270   "Decode STRING that uses CHARSET with ENCODING.
271 Valid ENCODINGs are \"B\" and \"Q\".
272 If your Emacs implementation can't decode CHARSET, it returns nil."
273   (let ((cs (mm-charset-to-coding-system charset)))
274     (when cs
275       (mm-decode-coding-string
276        (cond
277         ((equal "B" encoding)
278          (base64-decode string))
279         ((equal "Q" encoding)
280          (quoted-printable-decode-string
281           (mm-replace-chars-in-string string ?_ ? )))
282         (t (error "Invalid encoding: %s" encoding)))
283        cs))))
284
285 (provide 'rfc2047)
286
287 ;;; rfc2047.el ends here