Post to non-ascii groups.
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000 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 (require 'mail-prsvr)
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 charset;
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 . B)
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\011\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   (save-excursion
109     (goto-char (point-min))
110     (let (alist elem method)
111       (while (not (eobp))
112         (save-restriction
113           (rfc2047-narrow-to-field)
114           (if (not (rfc2047-encodable-p))
115               (if (and (eq (mm-body-7-or-8) '8bit)
116                        (mm-multibyte-p)
117                        (mm-coding-system-p
118                         (car message-posting-charset)))
119                        ;; 8 bit must be decoded.
120                        ;; Is message-posting-charset a coding system?
121                        (mm-encode-coding-region 
122                         (point-min) (point-max) 
123                         (car message-posting-charset)))
124             ;; We found something that may perhaps be encoded.
125             (setq method nil
126                   alist rfc2047-header-encoding-alist)
127             (while (setq elem (pop alist))
128               (when (or (and (stringp (car elem))
129                              (looking-at (car elem)))
130                         (eq (car elem) t))
131                 (setq alist nil
132                       method (cdr elem))))
133             (cond
134              ((eq method 'mime)
135               (rfc2047-encode-region (point-min) (point-max))
136               (rfc2047-fold-region (point-min) (point-max)))
137              ((eq method 'default)
138               (if (and (featurep 'mule)
139                        mail-parse-charset)
140                   (mm-encode-coding-region (point-min) (point-max) 
141                                            mail-parse-charset)))
142              ((mm-coding-system-p method)
143               (if (featurep 'mule)
144                   (mm-encode-coding-region (point-min) (point-max) method)))
145              ;; Hm.
146              (t)))
147           (goto-char (point-max)))))))
148
149 (defun rfc2047-encodable-p (&optional header)
150   "Say whether the current (narrowed) buffer contains characters that need encoding in headers."
151   (let ((charsets
152          (mapcar
153           'mm-mime-charset
154           (mm-find-charset-region (point-min) (point-max))))
155         (cs (list 'us-ascii (car message-posting-charset)))
156         found)
157     (while charsets
158       (unless (memq (pop charsets) cs)
159         (setq found t)))
160     found))
161
162 (defun rfc2047-dissect-region (b e)
163   "Dissect the region between B and E into words."
164   (let ((all-specials (concat ietf-drums-tspecials " \t\n\r"))
165         (special-list (mapcar 'identity ietf-drums-tspecials))
166         (blank-list '(?  ?\t ?\n ?\r))
167         words current cs state mail-parse-mule-charset)
168     (save-restriction
169       (narrow-to-region b e)
170       (goto-char (point-min))
171       (skip-chars-forward all-specials)
172       (setq b (point))
173       (while (not (eobp))
174         (cond
175          ((not state)
176           (setq state 'word)
177           (if (not (eq (setq cs (mm-charset-after)) 'ascii))
178               (setq current cs))
179           (setq b (point)))
180          ((eq state 'blank)
181           (cond 
182            ((memq (char-after) special-list)
183             (setq state nil))
184            ((memq (char-after) blank-list))
185            (t
186             (setq state 'word)
187             (unless b
188                 (setq b (point)))
189             (if (not (eq (setq cs (mm-charset-after)) 'ascii))
190                 (setq current cs)))))
191          ((eq state 'word)
192           (cond 
193            ((memq (char-after) special-list)
194             (setq state nil)
195             (push (list b (point) current) words)
196             (setq current nil))
197            ((memq (char-after) blank-list)
198             (setq state 'blank)
199             (if (not current)
200                 (setq b nil)
201               (push (list b (point) current) words)
202               (setq b (point))
203               (setq current nil)))
204            ((or (eq (setq cs (mm-charset-after)) 'ascii)
205                 (if current
206                     (eq current cs)
207                   (setq current cs))))
208            (t
209             (push (list b (point) current) words)
210             (setq current cs)
211             (setq b (point))))))
212         (if state
213             (forward-char)
214           (skip-chars-forward all-specials)))
215       (if (eq state 'word)
216           (push (list b (point) current) words)))
217     words))
218
219 (defun rfc2047-encode-region (b e)
220   "Encode all encodable words in REGION."
221   (let ((words (rfc2047-dissect-region b e))
222         beg end current word)
223     (while (setq word (pop words))
224       (if (equal (nth 2 word) current)
225           (setq beg (nth 0 word))
226         (when current
227           (if (and (eq beg (nth 1 word)) (nth 2 word))
228               (progn
229                 ;; There might be a bug in Emacs Mule.
230                 ;; A space must be inserted before encoding.
231                 (goto-char beg)
232                 (insert " ")
233                 (rfc2047-encode (1+ beg) (1+ end) current))
234             (rfc2047-encode beg end current)))
235         (setq current (nth 2 word)
236               beg (nth 0 word)
237               end (nth 1 word))))
238     (when current
239       (rfc2047-encode beg end current))))
240
241 (defun rfc2047-encode-string (string)
242   "Encode words in STRING."
243   (with-temp-buffer
244     (insert string)
245     (rfc2047-encode-region (point-min) (point-max))
246     (buffer-string)))
247
248 (defun rfc2047-encode (b e charset)
249   "Encode the word in the region with CHARSET."
250   (let* ((mime-charset (mm-mime-charset charset))
251          (encoding (or (cdr (assq mime-charset
252                                   rfc2047-charset-encoding-alist))
253                        'B))
254          (start (concat
255                  "=?" (downcase (symbol-name mime-charset)) "?"
256                  (downcase (symbol-name encoding)) "?"))
257          (first t))
258     (save-restriction
259       (narrow-to-region b e)
260       (when (eq encoding 'B)
261         ;; break into lines before encoding
262         (goto-char (point-min))
263         (while (not (eobp))
264           (goto-char (min (point-max) (+ 15 (point))))
265           (unless (eobp)
266             (insert "\n"))))
267       (if (and (mm-multibyte-p)
268                (mm-coding-system-p mime-charset))
269           (mm-encode-coding-region (point-min) (point-max) mime-charset))
270       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
271                (point-min) (point-max))
272       (goto-char (point-min))
273       (while (not (eobp))
274         (unless first
275           (insert " "))
276         (setq first nil)
277         (insert start)
278         (end-of-line)
279         (insert "?=")
280         (forward-line 1)))))
281
282 (defun rfc2047-fold-region (b e)
283   "Fold the long lines in the region."
284   (save-restriction
285     (narrow-to-region b e)
286     (goto-char (point-min))
287     (let ((break nil))
288       (while (not (eobp))
289         (cond
290          ((memq (char-after) '(?  ?\t))
291           (setq break (point)))
292          ((and (not break)
293                (looking-at "=\\?"))
294           (setq break (point)))
295          ((and break
296                (looking-at "\\?=")
297                (> (- (point) (save-excursion (beginning-of-line) (point))) 76))
298           (goto-char break)
299           (setq break nil)
300           (insert "\n ")))
301         (unless (eobp)
302           (forward-char 1))))))
303
304 (defun rfc2047-b-encode-region (b e)
305   "Encode the header contained in REGION with the B encoding."
306   (save-restriction
307     (narrow-to-region (goto-char b) e)
308     (while (not (eobp))
309       (base64-encode-region (point) (progn (end-of-line) (point)) t)
310       (if (and (bolp) (eolp))
311           (delete-backward-char 1))
312       (forward-line))))
313
314 (defun rfc2047-q-encode-region (b e)
315   "Encode the header contained in REGION with the Q encoding."
316   (save-excursion
317     (save-restriction
318       (narrow-to-region (goto-char b) e)
319       (let ((alist rfc2047-q-encoding-alist))
320         (while alist
321           (when (looking-at (caar alist))
322             (quoted-printable-encode-region b e nil (cdar alist))
323             (subst-char-in-region (point-min) (point-max) ?  ?_)
324             (setq alist nil))
325           (pop alist))
326         (goto-char (point-min))
327         (while (not (eobp))
328           (goto-char (min (point-max) (+ 64 (point))))
329           (search-backward "=" (- (point) 2) t)
330           (unless (eobp)
331             (insert "\n")))))))
332
333 ;;;
334 ;;; Functions for decoding RFC2047 messages
335 ;;;
336
337 (defvar rfc2047-encoded-word-regexp
338   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
339
340 (defun rfc2047-decode-region (start end)
341   "Decode MIME-encoded words in region between START and END."
342   (interactive "r")
343   (let ((case-fold-search t)
344         b e)
345     (save-excursion
346       (save-restriction
347         (narrow-to-region start end)
348         (goto-char (point-min))
349         ;; Remove whitespace between encoded words.
350         (while (re-search-forward
351                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
352                         "\\(\n?[ \t]\\)+"
353                         "\\(" rfc2047-encoded-word-regexp "\\)")
354                 nil t)
355           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
356         ;; Decode the encoded words.
357         (setq b (goto-char (point-min)))
358         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
359           (setq e (match-beginning 0))
360           (insert (rfc2047-parse-and-decode
361                    (prog1
362                        (match-string 0)
363                      (delete-region (match-beginning 0) (match-end 0)))))
364           (when (and (mm-multibyte-p)
365                      mail-parse-charset
366                      (not (eq mail-parse-charset 'gnus-decoded)))
367             (mm-decode-coding-region b e mail-parse-charset))
368           (setq b (point)))
369         (when (and (mm-multibyte-p)
370                    mail-parse-charset
371                    (not (eq mail-parse-charset 'us-ascii))
372                    (not (eq mail-parse-charset 'gnus-decoded)))
373           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
374
375 (defun rfc2047-decode-string (string)
376   "Decode the quoted-printable-encoded STRING and return the results."
377   (let ((m (mm-multibyte-p)))
378     (with-temp-buffer
379       (when m
380         (mm-enable-multibyte))
381       (insert string)
382       (inline
383         (rfc2047-decode-region (point-min) (point-max)))
384       (buffer-string))))
385
386 (defun rfc2047-parse-and-decode (word)
387   "Decode WORD and return it if it is an encoded word.
388 Return WORD if not."
389   (if (not (string-match rfc2047-encoded-word-regexp word))
390       word
391     (or
392      (condition-case nil
393          (rfc2047-decode
394           (match-string 1 word)
395           (upcase (match-string 2 word))
396           (match-string 3 word))
397        (error word))
398      word)))
399
400 (defun rfc2047-decode (charset encoding string)
401   "Decode STRING that uses CHARSET with ENCODING.
402 Valid ENCODINGs are \"B\" and \"Q\".
403 If your Emacs implementation can't decode CHARSET, it returns nil."
404   (if (stringp charset)
405       (setq charset (intern (downcase charset))))
406   (if (or (not charset) 
407           (eq 'gnus-all mail-parse-ignored-charsets)
408           (memq 'gnus-all mail-parse-ignored-charsets)
409           (memq charset mail-parse-ignored-charsets))
410       (setq charset mail-parse-charset))
411   (let ((cs (mm-charset-to-coding-system charset)))
412     (if (and (not cs) charset 
413              (listp mail-parse-ignored-charsets)
414              (memq 'gnus-unknown mail-parse-ignored-charsets))
415         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
416     (when cs
417       (when (and (eq cs 'ascii)
418                  mail-parse-charset)
419         (setq cs mail-parse-charset))
420       (mm-decode-coding-string
421        (cond
422         ((equal "B" encoding)
423          (base64-decode-string string))
424         ((equal "Q" encoding)
425          (quoted-printable-decode-string
426           (mm-replace-chars-in-string string ?_ ? )))
427         (t (error "Invalid encoding: %s" encoding)))
428        cs))))
429
430 (provide 'rfc2047)
431
432 ;;; rfc2047.el ends here