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