* rfc2047.el (rfc2047-encode-region): Insert a space before encoding.
[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           (if (and (eq beg (nth 1 word)) (nth 2 word))
219               (progn
220                 ;; There might be a bug in Emacs Mule.
221                 ;; A space must be inserted before encoding.
222                 (goto-char beg)
223                 (insert " ")
224                 (rfc2047-encode (1+ beg) (1+ end) current))
225             (rfc2047-encode beg end current)))
226         (setq current (nth 2 word)
227               beg (nth 0 word)
228               end (nth 1 word))))
229     (when current
230       (rfc2047-encode beg end current))))
231
232 (defun rfc2047-encode-string (string)
233   "Encode words in STRING."
234   (with-temp-buffer
235     (insert string)
236     (rfc2047-encode-region (point-min) (point-max))
237     (buffer-string)))
238
239 (defun rfc2047-encode (b e charset)
240   "Encode the word in the region with CHARSET."
241   (let* ((mime-charset (mm-mime-charset charset))
242          (encoding (or (cdr (assq mime-charset
243                                   rfc2047-charset-encoding-alist))
244                        'B))
245          (start (concat
246                  "=?" (downcase (symbol-name mime-charset)) "?"
247                  (downcase (symbol-name encoding)) "?"))
248          (first t))
249     (save-restriction
250       (narrow-to-region b e)
251       (when (eq encoding 'B)
252         ;; break into lines before encoding
253         (goto-char (point-min))
254         (while (not (eobp))
255           (goto-char (min (point-max) (+ 15 (point))))
256           (unless (eobp)
257             (insert "\n"))))
258       (if (and (mm-multibyte-p)
259                (mm-coding-system-p mime-charset))
260           (mm-encode-coding-region (point-min) (point-max) mime-charset))
261       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
262                (point-min) (point-max))
263       (goto-char (point-min))
264       (while (not (eobp))
265         (unless first
266           (insert " "))
267         (setq first nil)
268         (insert start)
269         (end-of-line)
270         (insert "?=")
271         (forward-line 1)))))
272
273 (defun rfc2047-fold-region (b e)
274   "Fold the long lines in the region."
275   (save-restriction
276     (narrow-to-region b e)
277     (goto-char (point-min))
278     (let ((break nil))
279       (while (not (eobp))
280         (cond
281          ((memq (char-after) '(?  ?\t))
282           (setq break (point)))
283          ((and (not break)
284                (looking-at "=\\?"))
285           (setq break (point)))
286          ((and break
287                (looking-at "\\?=")
288                (> (- (point) (save-excursion (beginning-of-line) (point))) 76))
289           (goto-char break)
290           (setq break nil)
291           (insert "\n ")))
292         (unless (eobp)
293           (forward-char 1))))))
294
295 (defun rfc2047-b-encode-region (b e)
296   "Encode the header contained in REGION with the B encoding."
297   (save-restriction
298     (narrow-to-region (goto-char b) e)
299     (while (not (eobp))
300       (base64-encode-region (point) (progn (end-of-line) (point)) t)
301       (if (and (bolp) (eolp))
302           (delete-backward-char 1))
303       (forward-line))))
304
305 (defun rfc2047-q-encode-region (b e)
306   "Encode the header contained in REGION with the Q encoding."
307   (save-excursion
308     (save-restriction
309       (narrow-to-region (goto-char b) e)
310       (let ((alist rfc2047-q-encoding-alist))
311         (while alist
312           (when (looking-at (caar alist))
313             (quoted-printable-encode-region b e nil (cdar alist))
314             (subst-char-in-region (point-min) (point-max) ?  ?_)
315             (setq alist nil))
316           (pop alist))
317         (goto-char (point-min))
318         (while (not (eobp))
319           (goto-char (min (point-max) (+ 64 (point))))
320           (search-backward "=" (- (point) 2) t)
321           (unless (eobp)
322             (insert "\n")))))))
323
324 ;;;
325 ;;; Functions for decoding RFC2047 messages
326 ;;;
327
328 (defvar rfc2047-encoded-word-regexp
329   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
330
331 (defun rfc2047-decode-region (start end)
332   "Decode MIME-encoded words in region between START and END."
333   (interactive "r")
334   (let ((case-fold-search t)
335         b e)
336     (save-excursion
337       (save-restriction
338         (narrow-to-region start end)
339         (goto-char (point-min))
340         ;; Remove whitespace between encoded words.
341         (while (re-search-forward
342                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
343                         "\\(\n?[ \t]\\)+"
344                         "\\(" rfc2047-encoded-word-regexp "\\)")
345                 nil t)
346           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
347         ;; Decode the encoded words.
348         (setq b (goto-char (point-min)))
349         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
350           (setq e (match-beginning 0))
351           (insert (rfc2047-parse-and-decode
352                    (prog1
353                        (match-string 0)
354                      (delete-region (match-beginning 0) (match-end 0)))))
355           (when (and (mm-multibyte-p)
356                      mail-parse-charset
357                      (not (eq mail-parse-charset 'gnus-decoded)))
358             (mm-decode-coding-region b e mail-parse-charset))
359           (setq b (point)))
360         (when (and (mm-multibyte-p)
361                    mail-parse-charset
362                    (not (eq mail-parse-charset 'us-ascii))
363                    (not (eq mail-parse-charset 'gnus-decoded)))
364           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
365
366 (defun rfc2047-decode-string (string)
367   "Decode the quoted-printable-encoded STRING and return the results."
368   (let ((m (mm-multibyte-p)))
369     (with-temp-buffer
370       (when m
371         (mm-enable-multibyte))
372       (insert string)
373       (inline
374         (rfc2047-decode-region (point-min) (point-max)))
375       (buffer-string))))
376
377 (defun rfc2047-parse-and-decode (word)
378   "Decode WORD and return it if it is an encoded word.
379 Return WORD if not."
380   (if (not (string-match rfc2047-encoded-word-regexp word))
381       word
382     (or
383      (condition-case nil
384          (rfc2047-decode
385           (match-string 1 word)
386           (upcase (match-string 2 word))
387           (match-string 3 word))
388        (error word))
389      word)))
390
391 (defun rfc2047-decode (charset encoding string)
392   "Decode STRING that uses CHARSET with ENCODING.
393 Valid ENCODINGs are \"B\" and \"Q\".
394 If your Emacs implementation can't decode CHARSET, it returns nil."
395   (if (stringp charset)
396       (setq charset (intern (downcase charset))))
397   (if (or (not charset) 
398           (eq 'gnus-all mail-parse-ignored-charsets)
399           (memq 'gnus-all mail-parse-ignored-charsets)
400           (memq charset mail-parse-ignored-charsets))
401       (setq charset mail-parse-charset))
402   (let ((cs (mm-charset-to-coding-system charset)))
403     (if (and (not cs) charset 
404              (listp mail-parse-ignored-charsets)
405              (memq 'gnus-unknown mail-parse-ignored-charsets))
406         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
407     (when cs
408       (when (and (eq cs 'ascii)
409                  mail-parse-charset)
410         (setq cs mail-parse-charset))
411       (mm-decode-coding-string
412        (cond
413         ((equal "B" encoding)
414          (base64-decode-string string))
415         ((equal "Q" encoding)
416          (quoted-printable-decode-string
417           (mm-replace-chars-in-string string ?_ ? )))
418         (t (error "Invalid encoding: %s" encoding)))
419        cs))))
420
421 (provide 'rfc2047)
422
423 ;;; rfc2047.el ends here