Fix my last change.
[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           (bol (save-restriction
290                  (widen)
291                  (gnus-point-at-bol))))
292       (while (not (eobp))
293         (when (and break (> (- (point) bol) 76))
294           (goto-char break)
295           (setq break nil)
296           (insert "\n ")
297           (setq bol (1- (point)))
298           ;; Don't break before the first non-LWSP characters.
299           (skip-chars-forward " \t")
300           (forward-char 1))
301         (cond
302          ((eq (char-after) ?\n)
303           (forward-char 1)
304           (setq bol (point))
305           (skip-chars-forward " \t")
306           (unless (or (eobp) (eq (char-after) ?\n))
307             (forward-char 1)))
308          ((eq (char-after) ?\r)
309           (forward-char 1))
310          ((memq (char-after) '(?  ?\t))
311           (skip-chars-forward " \t")
312           (setq break (1- (point))))
313          ((not break)
314           (if (not (looking-at "=\\?"))
315               (if (eq (char-after) ?=)
316                   (forward-char 1)
317                 (skip-chars-forward "^ \t="))
318             (setq break (point))
319             (skip-chars-forward "^ \t")))
320          (t
321           (skip-chars-forward "^ \t")))))))
322
323 (defun rfc2047-unfold-region (b e)
324   "Fold the long lines in the region."
325   (save-restriction
326     (narrow-to-region b e)
327     (goto-char (point-min))
328     (let ((bol (save-restriction
329                  (widen)
330                  (gnus-point-at-bol)))
331           (eol (gnus-point-at-eol))
332           leading)
333       (forward-line 1)
334       (while (not (eobp))
335         (looking-at "[ \t]*")
336         (setq leading (- (match-end 0) (match-beginning 0)))
337         (if (< (- (gnus-point-at-eol) bol leading) 76)
338             (progn
339               (goto-char eol)
340               (delete-region eol (progn 
341                                    (skip-chars-forward "[ \t\n\r]+")
342                                    (1- (point)))))
343           (setq bol (gnus-point-at-bol)))
344         (setq eol (gnus-point-at-eol))
345         (forward-line 1)))))
346
347 (defun rfc2047-b-encode-region (b e)
348   "Encode the header contained in REGION with the B encoding."
349   (save-restriction
350     (narrow-to-region (goto-char b) e)
351     (while (not (eobp))
352       (base64-encode-region (point) (progn (end-of-line) (point)) t)
353       (if (and (bolp) (eolp))
354           (delete-backward-char 1))
355       (forward-line))))
356
357 (defun rfc2047-q-encode-region (b e)
358   "Encode the header contained in REGION with the Q encoding."
359   (save-excursion
360     (save-restriction
361       (narrow-to-region (goto-char b) e)
362       (let ((alist rfc2047-q-encoding-alist))
363         (while alist
364           (when (looking-at (caar alist))
365             (quoted-printable-encode-region b e nil (cdar alist))
366             (subst-char-in-region (point-min) (point-max) ?  ?_)
367             (setq alist nil))
368           (pop alist))
369         (goto-char (1+ (point-min)))
370         (while (and (not (bobp)) (not (eobp)))
371           (goto-char (min (point-max) (save-restriction
372                                         (widen)
373                                         ;; THe QP encapsulation is about 20. 
374                                         (+ 56 (gnus-point-at-bol)))))
375           (search-backward "=" (- (point) 2) t)
376           (unless (or (bobp) (eobp))
377             (insert "\n")))))))
378
379 ;;;
380 ;;; Functions for decoding RFC2047 messages
381 ;;;
382
383 (defvar rfc2047-encoded-word-regexp
384   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
385
386 (defun rfc2047-decode-region (start end)
387   "Decode MIME-encoded words in region between START and END."
388   (interactive "r")
389   (let ((case-fold-search t)
390         b e)
391     (save-excursion
392       (save-restriction
393         (narrow-to-region start end)
394         (goto-char (point-min))
395         ;; Remove whitespace between encoded words.
396         (while (re-search-forward
397                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
398                         "\\(\n?[ \t]\\)+"
399                         "\\(" rfc2047-encoded-word-regexp "\\)")
400                 nil t)
401           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
402         ;; Decode the encoded words.
403         (setq b (goto-char (point-min)))
404         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
405           (setq e (match-beginning 0))
406           (insert (rfc2047-parse-and-decode
407                    (prog1
408                        (match-string 0)
409                      (delete-region (match-beginning 0) (match-end 0)))))
410           (when (and (mm-multibyte-p)
411                      mail-parse-charset
412                      (not (eq mail-parse-charset 'gnus-decoded)))
413             (mm-decode-coding-region b e mail-parse-charset))
414           (setq b (point)))
415         (when (and (mm-multibyte-p)
416                    mail-parse-charset
417                    (not (eq mail-parse-charset 'us-ascii))
418                    (not (eq mail-parse-charset 'gnus-decoded)))
419           (mm-decode-coding-region b (point-max) mail-parse-charset))
420         (rfc2047-unfold-region (point-min) (point-max))))))
421
422 (defun rfc2047-decode-string (string)
423   "Decode the quoted-printable-encoded STRING and return the results."
424   (let ((m (mm-multibyte-p)))
425     (with-temp-buffer
426       (when m
427         (mm-enable-multibyte))
428       (insert string)
429       (inline
430         (rfc2047-decode-region (point-min) (point-max)))
431       (buffer-string))))
432
433 (defun rfc2047-parse-and-decode (word)
434   "Decode WORD and return it if it is an encoded word.
435 Return WORD if not."
436   (if (not (string-match rfc2047-encoded-word-regexp word))
437       word
438     (or
439      (condition-case nil
440          (rfc2047-decode
441           (match-string 1 word)
442           (upcase (match-string 2 word))
443           (match-string 3 word))
444        (error word))
445      word)))
446
447 (defun rfc2047-decode (charset encoding string)
448   "Decode STRING that uses CHARSET with ENCODING.
449 Valid ENCODINGs are \"B\" and \"Q\".
450 If your Emacs implementation can't decode CHARSET, it returns nil."
451   (if (stringp charset)
452       (setq charset (intern (downcase charset))))
453   (if (or (not charset) 
454           (eq 'gnus-all mail-parse-ignored-charsets)
455           (memq 'gnus-all mail-parse-ignored-charsets)
456           (memq charset mail-parse-ignored-charsets))
457       (setq charset mail-parse-charset))
458   (let ((cs (mm-charset-to-coding-system charset)))
459     (if (and (not cs) charset 
460              (listp mail-parse-ignored-charsets)
461              (memq 'gnus-unknown mail-parse-ignored-charsets))
462         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
463     (when cs
464       (when (and (eq cs 'ascii)
465                  mail-parse-charset)
466         (setq cs mail-parse-charset))
467       (mm-with-unibyte-current-buffer 
468         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
469         (mm-decode-coding-string
470          (cond
471           ((equal "B" encoding)
472            (base64-decode-string string))
473           ((equal "Q" encoding)
474            (quoted-printable-decode-string
475             (mm-replace-chars-in-string string ?_ ? )))
476           (t (error "Invalid encoding: %s" encoding)))
477          cs)))))
478
479 (provide 'rfc2047)
480
481 ;;; rfc2047.el ends here