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