5d44dc32c80cea599ca68f8c3c76583541ef2bc8
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
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 (eval-and-compile
28   (eval
29    '(unless (fboundp 'base64-decode-string)
30       (require 'base64))))
31
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       (when rfc2047-default-charset
134         (encode-coding-region (point-min) (point-max)
135                               rfc2047-default-charset)))))
136
137 (defun rfc2047-encodable-p ()
138   "Say whether the current (narrowed) buffer contains characters that need encoding."
139   (let ((charsets (mapcar
140                    'mm-mule-charset-to-mime-charset
141                    (mm-find-charset-region (point-min) (point-max))))
142         (cs (list 'us-ascii rfc2047-default-charset))
143         found)
144     (while charsets
145       (unless (memq (pop charsets) cs)
146         (setq found t)))
147     found))
148
149 (defun rfc2047-dissect-region (b e)
150   "Dissect the region between B and E into words."
151   (let (words)
152     (save-restriction
153       (narrow-to-region b e)
154       (goto-char (point-min))
155       (while (re-search-forward
156               (concat "[^" ietf-drums-tspecials " \t\n]+") nil t)
157         (push
158          (list (match-beginning 0) (match-end 0)
159                (car (delq 'ascii (mm-find-charset-region
160                                   (match-beginning 0) (match-end 0)))))
161          words))
162       words)))
163
164 (defun rfc2047-encode-region (b e)
165   "Encode all encodable words in REGION."
166   (let ((words (rfc2047-dissect-region b e))
167         beg end current word)
168     (while (setq word (pop words))
169       (if (equal (nth 2 word) current)
170           (setq beg (nth 0 word))
171         (when current
172           (rfc2047-encode beg end current))
173         (setq current (nth 2 word)
174               beg (nth 0 word)
175               end (nth 1 word))))
176     (when current
177       (rfc2047-encode beg end current))))
178
179 (defun rfc2047-encode-string (string)
180   "Encode words in STRING."
181   (with-temp-buffer
182     (insert string)
183     (rfc2047-encode-region (point-min) (point-max))
184     (buffer-string)))
185
186 (defun rfc2047-encode (b e charset)
187   "Encode the word in the region with CHARSET."
188   (let* ((mime-charset
189           (mm-mime-charset charset b e))
190          (encoding (or (cdr (assq mime-charset
191                               rfc2047-charset-encoding-alist))
192                        'B))
193          (start (concat
194                  "=?" (downcase (symbol-name mime-charset)) "?"
195                  (downcase (symbol-name encoding)) "?"))
196          (first t))
197     (save-restriction
198       (narrow-to-region b e)
199       (mm-encode-coding-region b e mime-charset)
200       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
201                (point-min) (point-max))
202       (goto-char (point-min))
203       (while (not (eobp))
204         (unless first
205           (insert " "))
206         (setq first nil)
207         (insert start)
208         (end-of-line)
209         (insert "?=")
210         (forward-line 1)))))
211
212 (defun rfc2047-b-encode-region (b e)
213   "Encode the header contained in REGION with the B encoding."
214   (base64-encode-region b e t)
215   (goto-char (point-min))
216   (while (not (eobp))
217     (goto-char (min (point-max) (+ 64 (point))))
218     (unless (eobp)
219       (insert "\n"))))
220
221 (defun rfc2047-q-encode-region (b e)
222   "Encode the header contained in REGION with the Q encoding."
223   (save-excursion
224     (save-restriction
225       (narrow-to-region (goto-char b) e)
226       (let ((alist rfc2047-q-encoding-alist))
227         (while alist
228           (when (looking-at (caar alist))
229             (quoted-printable-encode-region b e nil (cdar alist))
230             (subst-char-in-region (point-min) (point-max) ?  ?_)
231             (setq alist nil))
232           (pop alist))
233         (goto-char (point-min))
234         (while (not (eobp))
235           (goto-char (min (point-max) (+ 64 (point))))
236           (search-backward "=" (- (point) 2) t)
237           (unless (eobp)
238             (insert "\n")))))))
239
240 ;;;
241 ;;; Functions for decoding RFC2047 messages
242 ;;;
243
244 (defvar rfc2047-encoded-word-regexp
245   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
246
247 (defun rfc2047-decode-region (start end)
248   "Decode MIME-encoded words in region between START and END."
249   (interactive "r")
250   (let ((case-fold-search t)
251         b e)
252     (save-excursion
253       (save-restriction
254         (narrow-to-region start end)
255         (goto-char (point-min))
256         ;; Remove whitespace between encoded words.
257         (while (re-search-forward
258                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
259                         "\\(\n?[ \t]\\)+"
260                         "\\(" rfc2047-encoded-word-regexp "\\)")
261                 nil t)
262           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
263         ;; Decode the encoded words.
264         (setq b (goto-char (point-min)))
265         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
266           (setq e (match-beginning 0))
267           (insert (rfc2047-parse-and-decode
268                    (prog1
269                        (match-string 0)
270                      (delete-region (match-beginning 0) (match-end 0)))))
271           (when (and (mm-multibyte-p) rfc2047-default-charset)
272             (mm-decode-coding-region b e rfc2047-default-charset))
273           (setq b (point)))
274         (when (and (mm-multibyte-p)
275                    rfc2047-default-charset
276                    (not (eq rfc2047-default-charset 'us-ascii)))
277           (mm-decode-coding-region b (point-max) rfc2047-default-charset))))))
278
279 (defun rfc2047-decode-string (string)
280   "Decode the quoted-printable-encoded STRING and return the results."
281   (let ((m (mm-multibyte-p)))
282     (with-temp-buffer
283       (when m
284         (mm-enable-multibyte))
285       (insert string)
286       (inline
287         (rfc2047-decode-region (point-min) (point-max)))
288       (buffer-string))))
289  
290 (defun rfc2047-parse-and-decode (word)
291   "Decode WORD and return it if it is an encoded word.
292 Return WORD if not."
293   (if (not (string-match rfc2047-encoded-word-regexp word))
294       word
295     (or
296      (condition-case nil
297          (rfc2047-decode
298           (match-string 1 word)
299           (upcase (match-string 2 word))
300           (match-string 3 word))
301        (error word))
302      word)))
303
304 (defun rfc2047-decode (charset encoding string)
305   "Decode STRING that uses CHARSET with ENCODING.
306 Valid ENCODINGs are \"B\" and \"Q\".
307 If your Emacs implementation can't decode CHARSET, it returns nil."
308   (let ((cs (let ((mm-default-charset rfc2047-default-charset))
309               (mm-charset-to-coding-system charset))))
310     (when cs
311       (when (eq cs 'ascii)
312         (setq cs rfc2047-default-charset))
313       (mm-decode-coding-string
314        (cond
315         ((equal "B" encoding)
316          (base64-decode-string string))
317         ((equal "Q" encoding)
318          (quoted-printable-decode-string
319           (mm-replace-chars-in-string string ?_ ? )))
320         (t (error "Invalid encoding: %s" encoding)))
321        cs))))
322
323 (provide 'rfc2047)
324
325 ;;; rfc2047.el ends here