907a084036529e333a2b97b5898b5694204d4b9e
[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 . B)
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 . rfc2047-b-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-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           (or
185            (coding-system-get
186             (get-charset-property charset 'prefered-coding-system)
187             'mime-charset)
188            (car (memq charset (find-coding-systems-region 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     (save-restriction
196       (narrow-to-region b e)
197       (mm-encode-coding-region b e mime-charset)
198       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
199                (point-min) (point-max))
200       (goto-char (point-min))
201       (insert start)
202       (goto-char (point-max))
203       (insert "?=")
204       ;; Encoded words can't be more than 75 chars long, so we have to
205       ;; split the long ones up.
206       (end-of-line)
207       (while (> (current-column) 74)
208         (beginning-of-line)
209         (forward-char 73)
210         (insert "?=\n " start)
211         (end-of-line)))))
212
213 (defun rfc2047-b-encode-region (b e)
214   "Encode the header contained in REGION with the B encoding."
215   (base64-encode-region b e t))
216
217 (defun rfc2047-q-encode-region (b e)
218   "Encode the header contained in REGION with the Q encoding."
219   (save-excursion
220     (save-restriction
221       (narrow-to-region (goto-char b) e)
222       (let ((alist rfc2047-q-encoding-alist))
223         (while alist
224           (when (looking-at (caar alist))
225             (quoted-printable-encode-region b e nil (cdar alist))
226             (subst-char-in-region (point-min) (point-max) ?  ?_))
227           (pop alist))))))
228
229 ;;;
230 ;;; Functions for decoding RFC2047 messages
231 ;;;
232
233 (defvar rfc2047-encoded-word-regexp
234   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ ]+\\)\\?=")
235
236 ;;;###autoload
237 (defun rfc2047-decode-region (start end)
238   "Decode MIME-encoded words in region between START and END."
239   (interactive "r")
240   (let ((case-fold-search t)
241         b e)
242     (save-excursion
243       (save-restriction
244         (narrow-to-region start end)
245         (goto-char (point-min))
246         ;; Remove whitespace between encoded words.
247         (while (re-search-forward
248                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
249                         "\\(\n?[ \t]\\)+"
250                         "\\(" rfc2047-encoded-word-regexp "\\)")
251                 nil t)
252           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
253         ;; Decode the encoded words.
254         (setq b (goto-char (point-min)))
255         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
256           (setq e (match-beginning 0))
257           (insert (rfc2047-parse-and-decode
258                    (prog1
259                        (match-string 0)
260                      (delete-region (match-beginning 0) (match-end 0)))))
261           (mm-decode-coding-region b e rfc2047-default-charset)
262           (setq b (point)))
263         (mm-decode-coding-region b (point-max) rfc2047-default-charset)))))
264
265 ;;;###autoload
266 (defun rfc2047-decode-string (string)
267  "Decode the quoted-printable-encoded STRING and return the results."
268  (with-temp-buffer
269    (mm-enable-multibyte)
270    (insert string)
271    (inline
272      (rfc2047-decode-region (point-min) (point-max)))
273    (buffer-string)))
274
275 (defun rfc2047-parse-and-decode (word)
276   "Decode WORD and return it if it is an encoded word.
277 Return WORD if not."
278   (if (not (string-match rfc2047-encoded-word-regexp word))
279       word
280     (or
281      (condition-case nil
282          (rfc2047-decode
283           (match-string 1 word)
284           (upcase (match-string 2 word))
285           (match-string 3 word))
286        (error word))
287      word)))
288
289 (defun rfc2047-decode (charset encoding string)
290   "Decode STRING that uses CHARSET with ENCODING.
291 Valid ENCODINGs are \"B\" and \"Q\".
292 If your Emacs implementation can't decode CHARSET, it returns nil."
293   (let ((cs (mm-charset-to-coding-system charset)))
294     (when cs
295       (mm-decode-coding-string
296        (cond
297         ((equal "B" encoding)
298          (if (fboundp 'base64-decode-string)
299              (base64-decode-string string)
300            (base64-decode string)))
301         ((equal "Q" encoding)
302          (quoted-printable-decode-string
303           (mm-replace-chars-in-string string ?_ ? )))
304         (t (error "Invalid encoding: %s" encoding)))
305        cs))))
306
307 (provide 'rfc2047)
308
309 ;;; rfc2047.el ends here