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