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