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