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