Synch with Gnus.
[elisp/gnus.git-] / 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-when-compile (require 'cl))
28 (eval-and-compile
29   (eval
30    '(unless (fboundp 'base64-decode-string)
31       (require 'base64))))
32
33 (require 'qp)
34 (require 'mm-util)
35 (require 'ietf-drums)
36 (require 'mail-prsvr)
37
38 (defvar rfc2047-header-encoding-alist
39   '(("Newsgroups" . nil)
40     ("Message-ID" . nil)
41     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
42      "-A-Za-z0-9!*+/=_")
43     (t . mime))
44   "*Header/encoding method alist.
45 The list is traversed sequentially.  The keys can either be
46 header regexps or `t'.
47
48 The values can be:
49
50 1) nil, in which case no encoding is done;
51 2) `mime', in which case the header will be encoded according to RFC2047;
52 3) a charset, in which case it will be encoded as that charset;
53 4) `default', in which case the field will be encoded as the rest
54    of the article.
55 5) a string, like `mime', expect for using it as word-chars.")
56
57 (defvar rfc2047-charset-encoding-alist
58   '((us-ascii . nil)
59     (iso-8859-1 . Q)
60     (iso-8859-2 . Q)
61     (iso-8859-3 . Q)
62     (iso-8859-4 . Q)
63     (iso-8859-5 . B)
64     (koi8-r . B)
65     (iso-8859-7 . Q)
66     (iso-8859-8 . Q)
67     (iso-8859-9 . Q)
68     (iso-8859-14 . Q)
69     (iso-8859-15 . Q)
70     (iso-2022-jp . B)
71     (iso-2022-kr . B)
72     (gb2312 . B)
73     (cn-gb . B)
74     (cn-gb-2312 . B)
75     (euc-kr . B)
76     (iso-2022-jp-2 . B)
77     (iso-2022-int-1 . B))
78   "Alist of MIME charsets to RFC2047 encodings.
79 Valid encodings are nil, `Q' and `B'.")
80
81 (defvar rfc2047-encoding-function-alist
82   '((Q . rfc2047-q-encode-region)
83     (B . rfc2047-b-encode-region)
84     (nil . ignore))
85   "Alist of RFC2047 encodings to encoding functions.")
86
87 (defvar rfc2047-q-encoding-alist
88   '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):" 
89      . "-A-Za-z0-9!*+/" )
90     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
91     ;; Avoid using 8bit characters. Some versions of Emacs has bug!
92     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
93     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
94   "Alist of header regexps and valid Q characters.")
95
96 ;;;
97 ;;; Functions for encoding RFC2047 messages
98 ;;;
99
100 (defun rfc2047-narrow-to-field ()
101   "Narrow the buffer to the header on the current line."
102   (beginning-of-line)
103   (narrow-to-region
104    (point)
105    (progn
106      (forward-line 1)
107      (if (re-search-forward "^[^ \n\t]" nil t)
108          (progn
109            (beginning-of-line)
110            (point))
111        (point-max))))
112   (goto-char (point-min)))
113
114 (defun rfc2047-encode-message-header ()
115   "Encode the message header according to `rfc2047-header-encoding-alist'.
116 Should be called narrowed to the head of the message."
117   (interactive "*")
118   (save-excursion
119     (goto-char (point-min))
120     (let (alist elem method)
121       (while (not (eobp))
122         (save-restriction
123           (rfc2047-narrow-to-field)
124           (if (not (rfc2047-encodable-p))
125               (if (and (eq (mm-body-7-or-8) '8bit)
126                        (mm-multibyte-p)
127                        (mm-coding-system-p
128                         (car message-posting-charset)))
129                        ;; 8 bit must be decoded.
130                        ;; Is message-posting-charset a coding system?
131                        (mm-encode-coding-region 
132                         (point-min) (point-max) 
133                         (car message-posting-charset)))
134             ;; We found something that may perhaps be encoded.
135             (setq method nil
136                   alist rfc2047-header-encoding-alist)
137             (while (setq elem (pop alist))
138               (when (or (and (stringp (car elem))
139                              (looking-at (car elem)))
140                         (eq (car elem) t))
141                 (setq alist nil
142                       method (cdr elem))))
143             (cond
144              ((stringp method)
145               (rfc2047-encode-region (point-min) (point-max) method))
146              ((eq method 'mime)
147               (rfc2047-encode-region (point-min) (point-max)))
148              ((eq method 'default)
149               (if (and (featurep 'mule)
150                        mail-parse-charset)
151                   (mm-encode-coding-region (point-min) (point-max) 
152                                            mail-parse-charset)))
153              ((null method)
154               (and (delq 'ascii 
155                          (mm-find-charset-region (point-min) 
156                                                  (point-max)))
157                    (if (or (message-options-get
158                             'rfc2047-encode-message-header-encode-any) 
159                            (message-options-set
160                             'rfc2047-encode-message-header-encode-any
161                             (y-or-n-p 
162                              "Some texts are not encoded. Encode anyway?")))
163                        (rfc2047-encode-region (point-min) (point-max))
164                      (error "Cannot send unencoded text."))))
165              ((mm-coding-system-p method)
166               (if (featurep 'mule)
167                   (mm-encode-coding-region (point-min) (point-max) method)))
168              ;; Hm.
169              (t)))
170           (goto-char (point-max)))))))
171
172 (defun rfc2047-encodable-p (&optional header)
173   "Say whether the current (narrowed) buffer contains characters that need encoding in headers."
174   (let ((charsets
175          (mapcar
176           'mm-mime-charset
177           (mm-find-charset-region (point-min) (point-max))))
178         (cs (list 'us-ascii (car message-posting-charset)))
179         found)
180     (while charsets
181       (unless (memq (pop charsets) cs)
182         (setq found t)))
183     found))
184
185 (defun rfc2047-dissect-region (b e &optional word-chars)
186   "Dissect the region between B and E into words."
187   (unless word-chars
188     ;; Anything except most CTLs, WSP
189     (setq word-chars "\010\012\014\041-\177"))
190   (let (mail-parse-mule-charset
191         words point current 
192         result word)
193     (save-restriction
194       (narrow-to-region b e)
195       (goto-char (point-min))
196       (skip-chars-forward "\000-\177")
197       (while (not (eobp))
198         (setq point (point))
199         (skip-chars-backward word-chars b)
200         (unless (eq b (point))
201           (push (cons (buffer-substring b (point)) nil) words)) 
202         (setq b (point))
203         (goto-char point)
204         (setq current (mm-charset-after))
205         (forward-char 1)
206         (skip-chars-forward word-chars)
207         (while (and (not (eobp))
208                     (eq (mm-charset-after) current))
209           (forward-char 1)
210           (skip-chars-forward word-chars))
211         (unless (eq b (point))
212           (push (cons (buffer-substring b (point)) current) words)) 
213         (setq b (point))
214         (skip-chars-forward "\000-\177"))
215       (unless (eq b (point))
216         (push (cons (buffer-substring b (point)) nil) words)))
217     ;; merge adjacent words
218     (setq word (pop words))
219     (while word
220       (if (and (cdr word) 
221                (caar words)
222                (not (cdar words))
223                (not (string-match "[^ \t]" (caar words))))
224           (if (eq (cdr (nth 1 words)) (cdr word))
225               (progn
226                 (setq word (cons (concat 
227                                   (car (nth 1 words)) (caar words) 
228                                   (car word))
229                                  (cdr word)))
230                 (pop words)
231                 (pop words))
232             (push (cons (concat (caar words) (car word)) (cdr word))
233                   result)
234             (pop words)
235             (setq word (pop words)))
236         (push word result)
237         (setq word (pop words))))
238     result))
239
240 (defun rfc2047-encode-region (b e &optional word-chars)
241   "Encode all encodable words in REGION."
242   (let ((words (rfc2047-dissect-region b e word-chars)) word)
243     (save-restriction
244       (narrow-to-region b e)
245       (delete-region (point-min) (point-max))
246       (while (setq word (pop words))
247         (if (not (cdr word))
248             (insert (car word))
249           (rfc2047-fold-region (gnus-point-at-bol) (point))
250           (goto-char (point-max))
251           (if (> (- (point) (save-restriction
252                               (widen)
253                               (gnus-point-at-bol))) 76)
254               (insert "\n "))
255           ;; Insert blank between encoded words
256           (if (eq (char-before) ?=) (insert " ")) 
257           (rfc2047-encode (point) 
258                           (progn (insert (car word)) (point))
259                           (cdr word))))
260       (rfc2047-fold-region (point-min) (point-max)))))
261
262 (defun rfc2047-encode-string (string &optional word-chars)
263   "Encode words in STRING."
264   (with-temp-buffer
265     (insert string)
266     (rfc2047-encode-region (point-min) (point-max) word-chars)
267     (buffer-string)))
268
269 (defun rfc2047-encode (b e charset)
270   "Encode the word in the region with CHARSET."
271   (let* ((mime-charset (mm-mime-charset charset))
272          (encoding (or (cdr (assq mime-charset
273                                   rfc2047-charset-encoding-alist))
274                        'B))
275          (start (concat
276                  "=?" (downcase (symbol-name mime-charset)) "?"
277                  (downcase (symbol-name encoding)) "?"))
278          (first t))
279     (save-restriction
280       (narrow-to-region b e)
281       (when (eq encoding 'B)
282         ;; break into lines before encoding
283         (goto-char (point-min))
284         (while (not (eobp))
285           (goto-char (min (point-max) (+ 15 (point))))
286           (unless (eobp)
287             (insert "\n"))))
288       (if (and (mm-multibyte-p)
289                (mm-coding-system-p mime-charset))
290           (mm-encode-coding-region (point-min) (point-max) mime-charset))
291       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
292                (point-min) (point-max))
293       (goto-char (point-min))
294       (while (not (eobp))
295         (unless first
296           (insert " "))
297         (setq first nil)
298         (insert start)
299         (end-of-line)
300         (insert "?=")
301         (forward-line 1)))))
302
303 (defun rfc2047-fold-region (b e)
304   "Fold the long lines in the region."
305   (save-restriction
306     (narrow-to-region b e)
307     (goto-char (point-min))
308     (let ((break nil)
309           (qword-break nil)
310           (bol (save-restriction
311                  (widen)
312                  (gnus-point-at-bol))))
313       (while (not (eobp))
314         (when (and (or break qword-break) (> (- (point) bol) 76))
315           (goto-char (or break qword-break))
316           (setq break nil
317                 qword-break nil)
318           (insert "\n ")
319           (setq bol (1- (point)))
320           ;; Don't break before the first non-LWSP characters.
321           (skip-chars-forward " \t")
322           (forward-char 1))
323         (cond
324          ((eq (char-after) ?\n)
325           (forward-char 1)
326           (setq bol (point)
327                 break nil
328                 qword-break nil)
329           (skip-chars-forward " \t")
330           (unless (or (eobp) (eq (char-after) ?\n))
331             (forward-char 1)))
332          ((eq (char-after) ?\r)
333           (forward-char 1))
334          ((memq (char-after) '(?  ?\t))
335           (skip-chars-forward " \t")
336           (setq break (1- (point))))
337          ((not break)
338           (if (not (looking-at "=\\?[^=]"))
339               (if (eq (char-after) ?=)
340                   (forward-char 1)
341                 (skip-chars-forward "^ \t\n\r="))
342             (setq qword-break (point))
343             (skip-chars-forward "^ \t\n\r")))
344          (t
345           (skip-chars-forward "^ \t\n\r"))))
346       (when (and (or break qword-break) (> (- (point) bol) 76))
347         (goto-char (or break qword-break))
348         (setq break nil
349               qword-break nil)
350         (insert "\n ")
351         (setq bol (1- (point)))
352         ;; Don't break before the first non-LWSP characters.
353         (skip-chars-forward " \t")
354         (forward-char 1)))))
355
356 (defun rfc2047-unfold-region (b e)
357   "Fold the long lines in the region."
358   (save-restriction
359     (narrow-to-region b e)
360     (goto-char (point-min))
361     (let ((bol (save-restriction
362                  (widen)
363                  (gnus-point-at-bol)))
364           (eol (gnus-point-at-eol))
365           leading)
366       (forward-line 1)
367       (while (not (eobp))
368         (looking-at "[ \t]*")
369         (setq leading (- (match-end 0) (match-beginning 0)))
370         (if (< (- (gnus-point-at-eol) bol leading) 76)
371             (progn
372               (goto-char eol)
373               (delete-region eol (progn 
374                                    (skip-chars-forward "[ \t\n\r]+")
375                                    (1- (point)))))
376           (setq bol (gnus-point-at-bol)))
377         (setq eol (gnus-point-at-eol))
378         (forward-line 1)))))
379
380 (defun rfc2047-b-encode-region (b e)
381   "Encode the header contained in REGION with the B encoding."
382   (save-restriction
383     (narrow-to-region (goto-char b) e)
384     (while (not (eobp))
385       (base64-encode-region (point) (progn (end-of-line) (point)) t)
386       (if (and (bolp) (eolp))
387           (delete-backward-char 1))
388       (forward-line))))
389
390 (defun rfc2047-q-encode-region (b e)
391   "Encode the header contained in REGION with the Q encoding."
392   (save-excursion
393     (save-restriction
394       (narrow-to-region (goto-char b) e)
395       (let ((alist rfc2047-q-encoding-alist)
396             (bol (save-restriction
397                    (widen)
398                    (gnus-point-at-bol))))
399         (while alist
400           (when (looking-at (caar alist))
401             (quoted-printable-encode-region b e nil (cdar alist))
402             (subst-char-in-region (point-min) (point-max) ?  ?_)
403             (setq alist nil))
404           (pop alist))
405         ;; The size of QP encapsulation is about 20, so set limit to
406         ;; 56=76-20.
407         (unless (< (- (point-max) (point-min)) 56)
408           ;; Don't break if it could fit in one line.
409           ;; Let rfc2047-encode-region break it later.
410           (goto-char (1+ (point-min)))
411           (while (and (not (bobp)) (not (eobp)))
412             (goto-char (min (point-max) (+ 56 bol)))
413             (search-backward "=" (- (point) 2) t)
414             (unless (or (bobp) (eobp))
415               (insert "\n")
416               (setq bol (point)))))))))
417
418 ;;;
419 ;;; Functions for decoding RFC2047 messages
420 ;;;
421
422 (defvar rfc2047-encoded-word-regexp
423   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?=")
424
425 (defun rfc2047-decode-region (start end)
426   "Decode MIME-encoded words in region between START and END."
427   (interactive "r")
428   (let ((case-fold-search t)
429         b e)
430     (save-excursion
431       (save-restriction
432         (narrow-to-region start end)
433         (goto-char (point-min))
434         ;; Remove whitespace between encoded words.
435         (while (re-search-forward
436                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
437                         "\\(\n?[ \t]\\)+"
438                         "\\(" rfc2047-encoded-word-regexp "\\)")
439                 nil t)
440           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
441         ;; Decode the encoded words.
442         (setq b (goto-char (point-min)))
443         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
444           (setq e (match-beginning 0))
445           (insert (rfc2047-parse-and-decode
446                    (prog1
447                        (match-string 0)
448                      (delete-region (match-beginning 0) (match-end 0)))))
449           (when (and (mm-multibyte-p)
450                      mail-parse-charset
451                      (not (eq mail-parse-charset 'gnus-decoded)))
452             (mm-decode-coding-region b e mail-parse-charset))
453           (setq b (point)))
454         (when (and (mm-multibyte-p)
455                    mail-parse-charset
456                    (not (eq mail-parse-charset 'us-ascii))
457                    (not (eq mail-parse-charset 'gnus-decoded)))
458           (mm-decode-coding-region b (point-max) mail-parse-charset))
459         (rfc2047-unfold-region (point-min) (point-max))))))
460
461 (defun rfc2047-decode-string (string)
462   "Decode the quoted-printable-encoded STRING and return the results."
463   (let ((m (mm-multibyte-p)))
464     (with-temp-buffer
465       (when m
466         (mm-enable-multibyte))
467       (insert string)
468       (inline
469         (rfc2047-decode-region (point-min) (point-max)))
470       (buffer-string))))
471
472 (defun rfc2047-parse-and-decode (word)
473   "Decode WORD and return it if it is an encoded word.
474 Return WORD if not."
475   (if (not (string-match rfc2047-encoded-word-regexp word))
476       word
477     (or
478      (condition-case nil
479          (rfc2047-decode
480           (match-string 1 word)
481           (upcase (match-string 2 word))
482           (match-string 3 word))
483        (error word))
484      word)))
485
486 (defun rfc2047-pad-base64 (string)
487   "Pad STRING to quartets."
488   ;; Be more liberal to accept buggy base64 strings. If
489   ;; base64-decode-string accepts buggy strings, this function could
490   ;; be aliased to identity.
491   (case (mod (length string) 4)
492     (0 string)
493     (1 string) ;; Error, don't pad it.
494     (2 (concat string "=="))
495     (3 (concat string "="))))
496
497 (defun rfc2047-decode (charset encoding string)
498   "Decode STRING that uses CHARSET with ENCODING.
499 Valid ENCODINGs are \"B\" and \"Q\".
500 If your Emacs implementation can't decode CHARSET, it returns nil."
501   (if (stringp charset)
502       (setq charset (intern (downcase charset))))
503   (if (or (not charset) 
504           (eq 'gnus-all mail-parse-ignored-charsets)
505           (memq 'gnus-all mail-parse-ignored-charsets)
506           (memq charset mail-parse-ignored-charsets))
507       (setq charset mail-parse-charset))
508   (let ((cs (mm-charset-to-coding-system charset)))
509     (if (and (not cs) charset 
510              (listp mail-parse-ignored-charsets)
511              (memq 'gnus-unknown mail-parse-ignored-charsets))
512         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
513     (when cs
514       (when (and (eq cs 'ascii)
515                  mail-parse-charset)
516         (setq cs mail-parse-charset))
517       (mm-with-unibyte-current-buffer-mule4
518         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
519         (mm-decode-coding-string
520          (cond
521           ((equal "B" encoding)
522            (base64-decode-string 
523             (rfc2047-pad-base64 string)))
524           ((equal "Q" encoding)
525            (quoted-printable-decode-string
526             (mm-replace-chars-in-string string ?_ ? )))
527           (t (error "Invalid encoding: %s" encoding)))
528          cs)))))
529
530 (provide 'rfc2047)
531
532 ;;; rfc2047.el ends here