2000-10-09 20:09:11 ShengHuo ZHU <zsh@cs.rochester.edu>
[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-8859-14 . Q)
65     (iso-8859-15 . Q)
66     (iso-2022-jp . B)
67     (iso-2022-kr . B)
68     (gb2312 . B)
69     (cn-gb . B)
70     (cn-gb-2312 . B)
71     (euc-kr . B)
72     (iso-2022-jp-2 . B)
73     (iso-2022-int-1 . B))
74   "Alist of MIME charsets to RFC2047 encodings.
75 Valid encodings are nil, `Q' and `B'.")
76
77 (defvar rfc2047-encoding-function-alist
78   '((Q . rfc2047-q-encode-region)
79     (B . rfc2047-b-encode-region)
80     (nil . ignore))
81   "Alist of RFC2047 encodings to encoding functions.")
82
83 (defvar rfc2047-q-encoding-alist
84   '(("\\(From\\|Cc\\|To\\|Bcc\||Reply-To\\):" . "-A-Za-z0-9!*+/") 
85     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
86     ;; Avoid using 8bit characters. Some versions of Emacs has bug!
87     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
88     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
89   "Alist of header regexps and valid Q characters.")
90
91 ;;;
92 ;;; Functions for encoding RFC2047 messages
93 ;;;
94
95 (defun rfc2047-narrow-to-field ()
96   "Narrow the buffer to the header on the current line."
97   (beginning-of-line)
98   (narrow-to-region
99    (point)
100    (progn
101      (forward-line 1)
102      (if (re-search-forward "^[^ \n\t]" nil t)
103          (progn
104            (beginning-of-line)
105            (point))
106        (point-max))))
107   (goto-char (point-min)))
108
109 (defun rfc2047-encode-message-header ()
110   "Encode the message header according to `rfc2047-header-encoding-alist'.
111 Should be called narrowed to the head of the message."
112   (interactive "*")
113   (save-excursion
114     (goto-char (point-min))
115     (let (alist elem method)
116       (while (not (eobp))
117         (save-restriction
118           (rfc2047-narrow-to-field)
119           (if (not (rfc2047-encodable-p))
120               (if (and (eq (mm-body-7-or-8) '8bit)
121                        (mm-multibyte-p)
122                        (mm-coding-system-p
123                         (car message-posting-charset)))
124                        ;; 8 bit must be decoded.
125                        ;; Is message-posting-charset a coding system?
126                        (mm-encode-coding-region 
127                         (point-min) (point-max) 
128                         (car message-posting-charset)))
129             ;; We found something that may perhaps be encoded.
130             (setq method nil
131                   alist rfc2047-header-encoding-alist)
132             (while (setq elem (pop alist))
133               (when (or (and (stringp (car elem))
134                              (looking-at (car elem)))
135                         (eq (car elem) t))
136                 (setq alist nil
137                       method (cdr elem))))
138             (cond
139              ((eq method 'mime)
140               (rfc2047-encode-region (point-min) (point-max)))
141              ((eq method 'default)
142               (if (and (featurep 'mule)
143                        mail-parse-charset)
144                   (mm-encode-coding-region (point-min) (point-max) 
145                                            mail-parse-charset)))
146              ((mm-coding-system-p method)
147               (if (featurep 'mule)
148                   (mm-encode-coding-region (point-min) (point-max) method)))
149              ;; Hm.
150              (t)))
151           (goto-char (point-max)))))))
152
153 (defun rfc2047-encodable-p (&optional header)
154   "Say whether the current (narrowed) buffer contains characters that need encoding in headers."
155   (let ((charsets
156          (mapcar
157           'mm-mime-charset
158           (mm-find-charset-region (point-min) (point-max))))
159         (cs (list 'us-ascii (car message-posting-charset)))
160         found)
161     (while charsets
162       (unless (memq (pop charsets) cs)
163         (setq found t)))
164     found))
165
166 (defun rfc2047-dissect-region (b e)
167   "Dissect the region between B and E into words."
168   (let ((word-chars "-A-Za-z0-9!*+/") 
169         ;; Not using ietf-drums-specials-token makes life simple.
170         mail-parse-mule-charset
171         words point current 
172         result word)
173     (save-restriction
174       (narrow-to-region b e)
175       (goto-char (point-min))
176       (skip-chars-forward "\000-\177")
177       (while (not (eobp))
178         (setq point (point))
179         (skip-chars-backward word-chars b)
180         (unless (eq b (point))
181           (push (cons (buffer-substring b (point)) nil) words)) 
182         (setq b (point))
183         (goto-char point)
184         (setq current (mm-charset-after))
185         (forward-char 1)
186         (skip-chars-forward word-chars)
187         (while (and (not (eobp))
188                     (eq (mm-charset-after) current))
189           (forward-char 1)
190           (skip-chars-forward word-chars))
191         (unless (eq b (point))
192           (push (cons (buffer-substring b (point)) current) words)) 
193         (setq b (point))
194         (skip-chars-forward "\000-\177"))
195       (unless (eq b (point))
196         (push (cons (buffer-substring b (point)) nil) words)))
197     ;; merge adjacent words
198     (setq word (pop words))
199     (while word
200       (if (and (cdr word) 
201                (caar words)
202                (not (cdar words))
203                (string-match "^[ \t]+$" (caar words)))
204           (if (eq (cdr (nth 1 words)) (cdr word))
205               (progn
206                 (setq word (cons (concat 
207                                   (car (nth 1 words)) (caar words) 
208                                   (car word))
209                                  (cdr word)))
210                 (pop words)
211                 (pop words))
212             (push (cons (concat (caar words) (car word)) (cdr word))
213                   result)
214             (pop words)
215             (setq word (pop words)))
216         (push word result)
217         (setq word (pop words))))
218     result))
219
220 (defun rfc2047-encode-region (b e)
221   "Encode all encodable words in REGION."
222   (let ((words (rfc2047-dissect-region b e)) word)
223     (save-restriction
224       (narrow-to-region b e)
225       (delete-region (point-min) (point-max))
226       (while (setq word (pop words))
227         (if (not (cdr word))
228             (insert (car word))
229           (rfc2047-fold-region (gnus-point-at-bol) (point))
230           (goto-char (point-max))
231           (if (> (- (point) (save-restriction
232                               (widen)
233                               (gnus-point-at-bol))) 76)
234               (insert "\n "))
235           ;; Insert blank between encoded words
236           (if (eq (char-before) ?=) (insert " ")) 
237           (rfc2047-encode (point) 
238                           (progn (insert (car word)) (point))
239                           (cdr word))))
240       (rfc2047-fold-region (point-min) (point-max)))))
241
242 (defun rfc2047-encode-string (string)
243   "Encode words in STRING."
244   (with-temp-buffer
245     (insert string)
246     (rfc2047-encode-region (point-min) (point-max))
247     (buffer-string)))
248
249 (defun rfc2047-encode (b e charset)
250   "Encode the word in the region with CHARSET."
251   (let* ((mime-charset (mm-mime-charset charset))
252          (encoding (or (cdr (assq mime-charset
253                                   rfc2047-charset-encoding-alist))
254                        'B))
255          (start (concat
256                  "=?" (downcase (symbol-name mime-charset)) "?"
257                  (downcase (symbol-name encoding)) "?"))
258          (first t))
259     (save-restriction
260       (narrow-to-region b e)
261       (when (eq encoding 'B)
262         ;; break into lines before encoding
263         (goto-char (point-min))
264         (while (not (eobp))
265           (goto-char (min (point-max) (+ 15 (point))))
266           (unless (eobp)
267             (insert "\n"))))
268       (if (and (mm-multibyte-p)
269                (mm-coding-system-p mime-charset))
270           (mm-encode-coding-region (point-min) (point-max) mime-charset))
271       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
272                (point-min) (point-max))
273       (goto-char (point-min))
274       (while (not (eobp))
275         (unless first
276           (insert " "))
277         (setq first nil)
278         (insert start)
279         (end-of-line)
280         (insert "?=")
281         (forward-line 1)))))
282
283 (defun rfc2047-fold-region (b e)
284   "Fold the long lines in the region."
285   (save-restriction
286     (narrow-to-region b e)
287     (goto-char (point-min))
288     (let ((break nil))
289       (while (not (eobp))
290         (when (and break
291                  (> (- (point) (save-restriction
292                                  (widen)
293                                  (gnus-point-at-bol))) 76))
294               (goto-char break)
295               (setq break nil)
296               (insert "\n ")
297               ;; Don't break before the first non-LWSP characters.
298               (skip-chars-forward " \t")
299               (forward-char 1))
300         (cond
301          ((memq (char-after) '(?  ?\t))
302           (skip-chars-forward " \t")
303           (setq break (1- (point))))
304          ((not break)
305           (if (not (looking-at "=\\?"))
306               (skip-chars-forward "^ \t=")
307             (setq break (point))
308             (skip-chars-forward "^ \t")))
309          (t
310           (skip-chars-forward "^ \t")))))))
311
312 (defun rfc2047-unfold-region (b e)
313   "Fold the long lines in the region."
314   (save-restriction
315     (narrow-to-region b e)
316     (goto-char (point-min))
317     (let ((bol (save-restriction
318                  (widen)
319                  (gnus-point-at-bol)))
320           (eol (gnus-point-at-eol))
321           leading)
322       (forward-line 1)
323       (while (not (eobp))
324         (looking-at "[ \t]*")
325         (setq leading (- (match-end 0) (match-beginning 0)))
326         (if (< (- (gnus-point-at-eol) bol leading) 76)
327             (progn
328               (goto-char eol)
329               (delete-region eol (progn 
330                                    (skip-chars-forward "[ \t\n\r]+")
331                                    (1- (point)))))
332           (setq bol (gnus-point-at-bol)))
333         (setq eol (gnus-point-at-eol))
334         (forward-line 1)))))
335
336 (defun rfc2047-b-encode-region (b e)
337   "Encode the header contained in REGION with the B encoding."
338   (save-restriction
339     (narrow-to-region (goto-char b) e)
340     (while (not (eobp))
341       (base64-encode-region (point) (progn (end-of-line) (point)) t)
342       (if (and (bolp) (eolp))
343           (delete-backward-char 1))
344       (forward-line))))
345
346 (defun rfc2047-q-encode-region (b e)
347   "Encode the header contained in REGION with the Q encoding."
348   (save-excursion
349     (save-restriction
350       (narrow-to-region (goto-char b) e)
351       (let ((alist rfc2047-q-encoding-alist))
352         (while alist
353           (when (looking-at (caar alist))
354             (quoted-printable-encode-region b e nil (cdar alist))
355             (subst-char-in-region (point-min) (point-max) ?  ?_)
356             (setq alist nil))
357           (pop alist))
358         (goto-char (1+ (point-min)))
359         (while (and (not (bobp)) (not (eobp)))
360           (goto-char (min (point-max) (save-restriction
361                                         (widen)
362                                         ;; THe QP encapsulation is about 20. 
363                                         (+ 56 (gnus-point-at-bol)))))
364           (search-backward "=" (- (point) 2) t)
365           (unless (or (bobp) (eobp))
366             (insert "\n")))))))
367
368 ;;;
369 ;;; Functions for decoding RFC2047 messages
370 ;;;
371
372 (defvar rfc2047-encoded-word-regexp
373   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
374
375 (defun rfc2047-decode-region (start end)
376   "Decode MIME-encoded words in region between START and END."
377   (interactive "r")
378   (let ((case-fold-search t)
379         b e)
380     (save-excursion
381       (save-restriction
382         (narrow-to-region start end)
383         (goto-char (point-min))
384         ;; Remove whitespace between encoded words.
385         (while (re-search-forward
386                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
387                         "\\(\n?[ \t]\\)+"
388                         "\\(" rfc2047-encoded-word-regexp "\\)")
389                 nil t)
390           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
391         ;; Decode the encoded words.
392         (setq b (goto-char (point-min)))
393         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
394           (setq e (match-beginning 0))
395           (insert (rfc2047-parse-and-decode
396                    (prog1
397                        (match-string 0)
398                      (delete-region (match-beginning 0) (match-end 0)))))
399           (when (and (mm-multibyte-p)
400                      mail-parse-charset
401                      (not (eq mail-parse-charset 'gnus-decoded)))
402             (mm-decode-coding-region b e mail-parse-charset))
403           (setq b (point)))
404         (when (and (mm-multibyte-p)
405                    mail-parse-charset
406                    (not (eq mail-parse-charset 'us-ascii))
407                    (not (eq mail-parse-charset 'gnus-decoded)))
408           (mm-decode-coding-region b (point-max) mail-parse-charset))
409         (rfc2047-unfold-region (point-min) (point-max))))))
410
411 (defun rfc2047-decode-string (string)
412   "Decode the quoted-printable-encoded STRING and return the results."
413   (let ((m (mm-multibyte-p)))
414     (with-temp-buffer
415       (when m
416         (mm-enable-multibyte))
417       (insert string)
418       (inline
419         (rfc2047-decode-region (point-min) (point-max)))
420       (buffer-string))))
421
422 (defun rfc2047-parse-and-decode (word)
423   "Decode WORD and return it if it is an encoded word.
424 Return WORD if not."
425   (if (not (string-match rfc2047-encoded-word-regexp word))
426       word
427     (or
428      (condition-case nil
429          (rfc2047-decode
430           (match-string 1 word)
431           (upcase (match-string 2 word))
432           (match-string 3 word))
433        (error word))
434      word)))
435
436 (defun rfc2047-decode (charset encoding string)
437   "Decode STRING that uses CHARSET with ENCODING.
438 Valid ENCODINGs are \"B\" and \"Q\".
439 If your Emacs implementation can't decode CHARSET, it returns nil."
440   (if (stringp charset)
441       (setq charset (intern (downcase charset))))
442   (if (or (not charset) 
443           (eq 'gnus-all mail-parse-ignored-charsets)
444           (memq 'gnus-all mail-parse-ignored-charsets)
445           (memq charset mail-parse-ignored-charsets))
446       (setq charset mail-parse-charset))
447   (let ((cs (mm-charset-to-coding-system charset)))
448     (if (and (not cs) charset 
449              (listp mail-parse-ignored-charsets)
450              (memq 'gnus-unknown mail-parse-ignored-charsets))
451         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
452     (when cs
453       (when (and (eq cs 'ascii)
454                  mail-parse-charset)
455         (setq cs mail-parse-charset))
456       (mm-with-unibyte-current-buffer 
457         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
458         (mm-decode-coding-string
459          (cond
460           ((equal "B" encoding)
461            (base64-decode-string string))
462           ((equal "Q" encoding)
463            (quoted-printable-decode-string
464             (mm-replace-chars-in-string string ?_ ? )))
465           (t (error "Invalid encoding: %s" encoding)))
466          cs)))))
467
468 (provide 'rfc2047)
469
470 ;;; rfc2047.el ends here