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