* rfc2047.el (rfc2047-encode-message-header): Check the coding-system.
[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-2022-jp . B)
65     (iso-2022-kr . B)
66     (gb2312 . B)
67     (cn-gb . B)
68     (cn-gb-2312 . B)
69     (euc-kr . B)
70     (iso-2022-jp-2 . B)
71     (iso-2022-int-1 . B))
72   "Alist of MIME charsets to RFC2047 encodings.
73 Valid encodings are nil, `Q' and `B'.")
74
75 (defvar rfc2047-encoding-function-alist
76   '((Q . rfc2047-q-encode-region)
77     (B . rfc2047-b-encode-region)
78     (nil . ignore))
79   "Alist of RFC2047 encodings to encoding functions.")
80
81 (defvar rfc2047-q-encoding-alist
82   '(("\\(From\\|Cc\\|To\\|Bcc\||Reply-To\\):" . "-A-Za-z0-9!*+/=_")
83     ("." . "^\000-\007\011\013\015-\037\200-\377=_?"))
84   "Alist of header regexps and valid Q characters.")
85
86 ;;;
87 ;;; Functions for encoding RFC2047 messages
88 ;;;
89
90 (defun rfc2047-narrow-to-field ()
91   "Narrow the buffer to the header on the current line."
92   (beginning-of-line)
93   (narrow-to-region
94    (point)
95    (progn
96      (forward-line 1)
97      (if (re-search-forward "^[^ \n\t]" nil t)
98          (progn
99            (beginning-of-line)
100            (point))
101        (point-max))))
102   (goto-char (point-min)))
103
104 (defun rfc2047-encode-message-header ()
105   "Encode the message header according to `rfc2047-header-encoding-alist'.
106 Should be called narrowed to the head of the message."
107   (interactive "*")
108   (save-excursion
109     (goto-char (point-min))
110     (let ((alist rfc2047-header-encoding-alist)
111           elem method)
112       (while (not (eobp))
113         (save-restriction
114           (rfc2047-narrow-to-field)
115           (if (not (rfc2047-encodable-p))
116               (if (and (eq (mm-body-7-or-8) '8bit)
117                        (mm-multibyte-p)
118                        (mm-coding-system-p
119                         (car message-posting-charset)))
120                        ;; 8 bit must be decoded.
121                        ;; Is message-posting-charset a coding system?
122                        (mm-encode-coding-region 
123                         (point-min) (point-max) 
124                         (car message-posting-charset)))
125             ;; We found something that may perhaps be encoded.
126             (while (setq elem (pop alist))
127               (when (or (and (stringp (car elem))
128                              (looking-at (car elem)))
129                         (eq (car elem) t))
130                 (setq alist nil
131                       method (cdr elem))))
132             (cond
133              ((eq method 'mime)
134               (rfc2047-encode-region (point-min) (point-max))
135               (rfc2047-fold-region (point-min) (point-max)))
136              ;; Hm.
137              (t)))
138           (goto-char (point-max)))))
139     (when mail-parse-charset
140       (mm-encode-coding-region
141        (point-min) (point-max) mail-parse-charset))))
142
143 (defun rfc2047-encodable-p (&optional header)
144   "Say whether the current (narrowed) buffer contains characters that need encoding in headers."
145   (let ((charsets
146          (mapcar
147           'mm-mime-charset
148           (mm-find-charset-region (point-min) (point-max))))
149         (cs (list 'us-ascii (car message-posting-charset)))
150         found)
151     (while charsets
152       (unless (memq (pop charsets) cs)
153         (setq found t)))
154     found))
155
156 (defun rfc2047-dissect-region (b e)
157   "Dissect the region between B and E into words."
158   (let ((all-specials (concat ietf-drums-tspecials " \t\n\r"))
159         (special-list (mapcar 'identity ietf-drums-tspecials))
160         (blank-list '(?  ?\t ?\n ?\r))
161         words current cs state mail-parse-mule-charset)
162     (save-restriction
163       (narrow-to-region b e)
164       (goto-char (point-min))
165       (skip-chars-forward all-specials)
166       (setq b (point))
167       (while (not (eobp))
168         (cond
169          ((not state)
170           (setq state 'word)
171           (if (not (eq (setq cs (mm-charset-after)) 'ascii))
172               (setq current cs))
173           (setq b (point)))
174          ((eq state 'blank)
175           (cond 
176            ((memq (char-after) special-list)
177             (setq state nil))
178            ((memq (char-after) blank-list))
179            (t
180             (setq state 'word)
181             (unless b
182                 (setq b (point)))
183             (if (not (eq (setq cs (mm-charset-after)) 'ascii))
184                 (setq current cs)))))
185          ((eq state 'word)
186           (cond 
187            ((memq (char-after) special-list)
188             (setq state nil)
189             (push (list b (point) current) words)
190             (setq current nil))
191            ((memq (char-after) blank-list)
192             (setq state 'blank)
193             (if (not current)
194                 (setq b nil)
195               (push (list b (point) current) words)
196               (setq b (point))
197               (setq current nil)))
198            ((or (eq (setq cs (mm-charset-after)) 'ascii)
199                 (if current
200                     (eq current cs)
201                   (setq current cs))))
202            (t
203             (push (list b (point) current) words)
204             (setq current cs)
205             (setq b (point))))))
206         (if state
207             (forward-char)
208           (skip-chars-forward all-specials)))
209       (if (eq state 'word)
210           (push (list b (point) current) words)))
211     words))
212
213 (defun rfc2047-encode-region (b e)
214   "Encode all encodable words in REGION."
215   (let ((words (rfc2047-dissect-region b e))
216         beg end current word)
217     (while (setq word (pop words))
218       (if (equal (nth 2 word) current)
219           (setq beg (nth 0 word))
220         (when current
221           (when (prog1 (and (eq beg (nth 1 word)) (nth 2 word))
222                   (rfc2047-encode beg end current))
223             (goto-char beg)
224             (insert " ")))
225         (setq current (nth 2 word)
226               beg (nth 0 word)
227               end (nth 1 word))))
228     (when current
229       (rfc2047-encode beg end current))))
230
231 (defun rfc2047-encode-string (string)
232   "Encode words in STRING."
233   (with-temp-buffer
234     (insert string)
235     (rfc2047-encode-region (point-min) (point-max))
236     (buffer-string)))
237
238 (defun rfc2047-encode (b e charset)
239   "Encode the word in the region with CHARSET."
240   (let* ((mime-charset (mm-mime-charset charset))
241          (encoding (or (cdr (assq mime-charset
242                                   rfc2047-charset-encoding-alist))
243                        'B))
244          (start (concat
245                  "=?" (downcase (symbol-name mime-charset)) "?"
246                  (downcase (symbol-name encoding)) "?"))
247          (first t))
248     (save-restriction
249       (narrow-to-region b e)
250       (when (eq encoding 'B)
251         ;; break into lines before encoding
252         (goto-char (point-min))
253         (while (not (eobp))
254           (goto-char (min (point-max) (+ 15 (point))))
255           (unless (eobp)
256             (insert "\n"))))
257       (mm-encode-coding-region (point-min) (point-max) mime-charset)
258       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
259                (point-min) (point-max))
260       (goto-char (point-min))
261       (while (not (eobp))
262         (unless first
263           (insert " "))
264         (setq first nil)
265         (insert start)
266         (end-of-line)
267         (insert "?=")
268         (forward-line 1)))))
269
270 (defun rfc2047-fold-region (b e)
271   "Fold the long lines in the region."
272   (save-restriction
273     (narrow-to-region b e)
274     (goto-char (point-min))
275     (let ((break nil))
276       (while (not (eobp))
277         (cond
278          ((memq (char-after) '(?  ?\t))
279           (setq break (point)))
280          ((and (not break)
281                (looking-at "=\\?"))
282           (setq break (point)))
283          ((and break
284                (looking-at "\\?=")
285                (> (- (point) (save-excursion (beginning-of-line) (point))) 76))
286           (goto-char break)
287           (setq break nil)
288           (insert "\n ")))
289         (unless (eobp)
290           (forward-char 1))))))
291
292 (defun rfc2047-b-encode-region (b e)
293   "Encode the header contained in REGION with the B encoding."
294   (save-restriction
295     (narrow-to-region (goto-char b) e)
296     (while (not (eobp))
297       (base64-encode-region (point) (progn (end-of-line) (point)) t)
298       (if (and (bolp) (eolp))
299           (delete-backward-char 1))
300       (forward-line))))
301
302 (defun rfc2047-q-encode-region (b e)
303   "Encode the header contained in REGION with the Q encoding."
304   (save-excursion
305     (save-restriction
306       (narrow-to-region (goto-char b) e)
307       (let ((alist rfc2047-q-encoding-alist))
308         (while alist
309           (when (looking-at (caar alist))
310             (quoted-printable-encode-region b e nil (cdar alist))
311             (subst-char-in-region (point-min) (point-max) ?  ?_)
312             (setq alist nil))
313           (pop alist))
314         (goto-char (point-min))
315         (while (not (eobp))
316           (goto-char (min (point-max) (+ 64 (point))))
317           (search-backward "=" (- (point) 2) t)
318           (unless (eobp)
319             (insert "\n")))))))
320
321 ;;;
322 ;;; Functions for decoding RFC2047 messages
323 ;;;
324
325 (defvar rfc2047-encoded-word-regexp
326   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
327
328 (defun rfc2047-decode-region (start end)
329   "Decode MIME-encoded words in region between START and END."
330   (interactive "r")
331   (let ((case-fold-search t)
332         b e)
333     (save-excursion
334       (save-restriction
335         (narrow-to-region start end)
336         (goto-char (point-min))
337         ;; Remove whitespace between encoded words.
338         (while (re-search-forward
339                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
340                         "\\(\n?[ \t]\\)+"
341                         "\\(" rfc2047-encoded-word-regexp "\\)")
342                 nil t)
343           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
344         ;; Decode the encoded words.
345         (setq b (goto-char (point-min)))
346         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
347           (setq e (match-beginning 0))
348           (insert (rfc2047-parse-and-decode
349                    (prog1
350                        (match-string 0)
351                      (delete-region (match-beginning 0) (match-end 0)))))
352           (when (and (mm-multibyte-p)
353                      mail-parse-charset
354                      (not (eq mail-parse-charset 'gnus-decoded)))
355             (mm-decode-coding-region b e mail-parse-charset))
356           (setq b (point)))
357         (when (and (mm-multibyte-p)
358                    mail-parse-charset
359                    (not (eq mail-parse-charset 'us-ascii))
360                    (not (eq mail-parse-charset 'gnus-decoded)))
361           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
362
363 (defun rfc2047-decode-string (string)
364   "Decode the quoted-printable-encoded STRING and return the results."
365   (let ((m (mm-multibyte-p)))
366     (with-temp-buffer
367       (when m
368         (mm-enable-multibyte))
369       (insert string)
370       (inline
371         (rfc2047-decode-region (point-min) (point-max)))
372       (buffer-string))))
373
374 (defun rfc2047-parse-and-decode (word)
375   "Decode WORD and return it if it is an encoded word.
376 Return WORD if not."
377   (if (not (string-match rfc2047-encoded-word-regexp word))
378       word
379     (or
380      (condition-case nil
381          (rfc2047-decode
382           (match-string 1 word)
383           (upcase (match-string 2 word))
384           (match-string 3 word))
385        (error word))
386      word)))
387
388 (defun rfc2047-decode (charset encoding string)
389   "Decode STRING that uses CHARSET with ENCODING.
390 Valid ENCODINGs are \"B\" and \"Q\".
391 If your Emacs implementation can't decode CHARSET, it returns nil."
392   (if (stringp charset)
393       (setq charset (intern (downcase charset))))
394   (if (or (not charset) 
395           (eq 'gnus-all mail-parse-ignored-charsets)
396           (memq 'gnus-all mail-parse-ignored-charsets)
397           (memq charset mail-parse-ignored-charsets))
398       (setq charset mail-parse-charset))
399   (let ((cs (mm-charset-to-coding-system charset)))
400     (if (and (not cs) charset 
401              (listp mail-parse-ignored-charsets)
402              (memq 'gnus-unknown mail-parse-ignored-charsets))
403         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
404     (when cs
405       (when (and (eq cs 'ascii)
406                  mail-parse-charset)
407         (setq cs mail-parse-charset))
408       (mm-decode-coding-string
409        (cond
410         ((equal "B" encoding)
411          (base64-decode-string string))
412         ((equal "Q" encoding)
413          (quoted-printable-decode-string
414           (mm-replace-chars-in-string string ?_ ? )))
415         (t (error "Invalid encoding: %s" encoding)))
416        cs))))
417
418 (provide 'rfc2047)
419
420 ;;; rfc2047.el ends here