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