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