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