Only ask question once when sending.
[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-when-compile (require 'cl))
28 (eval-and-compile
29   (eval
30    '(unless (fboundp 'base64-decode-string)
31       (require 'base64))))
32
33 (require 'qp)
34 (require 'mm-util)
35 (require 'ietf-drums)
36 (require 'mail-prsvr)
37
38 (defvar rfc2047-header-encoding-alist
39   '(("Newsgroups" . nil)
40     ("Message-ID" . nil)
41     (t . mime))
42   "*Header/encoding method alist.
43 The list is traversed sequentially.  The keys can either be
44 header regexps or `t'.
45
46 The values can be:
47
48 1) nil, in which case no encoding is done;
49 2) `mime', in which case the header will be encoded according to RFC2047;
50 3) a charset, in which case it will be encoded as that charset;
51 4) `default', in which case the field will be encoded as the rest
52    of the article.")
53
54 (defvar rfc2047-charset-encoding-alist
55   '((us-ascii . nil)
56     (iso-8859-1 . Q)
57     (iso-8859-2 . Q)
58     (iso-8859-3 . Q)
59     (iso-8859-4 . Q)
60     (iso-8859-5 . B)
61     (koi8-r . B)
62     (iso-8859-7 . Q)
63     (iso-8859-8 . Q)
64     (iso-8859-9 . Q)
65     (iso-8859-14 . Q)
66     (iso-8859-15 . Q)
67     (iso-2022-jp . B)
68     (iso-2022-kr . B)
69     (gb2312 . B)
70     (cn-gb . B)
71     (cn-gb-2312 . B)
72     (euc-kr . B)
73     (iso-2022-jp-2 . B)
74     (iso-2022-int-1 . B))
75   "Alist of MIME charsets to RFC2047 encodings.
76 Valid encodings are nil, `Q' and `B'.")
77
78 (defvar rfc2047-encoding-function-alist
79   '((Q . rfc2047-q-encode-region)
80     (B . rfc2047-b-encode-region)
81     (nil . ignore))
82   "Alist of RFC2047 encodings to encoding functions.")
83
84 (defvar rfc2047-q-encoding-alist
85   '(("\\(From\\|Cc\\|To\\|Bcc\||Reply-To\\):" . "-A-Za-z0-9!*+/") 
86     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
87     ;; Avoid using 8bit characters. Some versions of Emacs has bug!
88     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
89     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
90   "Alist of header regexps and valid Q characters.")
91
92 ;;;
93 ;;; Functions for encoding RFC2047 messages
94 ;;;
95
96 (defun rfc2047-narrow-to-field ()
97   "Narrow the buffer to the header on the current line."
98   (beginning-of-line)
99   (narrow-to-region
100    (point)
101    (progn
102      (forward-line 1)
103      (if (re-search-forward "^[^ \n\t]" nil t)
104          (progn
105            (beginning-of-line)
106            (point))
107        (point-max))))
108   (goto-char (point-min)))
109
110 (defun rfc2047-encode-message-header ()
111   "Encode the message header according to `rfc2047-header-encoding-alist'.
112 Should be called narrowed to the head of the message."
113   (interactive "*")
114   (save-excursion
115     (goto-char (point-min))
116     (let (alist elem method)
117       (while (not (eobp))
118         (save-restriction
119           (rfc2047-narrow-to-field)
120           (if (not (rfc2047-encodable-p))
121               (if (and (eq (mm-body-7-or-8) '8bit)
122                        (mm-multibyte-p)
123                        (mm-coding-system-p
124                         (car message-posting-charset)))
125                        ;; 8 bit must be decoded.
126                        ;; Is message-posting-charset a coding system?
127                        (mm-encode-coding-region 
128                         (point-min) (point-max) 
129                         (car message-posting-charset)))
130             ;; We found something that may perhaps be encoded.
131             (setq method nil
132                   alist rfc2047-header-encoding-alist)
133             (while (setq elem (pop alist))
134               (when (or (and (stringp (car elem))
135                              (looking-at (car elem)))
136                         (eq (car elem) t))
137                 (setq alist nil
138                       method (cdr elem))))
139             (cond
140              ((eq method 'mime)
141               (rfc2047-encode-region (point-min) (point-max)))
142              ((eq method 'default)
143               (if (and (featurep 'mule)
144                        mail-parse-charset)
145                   (mm-encode-coding-region (point-min) (point-max) 
146                                            mail-parse-charset)))
147              ((null method)
148               (and (delq 'ascii 
149                          (mm-find-charset-region (point-min) 
150                                                  (point-max)))
151                    (if (or (message-options-get
152                             'rfc2047-encode-message-header-encode-any) 
153                            (message-options-set
154                             'rfc2047-encode-message-header-encode-any
155                             (y-or-n-p 
156                              "Some texts are not encoded. Encode anyway?")))
157                        (rfc2047-encode-region (point-min) (point-max))
158                      (error "Cannot send unencoded text."))))
159              ((mm-coding-system-p method)
160               (if (featurep 'mule)
161                   (mm-encode-coding-region (point-min) (point-max) method)))
162              ;; Hm.
163              (t)))
164           (goto-char (point-max)))))))
165
166 (defun rfc2047-encodable-p (&optional header)
167   "Say whether the current (narrowed) buffer contains characters that need encoding in headers."
168   (let ((charsets
169          (mapcar
170           'mm-mime-charset
171           (mm-find-charset-region (point-min) (point-max))))
172         (cs (list 'us-ascii (car message-posting-charset)))
173         found)
174     (while charsets
175       (unless (memq (pop charsets) cs)
176         (setq found t)))
177     found))
178
179 (defun rfc2047-dissect-region (b e)
180   "Dissect the region between B and E into words."
181   (let ((word-chars "-A-Za-z0-9!*+/") 
182         ;; Not using ietf-drums-specials-token makes life simple.
183         mail-parse-mule-charset
184         words point current 
185         result word)
186     (save-restriction
187       (narrow-to-region b e)
188       (goto-char (point-min))
189       (skip-chars-forward "\000-\177")
190       (while (not (eobp))
191         (setq point (point))
192         (skip-chars-backward word-chars b)
193         (unless (eq b (point))
194           (push (cons (buffer-substring b (point)) nil) words)) 
195         (setq b (point))
196         (goto-char point)
197         (setq current (mm-charset-after))
198         (forward-char 1)
199         (skip-chars-forward word-chars)
200         (while (and (not (eobp))
201                     (eq (mm-charset-after) current))
202           (forward-char 1)
203           (skip-chars-forward word-chars))
204         (unless (eq b (point))
205           (push (cons (buffer-substring b (point)) current) words)) 
206         (setq b (point))
207         (skip-chars-forward "\000-\177"))
208       (unless (eq b (point))
209         (push (cons (buffer-substring b (point)) nil) words)))
210     ;; merge adjacent words
211     (setq word (pop words))
212     (while word
213       (if (and (cdr word) 
214                (caar words)
215                (not (cdar words))
216                (not (string-match "[^ \t]" (caar words))))
217           (if (eq (cdr (nth 1 words)) (cdr word))
218               (progn
219                 (setq word (cons (concat 
220                                   (car (nth 1 words)) (caar words) 
221                                   (car word))
222                                  (cdr word)))
223                 (pop words)
224                 (pop words))
225             (push (cons (concat (caar words) (car word)) (cdr word))
226                   result)
227             (pop words)
228             (setq word (pop words)))
229         (push word result)
230         (setq word (pop words))))
231     result))
232
233 (defun rfc2047-encode-region (b e)
234   "Encode all encodable words in REGION."
235   (let ((words (rfc2047-dissect-region b e)) word)
236     (save-restriction
237       (narrow-to-region b e)
238       (delete-region (point-min) (point-max))
239       (while (setq word (pop words))
240         (if (not (cdr word))
241             (insert (car word))
242           (rfc2047-fold-region (gnus-point-at-bol) (point))
243           (goto-char (point-max))
244           (if (> (- (point) (save-restriction
245                               (widen)
246                               (gnus-point-at-bol))) 76)
247               (insert "\n "))
248           ;; Insert blank between encoded words
249           (if (eq (char-before) ?=) (insert " ")) 
250           (rfc2047-encode (point) 
251                           (progn (insert (car word)) (point))
252                           (cdr word))))
253       (rfc2047-fold-region (point-min) (point-max)))))
254
255 (defun rfc2047-encode-string (string)
256   "Encode words in STRING."
257   (with-temp-buffer
258     (insert string)
259     (rfc2047-encode-region (point-min) (point-max))
260     (buffer-string)))
261
262 (defun rfc2047-encode (b e charset)
263   "Encode the word in the region with CHARSET."
264   (let* ((mime-charset (mm-mime-charset charset))
265          (encoding (or (cdr (assq mime-charset
266                                   rfc2047-charset-encoding-alist))
267                        'B))
268          (start (concat
269                  "=?" (downcase (symbol-name mime-charset)) "?"
270                  (downcase (symbol-name encoding)) "?"))
271          (first t))
272     (save-restriction
273       (narrow-to-region b e)
274       (when (eq encoding 'B)
275         ;; break into lines before encoding
276         (goto-char (point-min))
277         (while (not (eobp))
278           (goto-char (min (point-max) (+ 15 (point))))
279           (unless (eobp)
280             (insert "\n"))))
281       (if (and (mm-multibyte-p)
282                (mm-coding-system-p mime-charset))
283           (mm-encode-coding-region (point-min) (point-max) mime-charset))
284       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
285                (point-min) (point-max))
286       (goto-char (point-min))
287       (while (not (eobp))
288         (unless first
289           (insert " "))
290         (setq first nil)
291         (insert start)
292         (end-of-line)
293         (insert "?=")
294         (forward-line 1)))))
295
296 (defun rfc2047-fold-region (b e)
297   "Fold the long lines in the region."
298   (save-restriction
299     (narrow-to-region b e)
300     (goto-char (point-min))
301     (let ((break nil)
302           (qword-break nil)
303           (bol (save-restriction
304                  (widen)
305                  (gnus-point-at-bol))))
306       (while (not (eobp))
307         (when (and (or break qword-break) (> (- (point) bol) 76))
308           (goto-char (or break qword-break))
309           (setq break nil
310                 qword-break nil)
311           (insert "\n ")
312           (setq bol (1- (point)))
313           ;; Don't break before the first non-LWSP characters.
314           (skip-chars-forward " \t")
315           (forward-char 1))
316         (cond
317          ((eq (char-after) ?\n)
318           (forward-char 1)
319           (setq bol (point)
320                 break nil
321                 qword-break nil)
322           (skip-chars-forward " \t")
323           (unless (or (eobp) (eq (char-after) ?\n))
324             (forward-char 1)))
325          ((eq (char-after) ?\r)
326           (forward-char 1))
327          ((memq (char-after) '(?  ?\t))
328           (skip-chars-forward " \t")
329           (setq break (1- (point))))
330          ((not break)
331           (if (not (looking-at "=\\?[^=]"))
332               (if (eq (char-after) ?=)
333                   (forward-char 1)
334                 (skip-chars-forward "^ \t\n\r="))
335             (setq qword-break (point))
336             (skip-chars-forward "^ \t\n\r")))
337          (t
338           (skip-chars-forward "^ \t\n\r"))))
339       (when (and (or break qword-break) (> (- (point) bol) 76))
340         (goto-char (or break qword-break))
341         (setq break nil
342               qword-break nil)
343         (insert "\n ")
344         (setq bol (1- (point)))
345         ;; Don't break before the first non-LWSP characters.
346         (skip-chars-forward " \t")
347         (forward-char 1)))))
348
349 (defun rfc2047-unfold-region (b e)
350   "Fold the long lines in the region."
351   (save-restriction
352     (narrow-to-region b e)
353     (goto-char (point-min))
354     (let ((bol (save-restriction
355                  (widen)
356                  (gnus-point-at-bol)))
357           (eol (gnus-point-at-eol))
358           leading)
359       (forward-line 1)
360       (while (not (eobp))
361         (looking-at "[ \t]*")
362         (setq leading (- (match-end 0) (match-beginning 0)))
363         (if (< (- (gnus-point-at-eol) bol leading) 76)
364             (progn
365               (goto-char eol)
366               (delete-region eol (progn 
367                                    (skip-chars-forward "[ \t\n\r]+")
368                                    (1- (point)))))
369           (setq bol (gnus-point-at-bol)))
370         (setq eol (gnus-point-at-eol))
371         (forward-line 1)))))
372
373 (defun rfc2047-b-encode-region (b e)
374   "Encode the header contained in REGION with the B encoding."
375   (save-restriction
376     (narrow-to-region (goto-char b) e)
377     (while (not (eobp))
378       (base64-encode-region (point) (progn (end-of-line) (point)) t)
379       (if (and (bolp) (eolp))
380           (delete-backward-char 1))
381       (forward-line))))
382
383 (defun rfc2047-q-encode-region (b e)
384   "Encode the header contained in REGION with the Q encoding."
385   (save-excursion
386     (save-restriction
387       (narrow-to-region (goto-char b) e)
388       (let ((alist rfc2047-q-encoding-alist)
389             (bol (save-restriction
390                    (widen)
391                    (gnus-point-at-bol))))
392         (while alist
393           (when (looking-at (caar alist))
394             (quoted-printable-encode-region b e nil (cdar alist))
395             (subst-char-in-region (point-min) (point-max) ?  ?_)
396             (setq alist nil))
397           (pop alist))
398         ;; The size of QP encapsulation is about 20, so set limit to
399         ;; 56=76-20.
400         (unless (< (- (point-max) (point-min)) 56)
401           ;; Don't break if it could fit in one line.
402           ;; Let rfc2047-encode-region break it later.
403           (goto-char (1+ (point-min)))
404           (while (and (not (bobp)) (not (eobp)))
405             (goto-char (min (point-max) (+ 56 bol)))
406             (search-backward "=" (- (point) 2) t)
407             (unless (or (bobp) (eobp))
408               (insert "\n")
409               (setq bol (point)))))))))
410
411 ;;;
412 ;;; Functions for decoding RFC2047 messages
413 ;;;
414
415 (defvar rfc2047-encoded-word-regexp
416   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
417
418 (defun rfc2047-decode-region (start end)
419   "Decode MIME-encoded words in region between START and END."
420   (interactive "r")
421   (let ((case-fold-search t)
422         b e)
423     (save-excursion
424       (save-restriction
425         (narrow-to-region start end)
426         (goto-char (point-min))
427         ;; Remove whitespace between encoded words.
428         (while (re-search-forward
429                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
430                         "\\(\n?[ \t]\\)+"
431                         "\\(" rfc2047-encoded-word-regexp "\\)")
432                 nil t)
433           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
434         ;; Decode the encoded words.
435         (setq b (goto-char (point-min)))
436         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
437           (setq e (match-beginning 0))
438           (insert (rfc2047-parse-and-decode
439                    (prog1
440                        (match-string 0)
441                      (delete-region (match-beginning 0) (match-end 0)))))
442           (when (and (mm-multibyte-p)
443                      mail-parse-charset
444                      (not (eq mail-parse-charset 'gnus-decoded)))
445             (mm-decode-coding-region b e mail-parse-charset))
446           (setq b (point)))
447         (when (and (mm-multibyte-p)
448                    mail-parse-charset
449                    (not (eq mail-parse-charset 'us-ascii))
450                    (not (eq mail-parse-charset 'gnus-decoded)))
451           (mm-decode-coding-region b (point-max) mail-parse-charset))
452         (rfc2047-unfold-region (point-min) (point-max))))))
453
454 (defun rfc2047-decode-string (string)
455   "Decode the quoted-printable-encoded STRING and return the results."
456   (let ((m (mm-multibyte-p)))
457     (with-temp-buffer
458       (when m
459         (mm-enable-multibyte))
460       (insert string)
461       (inline
462         (rfc2047-decode-region (point-min) (point-max)))
463       (buffer-string))))
464
465 (defun rfc2047-parse-and-decode (word)
466   "Decode WORD and return it if it is an encoded word.
467 Return WORD if not."
468   (if (not (string-match rfc2047-encoded-word-regexp word))
469       word
470     (or
471      (condition-case nil
472          (rfc2047-decode
473           (match-string 1 word)
474           (upcase (match-string 2 word))
475           (match-string 3 word))
476        (error word))
477      word)))
478
479 (defun rfc2047-decode (charset encoding string)
480   "Decode STRING that uses CHARSET with ENCODING.
481 Valid ENCODINGs are \"B\" and \"Q\".
482 If your Emacs implementation can't decode CHARSET, it returns nil."
483   (if (stringp charset)
484       (setq charset (intern (downcase charset))))
485   (if (or (not charset) 
486           (eq 'gnus-all mail-parse-ignored-charsets)
487           (memq 'gnus-all mail-parse-ignored-charsets)
488           (memq charset mail-parse-ignored-charsets))
489       (setq charset mail-parse-charset))
490   (let ((cs (mm-charset-to-coding-system charset)))
491     (if (and (not cs) charset 
492              (listp mail-parse-ignored-charsets)
493              (memq 'gnus-unknown mail-parse-ignored-charsets))
494         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
495     (when cs
496       (when (and (eq cs 'ascii)
497                  mail-parse-charset)
498         (setq cs mail-parse-charset))
499       (mm-with-unibyte-current-buffer-mule4
500         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
501         (mm-decode-coding-string
502          (cond
503           ((equal "B" encoding)
504            (base64-decode-string string))
505           ((equal "Q" encoding)
506            (quoted-printable-decode-string
507             (mm-replace-chars-in-string string ?_ ? )))
508           (t (error "Invalid encoding: %s" encoding)))
509          cs)))))
510
511 (provide 'rfc2047)
512
513 ;;; rfc2047.el ends here