(rfc2047-encodable-p): New parameter header used to indicate that only
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998,99 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 charse;
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\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   (when (featurep 'mule)
109     (save-excursion
110       (goto-char (point-min))
111       (let ((alist rfc2047-header-encoding-alist)
112             elem method)
113         (while (not (eobp))
114           (save-restriction
115             (rfc2047-narrow-to-field)
116             (when (rfc2047-encodable-p t)
117               ;; We found something that may perhaps be encoded.
118               (while (setq elem (pop alist))
119                 (when (or (and (stringp (car elem))
120                                (looking-at (car elem)))
121                           (eq (car elem) t))
122                   (setq alist nil
123                         method (cdr elem))))
124               (when method
125                 (cond
126                  ((eq method 'mime)
127                   (rfc2047-encode-region (point-min) (point-max))
128                   (rfc2047-fold-region (point-min) (point-max)))
129                  ;; Hm.
130                  (t))))
131             (goto-char (point-max)))))
132       (when mail-parse-charset
133         (encode-coding-region (point-min) (point-max)
134                               mail-parse-charset)))))
135
136 (defun rfc2047-encodable-p (&optional header)
137   "Say whether the current (narrowed) buffer contains characters that need encoding.
138
139 A non-nil value should be passed for the optional parameter HEADER if
140 the region is part of a message header.  In this case, the only
141 permitted unencoded charset is us-ascii."
142   (let ((charsets
143          (mapcar
144           'mm-mime-charset
145           (mm-find-charset-region (point-min) (point-max))))
146         (cs (if header
147                 '(us-ascii)
148               (list 'us-ascii mail-parse-charset)))
149         found)
150     (while charsets
151       (unless (memq (pop charsets) cs)
152         (setq found t)))
153     found))
154
155 (defun rfc2047-dissect-region (b e)
156   "Dissect the region between B and E into words."
157   (let (words)
158     (save-restriction
159       (narrow-to-region b e)
160       (goto-char (point-min))
161       (while (re-search-forward
162               (concat "[^" ietf-drums-tspecials " \t\n]+") nil t)
163         (push
164          (list (match-beginning 0) (match-end 0)
165                (car (delq 'ascii (mm-find-charset-region
166                                   (match-beginning 0) (match-end 0)))))
167          words))
168       words)))
169
170 (defun rfc2047-encode-region (b e)
171   "Encode all encodable words in REGION."
172   (let ((words (rfc2047-dissect-region b e))
173         beg end current word)
174     (while (setq word (pop words))
175       (if (equal (nth 2 word) current)
176           (setq beg (nth 0 word))
177         (when current
178           (rfc2047-encode beg end current))
179         (setq current (nth 2 word)
180               beg (nth 0 word)
181               end (nth 1 word))))
182     (when current
183       (rfc2047-encode beg end current))))
184
185 (defun rfc2047-encode-string (string)
186   "Encode words in STRING."
187   (with-temp-buffer
188     (insert string)
189     (rfc2047-encode-region (point-min) (point-max))
190     (buffer-string)))
191
192 (defun rfc2047-encode (b e charset)
193   "Encode the word in the region with CHARSET."
194   (let* ((mime-charset (mm-mime-charset charset))
195          (encoding (or (cdr (assq mime-charset
196                                   rfc2047-charset-encoding-alist))
197                        'B))
198          (start (concat
199                  "=?" (downcase (symbol-name mime-charset)) "?"
200                  (downcase (symbol-name encoding)) "?"))
201          (first t))
202     (save-restriction
203       (narrow-to-region b e)
204       (when (eq encoding 'B)
205         ;; break into lines before encoding
206         (goto-char (point-min))
207         (while (not (eobp))
208           (goto-char (min (point-max) (+ 15 (point))))
209           (unless (eobp)
210             (insert "\n"))))
211       (mm-encode-coding-region (point-min) (point-max) mime-charset)
212       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
213                (point-min) (point-max))
214       (goto-char (point-min))
215       (while (not (eobp))
216         (unless first
217           (insert " "))
218         (setq first nil)
219         (insert start)
220         (end-of-line)
221         (insert "?=")
222         (forward-line 1)))))
223
224 (defun rfc2047-fold-region (b e)
225   "Fold the long lines in the region."
226   (save-restriction
227     (narrow-to-region b e)
228     (goto-char (point-min))
229     (let ((break nil))
230       (while (not (eobp))
231         (cond
232          ((memq (char-after) '(?  ?\t))
233           (setq break (point)))
234          ((and (not break)
235                (looking-at "=\\?"))
236           (setq break (point)))
237          ((and (looking-at "\\?=")
238                (> (- (point) (save-excursion (beginning-of-line) (point))) 76))
239           (goto-char break)
240           (insert "\n ")
241           (forward-line 1)))
242         (unless (eobp)
243           (forward-char 1))))))
244
245 (defun rfc2047-b-encode-region (b e)
246   "Encode the header contained in REGION with the B encoding."
247   (save-restriction
248     (narrow-to-region (goto-char b) e)
249     (while (not (eobp))
250       (base64-encode-region (point) (progn (end-of-line) (point)) t)
251       (if (and (bolp) (eolp))
252           (delete-backward-char 1))
253       (forward-line))))
254
255 (defun rfc2047-q-encode-region (b e)
256   "Encode the header contained in REGION with the Q encoding."
257   (save-excursion
258     (save-restriction
259       (narrow-to-region (goto-char b) e)
260       (let ((alist rfc2047-q-encoding-alist))
261         (while alist
262           (when (looking-at (caar alist))
263             (quoted-printable-encode-region b e nil (cdar alist))
264             (subst-char-in-region (point-min) (point-max) ?  ?_)
265             (setq alist nil))
266           (pop alist))
267         (goto-char (point-min))
268         (while (not (eobp))
269           (goto-char (min (point-max) (+ 64 (point))))
270           (search-backward "=" (- (point) 2) t)
271           (unless (eobp)
272             (insert "\n")))))))
273
274 ;;;
275 ;;; Functions for decoding RFC2047 messages
276 ;;;
277
278 (defvar rfc2047-encoded-word-regexp
279   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
280
281 (defun rfc2047-decode-region (start end)
282   "Decode MIME-encoded words in region between START and END."
283   (interactive "r")
284   (let ((case-fold-search t)
285         b e)
286     (save-excursion
287       (save-restriction
288         (narrow-to-region start end)
289         (goto-char (point-min))
290         ;; Remove whitespace between encoded words.
291         (while (re-search-forward
292                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
293                         "\\(\n?[ \t]\\)+"
294                         "\\(" rfc2047-encoded-word-regexp "\\)")
295                 nil t)
296           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
297         ;; Decode the encoded words.
298         (setq b (goto-char (point-min)))
299         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
300           (setq e (match-beginning 0))
301           (insert (rfc2047-parse-and-decode
302                    (prog1
303                        (match-string 0)
304                      (delete-region (match-beginning 0) (match-end 0)))))
305           (when (and (mm-multibyte-p)
306                      mail-parse-charset
307                      (not (eq mail-parse-charset 'gnus-decoded)))
308             (mm-decode-coding-region b e mail-parse-charset))
309           (setq b (point)))
310         (when (and (mm-multibyte-p)
311                    mail-parse-charset
312                    (not (eq mail-parse-charset 'us-ascii))
313                    (not (eq mail-parse-charset 'gnus-decoded)))
314           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
315
316 (defun rfc2047-decode-string (string)
317   "Decode the quoted-printable-encoded STRING and return the results."
318   (let ((m (mm-multibyte-p)))
319     (with-temp-buffer
320       (when m
321         (mm-enable-multibyte))
322       (insert string)
323       (inline
324         (rfc2047-decode-region (point-min) (point-max)))
325       (buffer-string))))
326
327 (defun rfc2047-parse-and-decode (word)
328   "Decode WORD and return it if it is an encoded word.
329 Return WORD if not."
330   (if (not (string-match rfc2047-encoded-word-regexp word))
331       word
332     (or
333      (condition-case nil
334          (rfc2047-decode
335           (match-string 1 word)
336           (upcase (match-string 2 word))
337           (match-string 3 word))
338        (error word))
339      word)))
340
341 (defun rfc2047-decode (charset encoding string)
342   "Decode STRING that uses CHARSET with ENCODING.
343 Valid ENCODINGs are \"B\" and \"Q\".
344 If your Emacs implementation can't decode CHARSET, it returns nil."
345   (if (stringp charset)
346       (setq charset (intern (downcase charset))))
347   (if (or (not charset) 
348           (eq 'gnus-all mail-parse-ignored-charsets)
349           (memq 'gnus-all mail-parse-ignored-charsets)
350           (memq charset mail-parse-ignored-charsets))
351       (setq charset mail-parse-charset))
352   (let ((cs (mm-charset-to-coding-system charset)))
353     (if (and (not cs) charset 
354              (listp mail-parse-ignored-charsets)
355              (memq 'gnus-unknown mail-parse-ignored-charsets))
356         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
357     (when cs
358       (when (and (eq cs 'ascii)
359                  mail-parse-charset)
360         (setq cs mail-parse-charset))
361       (mm-decode-coding-string
362        (cond
363         ((equal "B" encoding)
364          (base64-decode-string string))
365         ((equal "Q" encoding)
366          (quoted-printable-decode-string
367           (mm-replace-chars-in-string string ?_ ? )))
368         (t (error "Invalid encoding: %s" encoding)))
369        cs))))
370
371 (provide 'rfc2047)
372
373 ;;; rfc2047.el ends here