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