Skip LWSP.
[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-and-compile
28   (eval
29    '(unless (fboundp 'base64-decode-string)
30       (require 'base64))))
31
32 (require 'qp)
33 (require 'mm-util)
34 (require 'ietf-drums)
35 (require 'mail-prsvr)
36
37 (defvar rfc2047-header-encoding-alist
38   '(("Newsgroups" . nil)
39     ("Message-ID" . nil)
40     (t . mime))
41   "*Header/encoding method alist.
42 The list is traversed sequentially.  The keys can either be
43 header regexps or `t'.
44
45 The values can be:
46
47 1) nil, in which case no encoding is done;
48 2) `mime', in which case the header will be encoded according to RFC2047;
49 3) a charset, in which case it will be encoded as that charset;
50 4) `default', in which case the field will be encoded as the rest
51    of the article.")
52
53 (defvar rfc2047-charset-encoding-alist
54   '((us-ascii . nil)
55     (iso-8859-1 . Q)
56     (iso-8859-2 . Q)
57     (iso-8859-3 . Q)
58     (iso-8859-4 . Q)
59     (iso-8859-5 . B)
60     (koi8-r . B)
61     (iso-8859-7 . Q)
62     (iso-8859-8 . Q)
63     (iso-8859-9 . Q)
64     (iso-8859-14 . Q)
65     (iso-8859-15 . Q)
66     (iso-2022-jp . B)
67     (iso-2022-kr . B)
68     (gb2312 . B)
69     (cn-gb . B)
70     (cn-gb-2312 . B)
71     (euc-kr . B)
72     (iso-2022-jp-2 . B)
73     (iso-2022-int-1 . B))
74   "Alist of MIME charsets to RFC2047 encodings.
75 Valid encodings are nil, `Q' and `B'.")
76
77 (defvar rfc2047-encoding-function-alist
78   '((Q . rfc2047-q-encode-region)
79     (B . rfc2047-b-encode-region)
80     (nil . ignore))
81   "Alist of RFC2047 encodings to encoding functions.")
82
83 (defvar rfc2047-q-encoding-alist
84   '(("\\(From\\|Cc\\|To\\|Bcc\||Reply-To\\):" . "-A-Za-z0-9!*+/") 
85     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
86     ;; Avoid using 8bit characters. Some versions of Emacs has bug!
87     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
88     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
89   "Alist of header regexps and valid Q characters.")
90
91 ;;;
92 ;;; Functions for encoding RFC2047 messages
93 ;;;
94
95 (defun rfc2047-narrow-to-field ()
96   "Narrow the buffer to the header on the current line."
97   (beginning-of-line)
98   (narrow-to-region
99    (point)
100    (progn
101      (forward-line 1)
102      (if (re-search-forward "^[^ \n\t]" nil t)
103          (progn
104            (beginning-of-line)
105            (point))
106        (point-max))))
107   (goto-char (point-min)))
108
109 (defun rfc2047-encode-message-header ()
110   "Encode the message header according to `rfc2047-header-encoding-alist'.
111 Should be called narrowed to the head of the message."
112   (interactive "*")
113   (save-excursion
114     (goto-char (point-min))
115     (let (alist elem method)
116       (while (not (eobp))
117         (save-restriction
118           (rfc2047-narrow-to-field)
119           (if (not (rfc2047-encodable-p))
120               (if (and (eq (mm-body-7-or-8) '8bit)
121                        (mm-multibyte-p)
122                        (mm-coding-system-p
123                         (car message-posting-charset)))
124                        ;; 8 bit must be decoded.
125                        ;; Is message-posting-charset a coding system?
126                        (mm-encode-coding-region 
127                         (point-min) (point-max) 
128                         (car message-posting-charset)))
129             ;; We found something that may perhaps be encoded.
130             (setq method nil
131                   alist rfc2047-header-encoding-alist)
132             (while (setq elem (pop alist))
133               (when (or (and (stringp (car elem))
134                              (looking-at (car elem)))
135                         (eq (car elem) t))
136                 (setq alist nil
137                       method (cdr elem))))
138             (cond
139              ((eq method 'mime)
140               (rfc2047-encode-region (point-min) (point-max))
141               (rfc2047-fold-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 ((all-specials (concat ietf-drums-tspecials " \t\n\r"))
170         (special-list (mapcar 'identity ietf-drums-tspecials))
171         (blank-list '(?  ?\t ?\n ?\r))
172         words current cs state mail-parse-mule-charset)
173     (save-restriction
174       (narrow-to-region b e)
175       (goto-char (point-min))
176       (skip-chars-forward all-specials)
177       (setq b (point))
178       (while (not (eobp))
179         (cond
180          ((not state)
181           (setq state 'word)
182           (if (not (eq (setq cs (mm-charset-after)) 'ascii))
183               (setq current cs))
184           (setq b (point)))
185          ((eq state 'blank)
186           (cond 
187            ((memq (char-after) special-list)
188             (setq state nil))
189            ((memq (char-after) blank-list))
190            (t
191             (setq state 'word)
192             (unless b
193                 (setq b (point)))
194             (if (not (eq (setq cs (mm-charset-after)) 'ascii))
195                 (setq current cs)))))
196          ((eq state 'word)
197           (cond 
198            ((memq (char-after) special-list)
199             (setq state nil)
200             (push (list b (point) current) words)
201             (setq current nil))
202            ((memq (char-after) blank-list)
203             (setq state 'blank)
204             (if (not current)
205                 (setq b nil)
206               (push (list b (point) current) words)
207               (setq b (point))
208               (setq current nil)))
209            ((or (eq (setq cs (mm-charset-after)) 'ascii)
210                 (if current
211                     (eq current cs)
212                   (setq current cs))))
213            (t
214             (push (list b (point) current) words)
215             (setq current cs)
216             (setq b (point))))))
217         (if state
218             (forward-char)
219           (skip-chars-forward all-specials)))
220       (if (eq state 'word)
221           (push (list b (point) current) words)))
222     words))
223
224 (defun rfc2047-encode-region (b e)
225   "Encode all encodable words in REGION."
226   (let ((words (rfc2047-dissect-region b e))
227         beg end current word)
228     (while (setq word (pop words))
229       (if (and (eq (nth 2 word) current)
230                (eq beg (nth 1 word)))
231           (setq beg (nth 0 word))
232         (when current
233           (if (and (eq beg (nth 1 word)) (nth 2 word))
234               (progn
235                 ;; There might be a bug in Emacs Mule.
236                 ;; A space must be inserted before encoding.
237                 (goto-char beg)
238                 (insert " ")
239                 (rfc2047-encode (1+ beg) (1+ end) current))
240             (rfc2047-encode beg end current)))
241         (setq current (nth 2 word)
242               beg (nth 0 word)
243               end (nth 1 word))))
244     (when current
245       (rfc2047-encode beg end current))))
246
247 (defun rfc2047-encode-string (string)
248   "Encode words in STRING."
249   (with-temp-buffer
250     (insert string)
251     (rfc2047-encode-region (point-min) (point-max))
252     (buffer-string)))
253
254 (defun rfc2047-encode (b e charset)
255   "Encode the word in the region with CHARSET."
256   (let* ((mime-charset (mm-mime-charset charset))
257          (encoding (or (cdr (assq mime-charset
258                                   rfc2047-charset-encoding-alist))
259                        'B))
260          (start (concat
261                  "=?" (downcase (symbol-name mime-charset)) "?"
262                  (downcase (symbol-name encoding)) "?"))
263          (first t))
264     (save-restriction
265       (narrow-to-region b e)
266       (when (eq encoding 'B)
267         ;; break into lines before encoding
268         (goto-char (point-min))
269         (while (not (eobp))
270           (goto-char (min (point-max) (+ 15 (point))))
271           (unless (eobp)
272             (insert "\n"))))
273       (if (and (mm-multibyte-p)
274                (mm-coding-system-p mime-charset))
275           (mm-encode-coding-region (point-min) (point-max) mime-charset))
276       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
277                (point-min) (point-max))
278       (goto-char (point-min))
279       (while (not (eobp))
280         (unless first
281           (insert " "))
282         (setq first nil)
283         (insert start)
284         (end-of-line)
285         (insert "?=")
286         (forward-line 1)))))
287
288 (defun rfc2047-fold-region (b e)
289   "Fold the long lines in the region."
290   (save-restriction
291     (narrow-to-region b e)
292     (goto-char (point-min))
293     (let ((break nil))
294       (while (not (eobp))
295         (cond
296          ((memq (char-after) '(?  ?\t))
297           (setq break (point)))
298          ((and (not break)
299                (looking-at "=\\?"))
300           (setq break (point)))
301          ((and break
302                (looking-at "\\?=")
303                (> (- (point) (gnus-point-at-bol)) 76))
304           (goto-char break)
305           (setq break nil)
306           (insert "\n ")
307           ;; Don't break before the first non-LWSP characters.
308           (skip-chars-forward " \t")
309           (forward-char 1)))
310         (unless (eobp)
311           (forward-char 1))))))
312
313 (defun rfc2047-b-encode-region (b e)
314   "Encode the header contained in REGION with the B encoding."
315   (save-restriction
316     (narrow-to-region (goto-char b) e)
317     (while (not (eobp))
318       (base64-encode-region (point) (progn (end-of-line) (point)) t)
319       (if (and (bolp) (eolp))
320           (delete-backward-char 1))
321       (forward-line))))
322
323 (defun rfc2047-q-encode-region (b e)
324   "Encode the header contained in REGION with the Q encoding."
325   (save-excursion
326     (save-restriction
327       (narrow-to-region (goto-char b) e)
328       (let ((alist rfc2047-q-encoding-alist))
329         (while alist
330           (when (looking-at (caar alist))
331             (quoted-printable-encode-region b e nil (cdar alist))
332             (subst-char-in-region (point-min) (point-max) ?  ?_)
333             (setq alist nil))
334           (pop alist))
335         (goto-char (point-min))
336         (while (not (eobp))
337           (goto-char (min (point-max) (save-restriction
338                                         (widen)
339                                         ;; THe QP encapsulation is about 20. 
340                                         (+ 56 (gnus-point-at-bol)))))
341           (search-backward "=" (- (point) 2) t)
342           (unless (eobp)
343             (insert "\n")))))))
344
345 ;;;
346 ;;; Functions for decoding RFC2047 messages
347 ;;;
348
349 (defvar rfc2047-encoded-word-regexp
350   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
351
352 (defun rfc2047-decode-region (start end)
353   "Decode MIME-encoded words in region between START and END."
354   (interactive "r")
355   (let ((case-fold-search t)
356         b e)
357     (save-excursion
358       (save-restriction
359         (narrow-to-region start end)
360         (goto-char (point-min))
361         ;; Remove whitespace between encoded words.
362         (while (re-search-forward
363                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
364                         "\\(\n?[ \t]\\)+"
365                         "\\(" rfc2047-encoded-word-regexp "\\)")
366                 nil t)
367           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
368         ;; Decode the encoded words.
369         (setq b (goto-char (point-min)))
370         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
371           (setq e (match-beginning 0))
372           (insert (rfc2047-parse-and-decode
373                    (prog1
374                        (match-string 0)
375                      (delete-region (match-beginning 0) (match-end 0)))))
376           (when (and (mm-multibyte-p)
377                      mail-parse-charset
378                      (not (eq mail-parse-charset 'gnus-decoded)))
379             (mm-decode-coding-region b e mail-parse-charset))
380           (setq b (point)))
381         (when (and (mm-multibyte-p)
382                    mail-parse-charset
383                    (not (eq mail-parse-charset 'us-ascii))
384                    (not (eq mail-parse-charset 'gnus-decoded)))
385           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
386
387 (defun rfc2047-decode-string (string)
388   "Decode the quoted-printable-encoded STRING and return the results."
389   (let ((m (mm-multibyte-p)))
390     (with-temp-buffer
391       (when m
392         (mm-enable-multibyte))
393       (insert string)
394       (inline
395         (rfc2047-decode-region (point-min) (point-max)))
396       (buffer-string))))
397
398 (defun rfc2047-parse-and-decode (word)
399   "Decode WORD and return it if it is an encoded word.
400 Return WORD if not."
401   (if (not (string-match rfc2047-encoded-word-regexp word))
402       word
403     (or
404      (condition-case nil
405          (rfc2047-decode
406           (match-string 1 word)
407           (upcase (match-string 2 word))
408           (match-string 3 word))
409        (error word))
410      word)))
411
412 (defun rfc2047-decode (charset encoding string)
413   "Decode STRING that uses CHARSET with ENCODING.
414 Valid ENCODINGs are \"B\" and \"Q\".
415 If your Emacs implementation can't decode CHARSET, it returns nil."
416   (if (stringp charset)
417       (setq charset (intern (downcase charset))))
418   (if (or (not charset) 
419           (eq 'gnus-all mail-parse-ignored-charsets)
420           (memq 'gnus-all mail-parse-ignored-charsets)
421           (memq charset mail-parse-ignored-charsets))
422       (setq charset mail-parse-charset))
423   (let ((cs (mm-charset-to-coding-system charset)))
424     (if (and (not cs) charset 
425              (listp mail-parse-ignored-charsets)
426              (memq 'gnus-unknown mail-parse-ignored-charsets))
427         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
428     (when cs
429       (when (and (eq cs 'ascii)
430                  mail-parse-charset)
431         (setq cs mail-parse-charset))
432       (mm-with-unibyte-current-buffer 
433         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
434         (mm-decode-coding-string
435          (cond
436           ((equal "B" encoding)
437            (base64-decode-string string))
438           ((equal "Q" encoding)
439            (quoted-printable-decode-string
440             (mm-replace-chars-in-string string ?_ ? )))
441           (t (error "Invalid encoding: %s" encoding)))
442          cs)))))
443
444 (provide 'rfc2047)
445
446 ;;; rfc2047.el ends here