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