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