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