b0454953fa0dbe15c59947e702cb77f1175c3152
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003 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 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three:  Message Header Extensions for Non-ASCII Text".
27
28 ;;; Code:
29
30 (eval-when-compile
31   (require 'cl)
32   (defvar message-posting-charset))
33
34 (require 'qp)
35 (require 'mm-util)
36 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
37 (require 'mail-prsvr)
38 (require 'base64)
39 (autoload 'mm-body-7-or-8 "mm-bodies")
40
41 (defvar rfc2047-header-encoding-alist
42   '(("Newsgroups" . nil)
43     ("Followup-To" . nil)
44     ("Message-ID" . nil)
45     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\
46 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
47     (t . mime))
48   "*Header/encoding method alist.
49 The list is traversed sequentially.  The keys can either be
50 header regexps or t.
51
52 The values can be:
53
54 1) nil, in which case no encoding is done;
55 2) `mime', in which case the header will be encoded according to RFC2047;
56 3) `address-mime', like `mime', but takes account of the rules for address
57    fields (where quoted strings and comments must be treated separately);
58 4) a charset, in which case it will be encoded as that charset;
59 5) `default', in which case the field will be encoded as the rest
60    of the article.")
61
62 (defvar rfc2047-charset-encoding-alist
63   '((us-ascii . nil)
64     (iso-8859-1 . Q)
65     (iso-8859-2 . Q)
66     (iso-8859-3 . Q)
67     (iso-8859-4 . Q)
68     (iso-8859-5 . B)
69     (koi8-r . B)
70     (iso-8859-7 . B)
71     (iso-8859-8 . B)
72     (iso-8859-9 . Q)
73     (iso-8859-14 . Q)
74     (iso-8859-15 . Q)
75     (iso-2022-jp . B)
76     (iso-2022-kr . B)
77     (gb2312 . B)
78     (big5 . B)
79     (cn-big5 . B)
80     (cn-gb . B)
81     (cn-gb-2312 . B)
82     (euc-kr . B)
83     (iso-2022-jp-2 . B)
84     (iso-2022-int-1 . B)
85     (viscii . Q))
86   "Alist of MIME charsets to RFC2047 encodings.
87 Valid encodings are nil, `Q' and `B'.  These indicate binary (no) encoding,
88 quoted-printable and base64 respectively.")
89
90 (defvar rfc2047-encoding-function-alist
91   '((Q . rfc2047-q-encode-region)
92     (B . rfc2047-b-encode-region)
93     (nil . ignore))
94   "Alist of RFC2047 encodings to encoding functions.")
95
96 (defvar rfc2047-encode-encoded-words t
97   "Whether encoded words should be encoded again.")
98
99 ;;;
100 ;;; Functions for encoding RFC2047 messages
101 ;;;
102
103 (defun rfc2047-qp-or-base64 ()
104   "Return the type with which to encode the buffer.
105 This is either `base64' or `quoted-printable'."
106   (save-excursion
107     (let ((limit (min (point-max) (+ 2000 (point-min))))
108           (n8bit 0))
109       (goto-char (point-min))
110       (skip-chars-forward "\x20-\x7f\r\n\t" limit)
111       (while (< (point) limit)
112         (incf n8bit)
113         (forward-char 1)
114         (skip-chars-forward "\x20-\x7f\r\n\t" limit))
115       (if (or (< (* 6 n8bit) (- limit (point-min)))
116               ;; Don't base64, say, a short line with a single
117               ;; non-ASCII char when splitting parts by charset.
118               (= n8bit 1))
119           'quoted-printable
120         'base64))))
121
122 (defun rfc2047-narrow-to-field ()
123   "Narrow the buffer to the header on the current line."
124   (beginning-of-line)
125   (narrow-to-region
126    (point)
127    (progn
128      (forward-line 1)
129      (if (re-search-forward "^[^ \n\t]" nil t)
130          (point-at-bol)
131        (point-max))))
132   (goto-char (point-min)))
133
134 (defun rfc2047-field-value ()
135   "Return the value of the field at point."
136   (save-excursion
137     (save-restriction
138       (rfc2047-narrow-to-field)
139       (re-search-forward ":[ \t\n]*" nil t)
140       (buffer-substring-no-properties (point) (point-max)))))
141
142 (defvar rfc2047-encoding-type 'address-mime
143   "The type of encoding done by `rfc2047-encode-region'.
144 This should be dynamically bound around calls to
145 `rfc2047-encode-region' to either `mime' or `address-mime'.  See
146 `rfc2047-header-encoding-alist', for definitions.")
147
148 (defun rfc2047-encode-message-header ()
149   "Encode the message header according to `rfc2047-header-encoding-alist'.
150 Should be called narrowed to the head of the message."
151   (interactive "*")
152   (save-excursion
153     (goto-char (point-min))
154     (let (alist elem method)
155       (while (not (eobp))
156         (save-restriction
157           (rfc2047-narrow-to-field)
158           (if (not (rfc2047-encodable-p))
159               (prog1
160                 (if (and (eq (mm-body-7-or-8) '8bit)
161                          (mm-multibyte-p)
162                          (mm-coding-system-p
163                           (car message-posting-charset)))
164                     ;; 8 bit must be decoded.
165                     (mm-encode-coding-region
166                      (point-min) (point-max)
167                      (mm-charset-to-coding-system
168                       (car message-posting-charset))))
169                 ;; No encoding necessary, but folding is nice
170                 (rfc2047-fold-region
171                  (save-excursion
172                    (goto-char (point-min))
173                    (skip-chars-forward "^:")
174                    (when (looking-at ": ")
175                      (forward-char 2))
176                    (point))
177                  (point-max)))
178             ;; We found something that may perhaps be encoded.
179             (setq method nil
180                   alist rfc2047-header-encoding-alist)
181             (while (setq elem (pop alist))
182               (when (or (and (stringp (car elem))
183                              (looking-at (car elem)))
184                         (eq (car elem) t))
185                 (setq alist nil
186                       method (cdr elem))))
187             (goto-char (point-min))
188             (re-search-forward "^[^:]+: *" nil t)
189             (cond
190              ((eq method 'address-mime)
191               (rfc2047-encode-region (point) (point-max)))
192              ((eq method 'mime)
193               (let ((rfc2047-encoding-type 'mime))
194                 (rfc2047-encode-region (point) (point-max))))
195              ((eq method 'default)
196               (if (and (featurep 'mule)
197                        (if (boundp 'default-enable-multibyte-characters)
198                            default-enable-multibyte-characters)
199                        mail-parse-charset)
200                   (mm-encode-coding-region (point) (point-max)
201                                            mail-parse-charset)))
202              ;; We get this when CC'ing messsages to newsgroups with
203              ;; 8-bit names.  The group name mail copy just got
204              ;; unconditionally encoded.  Previously, it would ask
205              ;; whether to encode, which was quite confusing for the
206              ;; user.  If the new behaviour is wrong, tell me. I have
207              ;; left the old code commented out below.
208              ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
209              ;; Modified by Dave Love, with the commented-out code changed
210              ;; in accordance with changes elsewhere.
211              ((null method)
212               (rfc2047-encode-region (point) (point-max)))
213 ;;;          ((null method)
214 ;;;           (if (or (message-options-get
215 ;;;                    'rfc2047-encode-message-header-encode-any)
216 ;;;                   (message-options-set
217 ;;;                    'rfc2047-encode-message-header-encode-any
218 ;;;                    (y-or-n-p
219 ;;;                     "Some texts are not encoded. Encode anyway?")))
220 ;;;               (rfc2047-encode-region (point-min) (point-max))
221 ;;;             (error "Cannot send unencoded text")))
222              ((mm-coding-system-p method)
223               (if (and (featurep 'mule)
224                        (if (boundp 'default-enable-multibyte-characters)
225                            default-enable-multibyte-characters))
226                   (mm-encode-coding-region (point) (point-max) method)))
227              ;; Hm.
228              (t)))
229           (goto-char (point-max)))))))
230
231 ;; Fixme: This, and the require below may not be the Right Thing, but
232 ;; should be safe just before release.  -- fx 2001-02-08
233 (eval-when-compile (defvar message-posting-charset))
234
235 (defun rfc2047-encodable-p ()
236   "Return non-nil if any characters in current buffer need encoding in headers.
237 The buffer may be narrowed."
238   (require 'message)                    ; for message-posting-charset
239   (let ((charsets
240          (mm-find-mime-charset-region (point-min) (point-max))))
241     (goto-char (point-min))
242     (or (and rfc2047-encode-encoded-words
243              (search-forward "=?" nil t))
244         (and charsets
245              (not (equal charsets (list (car message-posting-charset))))))))
246
247 ;; Use this syntax table when parsing into regions that may need
248 ;; encoding.  Double quotes are string delimiters, backslash is
249 ;; character quoting, and all other RFC 2822 special characters are
250 ;; treated as punctuation so we can use forward-sexp/forward-word to
251 ;; skip to the end of regions appropriately.  Nb. ietf-drums does
252 ;; things differently.
253 (defconst rfc2047-syntax-table
254   ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
255   (let ((table (make-syntax-table)))
256     ;; The following is done to work for setting all elements of the table
257     ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
258     ;; Play safe and don't assume the form of the word syntax entry --
259     ;; copy it from ?a.
260     (if (fboundp 'set-char-table-range) ; Emacs
261         (funcall (intern "set-char-table-range")
262                  table t (aref (standard-syntax-table) ?a))
263       (if (fboundp 'put-char-table)
264           (if (fboundp 'get-char-table) ; warning avoidance
265               (put-char-table t (get-char-table ?a (standard-syntax-table))
266                               table))))
267     (modify-syntax-entry ?\\ "\\" table)
268     (modify-syntax-entry ?\" "\"" table)
269     (modify-syntax-entry ?\( "." table)
270     (modify-syntax-entry ?\) "." table)
271     (modify-syntax-entry ?\< "." table)
272     (modify-syntax-entry ?\> "." table)
273     (modify-syntax-entry ?\[ "." table)
274     (modify-syntax-entry ?\] "." table)
275     (modify-syntax-entry ?: "." table)
276     (modify-syntax-entry ?\; "." table)
277     (modify-syntax-entry ?, "." table)
278     (modify-syntax-entry ?@ "." table)
279     table))
280
281 (defun rfc2047-encode-region (b e)
282   "Encode words in region B to E that need encoding.
283 By default, the region is treated as containing RFC2822 addresses.
284 Dynamically bind `rfc2047-encoding-type' to change that."
285   (save-restriction
286     (narrow-to-region b e)
287     (if (eq 'mime rfc2047-encoding-type)
288         ;; Simple case.  Treat as single word after any initial ASCII
289         ;; part and before any tailing ASCII part.  The leading ASCII
290         ;; is relevant for instance in Subject headers with `Re:' for
291         ;; interoperability with non-MIME clients, and we might as
292         ;; well avoid the tail too.
293         (let ((encodable-regexp
294                (if rfc2047-encode-encoded-words
295                    "[^\000-\177]\\|=\\?"
296                  "[^\000-\177]")))
297           (goto-char (point-min))
298           ;; Does it need encoding?
299           (re-search-forward encodable-regexp (point-max) 'move)
300           (unless (eobp)
301             (skip-chars-backward "^ \n") ; beginning of space-delimited word
302             (rfc2047-encode
303              (point)
304              (progn
305                (goto-char e)
306                (re-search-backward encodable-regexp (point-max) 'move)
307                (skip-chars-forward "^ \n")
308                ;; end of space-delimited word
309                (point)))))
310       ;; `address-mime' case -- take care of quoted words, comments.
311       (with-syntax-table rfc2047-syntax-table
312         (let ((start)                   ; start of current token
313               end                       ; end of current token
314               ;; Whether there's an encoded word before the current
315               ;; token, either immediately or separated by space.
316               last-encoded)
317           (goto-char (point-min))
318           (condition-case nil           ; in case of unbalanced quotes
319               ;; Look for rfc2822-style: sequences of atoms, quoted
320               ;; strings, specials, whitespace.  (Specials mustn't be
321               ;; encoded.)
322               (while (not (eobp))
323                 (setq start (point))
324                 ;; Skip whitespace.
325                 (unless (= 0 (skip-chars-forward " \t\n"))
326                   (setq start (point)))
327                 (cond
328                  ((not (char-after)))   ; eob
329                  ;; else token start
330                  ((eq ?\" (char-syntax (char-after)))
331                   ;; Quoted word.
332                   (forward-sexp)
333                   (setq end (point))
334                   ;; Does it need encoding?
335                   (goto-char start)
336                   (skip-chars-forward "\000-\177" end)
337                   (if (= end (point))
338                       (setq last-encoded  nil)
339                     ;; It needs encoding.  Strip the quotes first,
340                     ;; since encoded words can't occur in quotes.
341                     (goto-char end)
342                     (delete-backward-char 1)
343                     (goto-char start)
344                     (delete-char 1)
345                     (when last-encoded
346                       ;; There was a preceding quoted word.  We need
347                       ;; to include any separating whitespace in this
348                       ;; word to avoid it getting lost.
349                       (skip-chars-backward " \t")
350                       ;; A space is needed between the encoded words.
351                       (insert ? )
352                       (setq start (point)
353                             end (1+ end)))
354                     ;; Adjust the end position for the deleted quotes.
355                     (rfc2047-encode start (- end 2))
356                     (setq last-encoded t))) ; record that it was encoded
357                  ((eq ?. (char-syntax (char-after)))
358                   ;; Skip other delimiters, but record that they've
359                   ;; potentially separated quoted words.
360                   (forward-char)
361                   (setq last-encoded nil))
362                  (t                 ; normal token/whitespace sequence
363                   ;; Find the end.
364                   (forward-word 1)
365                   (skip-chars-backward " \t")
366                   (setq end (point))
367                   ;; Deal with encoding and leading space as for
368                   ;; quoted words.
369                   (goto-char start)
370                   (skip-chars-forward "\000-\177" end)
371                   (if (= end (point))
372                       (setq last-encoded  nil)
373                     (when last-encoded
374                       (goto-char start)
375                       (skip-chars-backward " \t")
376                       (insert ? )
377                       (setq start (point)
378                             end (1+ end)))
379                     (rfc2047-encode start end)
380                     (setq last-encoded t)))))
381             (error
382              (error "Invalid data for rfc2047 encoding: %s"
383                     (buffer-substring b e)))))))
384     (rfc2047-fold-region b (point))))
385
386 (defun rfc2047-encode-string (string)
387   "Encode words in STRING.
388 By default, the string is treated as containing addresses (see
389 `rfc2047-encoding-type')."
390   (with-temp-buffer
391     (insert string)
392     (rfc2047-encode-region (point-min) (point-max))
393     (buffer-string)))
394
395 (defun rfc2047-encode (b e)
396   "Encode the word(s) in the region B to E.
397 By default, the region is treated as containing addresses (see
398 `rfc2047-encoding-type')."
399   (let* ((mime-charset (or (mm-find-mime-charset-region b e) (list 'us-ascii)))
400          (cs (if (> (length mime-charset) 1)
401                  ;; Fixme: Instead of this, try to break region into
402                  ;; parts that can be encoded separately.
403                  (error "Can't rfc2047-encode `%s'"
404                         (buffer-substring b e))
405                (setq mime-charset (car mime-charset))
406                (mm-charset-to-coding-system mime-charset)))
407          ;; Fixme: Better, calculate the number of non-ASCII
408          ;; characters, at least for 8-bit charsets.
409          (encoding (or (cdr (assq mime-charset
410                                   rfc2047-charset-encoding-alist))
411                        ;; For the charsets that don't have a preferred
412                        ;; encoding, choose the one that's shorter.
413                        (save-restriction
414                          (narrow-to-region b e)
415                          (if (eq (rfc2047-qp-or-base64) 'base64)
416                              'B
417                            'Q))))
418          (start (concat
419                  "=?" (downcase (symbol-name mime-charset)) "?"
420                  (upcase (symbol-name encoding)) "?"))
421          (factor (case mime-charset
422                    ((iso-8859-5 iso-8859-7 iso-8859-8 koi8-r) 1)
423                    ((big5 gb2312 euc-kr) 2)
424                    (utf-8 4)
425                    (t 8)))
426          (pre (- b (save-restriction
427                      (widen)
428                      (point-at-bol))))
429          ;; encoded-words must not be longer than 75 characters,
430          ;; including charset, encoding etc.  This leaves us with
431          ;; 75 - (length start) - 2 - 2 characters.  The last 2 is for
432          ;; possible base64 padding.  In the worst case (iso-2022-*)
433          ;; each character expands to 8 bytes which is expanded by a
434          ;; factor of 4/3 by base64 encoding.
435          (length (floor (- 75 (length start) 4) (* factor (/ 4.0 3.0))))
436          ;; Limit line length to 76 characters.
437          (length1 (max 1 (floor (- 76 (length start) 4 pre)
438                                 (* factor (/ 4.0 3.0)))))
439          (first t))
440     (if mime-charset
441         (save-restriction
442           (narrow-to-region b e)
443           (when (eq encoding 'B)
444             ;; break into lines before encoding
445             (goto-char (point-min))
446             (while (not (eobp))
447               (if first
448                   (progn
449                     (goto-char (min (point-max) (+ length1 (point))))
450                     (setq first nil))
451                 (goto-char (min (point-max) (+ length (point)))))
452               (unless (eobp)
453                 (insert ?\n)))
454             (setq first t))
455           (if (and (mm-multibyte-p)
456                    (mm-coding-system-p cs))
457               (mm-encode-coding-region (point-min) (point-max) cs))
458           (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
459                    (point-min) (point-max))
460           (goto-char (point-min))
461           (while (not (eobp))
462             (unless first
463               (insert ? ))
464             (setq first nil)
465             (insert start)
466             (end-of-line)
467             (insert "?=")
468             (forward-line 1))))))
469
470 (defun rfc2047-fold-field ()
471   "Fold the current header field."
472   (save-excursion
473     (save-restriction
474       (rfc2047-narrow-to-field)
475       (rfc2047-fold-region (point-min) (point-max)))))
476
477 (defun rfc2047-fold-region (b e)
478   "Fold long lines in region B to E."
479   (save-restriction
480     (narrow-to-region b e)
481     (goto-char (point-min))
482     (let ((break nil)
483           (qword-break nil)
484           (first t)
485           (bol (save-restriction
486                  (widen)
487                  (point-at-bol))))
488       (while (not (eobp))
489         (when (and (or break qword-break)
490                    (> (- (point) bol) 76))
491           (goto-char (or break qword-break))
492           (setq break nil
493                 qword-break nil)
494           (if (looking-at "[ \t]")
495               (insert ?\n)
496             (insert "\n "))
497           (setq bol (1- (point)))
498           ;; Don't break before the first non-LWSP characters.
499           (skip-chars-forward " \t")
500           (unless (eobp)
501             (forward-char 1)))
502         (cond
503          ((eq (char-after) ?\n)
504           (forward-char 1)
505           (setq bol (point)
506                 break nil
507                 qword-break nil)
508           (skip-chars-forward " \t")
509           (unless (or (eobp) (eq (char-after) ?\n))
510             (forward-char 1)))
511          ((eq (char-after) ?\r)
512           (forward-char 1))
513          ((memq (char-after) '(?  ?\t))
514           (skip-chars-forward " \t")
515           (if first
516               ;; Don't break just after the header name.
517               (setq first nil)
518             (setq break (1- (point)))))
519          ((not break)
520           (if (not (looking-at "=\\?[^=]"))
521               (if (eq (char-after) ?=)
522                   (forward-char 1)
523                 (skip-chars-forward "^ \t\n\r="))
524             ;; Don't break at the start of the field.
525             (unless (= (point) b)
526               (setq qword-break (point)))
527             (skip-chars-forward "^ \t\n\r")))
528          (t
529           (skip-chars-forward "^ \t\n\r"))))
530       (when (and (or break qword-break)
531                  (> (- (point) bol) 76))
532         (goto-char (or break qword-break))
533         (setq break nil
534               qword-break nil)
535           (if (looking-at "[ \t]")
536               (insert ?\n)
537             (insert "\n "))
538         (setq bol (1- (point)))
539         ;; Don't break before the first non-LWSP characters.
540         (skip-chars-forward " \t")
541         (unless (eobp)
542           (forward-char 1))))))
543
544 (defun rfc2047-unfold-field ()
545   "Fold the current line."
546   (save-excursion
547     (save-restriction
548       (rfc2047-narrow-to-field)
549       (rfc2047-unfold-region (point-min) (point-max)))))
550
551 (defun rfc2047-unfold-region (b e)
552   "Unfold lines in region B to E."
553   (save-restriction
554     (narrow-to-region b e)
555     (goto-char (point-min))
556     (let ((bol (save-restriction
557                  (widen)
558                  (point-at-bol)))
559           (eol (point-at-eol)))
560       (forward-line 1)
561       (while (not (eobp))
562         (if (and (looking-at "[ \t]")
563                  (< (- (point-at-eol) bol) 76))
564             (delete-region eol (progn
565                                  (goto-char eol)
566                                  (skip-chars-forward "\r\n")
567                                  (point)))
568           (setq bol (point-at-bol)))
569         (setq eol (point-at-eol))
570         (forward-line 1)))))
571
572 (defun rfc2047-b-encode-region (b e)
573   "Base64-encode the header contained in region B to E."
574   (save-restriction
575     (narrow-to-region (goto-char b) e)
576     (while (not (eobp))
577       (base64-encode-region (point) (progn (end-of-line) (point)) t)
578       (if (and (bolp) (eolp))
579           (delete-backward-char 1))
580       (forward-line))))
581
582 (defun rfc2047-q-encode-region (b e)
583   "Quoted-printable-encode the header in region B to E."
584   (save-excursion
585     (save-restriction
586       (narrow-to-region (goto-char b) e)
587       (let ((bol (save-restriction
588                    (widen)
589                    (point-at-bol))))
590         (quoted-printable-encode-region
591          b e nil
592          ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
593          ;; Avoid using 8bit characters.
594          ;; This list excludes `especials' (see the RFC2047 syntax),
595          ;; meaning that some characters in non-structured fields will
596          ;; get encoded when they con't need to be.  The following is
597          ;; what it used to be.
598 ;;;      ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
599 ;;;      "\010\012\014\040-\074\076\100-\136\140-\177")
600          "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
601         (subst-char-in-region (point-min) (point-max) ?  ?_)
602         ;; The size of QP encapsulation is about 20, so set limit to
603         ;; 56=76-20.
604         (unless (< (- (point-max) (point-min)) 56)
605           ;; Don't break if it could fit in one line.
606           ;; Let rfc2047-encode-region break it later.
607           (goto-char (1+ (point-min)))
608           (while (and (not (bobp)) (not (eobp)))
609             (goto-char (min (point-max) (+ 56 bol)))
610             (search-backward "=" (- (point) 2) t)
611             (unless (or (bobp) (eobp))
612               (insert ?\n)
613               (setq bol (point)))))))))
614
615 ;;;
616 ;;; Functions for decoding RFC2047 messages
617 ;;;
618
619 (eval-and-compile
620   (defconst rfc2047-encoded-word-regexp
621     "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\
622 \\?\\(B\\|Q\\)\\?\\([!->@-~ ]*\\)\\?="))
623
624 ;; Fixme: This should decode in place, not cons intermediate strings.
625 ;; Also check whether it needs to worry about delimiting fields like
626 ;; encoding.
627
628 ;; In fact it's reported that (invalid) encoding of mailboxes in
629 ;; addr-specs is in use, so delimiting fields might help.  Probably
630 ;; not decoding a word which isn't properly delimited is good enough
631 ;; and worthwhile (is it more correct or not?), e.g. something like
632 ;; `=?iso-8859-1?q?foo?=@'.
633
634 (defun rfc2047-decode-region (start end)
635   "Decode MIME-encoded words in region between START and END."
636   (interactive "r")
637   (let ((case-fold-search t)
638         b e)
639     (save-excursion
640       (save-restriction
641         (narrow-to-region start end)
642         (goto-char (point-min))
643         ;; Remove whitespace between encoded words.
644         (while (re-search-forward
645                 (eval-when-compile
646                   (concat "\\(" rfc2047-encoded-word-regexp "\\)"
647                           "\\(\n?[ \t]\\)+"
648                           "\\(" rfc2047-encoded-word-regexp "\\)"))
649                 nil t)
650           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
651         ;; Decode the encoded words.
652         (setq b (goto-char (point-min)))
653         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
654           (setq e (match-beginning 0))
655           (insert (rfc2047-parse-and-decode
656                    (prog1
657                        (match-string 0)
658                      (delete-region (match-beginning 0) (match-end 0)))))
659           ;; Remove newlines between decoded words, though such things
660           ;; essentially must not be there.
661           (save-restriction
662             (narrow-to-region e (point))
663             (goto-char e)
664             (while (re-search-forward "[\n\r]+" nil t)
665               (replace-match " "))
666             (goto-char (point-max)))
667           (when (and (mm-multibyte-p)
668                      mail-parse-charset
669                      (not (eq mail-parse-charset 'us-ascii))
670                      (not (eq mail-parse-charset 'gnus-decoded)))
671             (mm-decode-coding-region b e mail-parse-charset))
672           (setq b (point)))
673         (when (and (mm-multibyte-p)
674                    mail-parse-charset
675                    (not (eq mail-parse-charset 'us-ascii))
676                    (not (eq mail-parse-charset 'gnus-decoded)))
677           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
678
679 (defun rfc2047-decode-string (string)
680   "Decode the quoted-printable-encoded STRING and return the results."
681   (let ((m (mm-multibyte-p)))
682     (if (string-match "=\\?" string)
683         (with-temp-buffer
684           ;; Fixme: This logic is wrong, but seems to be required by
685           ;; Gnus summary buffer generation.  The value of `m' depends
686           ;; on the current buffer, not global multibyteness or that
687           ;; of the string.  Also the string returned should always be
688           ;; multibyte in a multibyte session, i.e. the buffer should
689           ;; be multibyte before `buffer-string' is called.
690           (when m
691             (mm-enable-multibyte))
692           (insert string)
693           (inline
694             (rfc2047-decode-region (point-min) (point-max)))
695           (buffer-string))
696       ;; Fixme: As above, `m' here is inappropriate.
697       (if (and m
698                mail-parse-charset
699                (not (eq mail-parse-charset 'us-ascii))
700                (not (eq mail-parse-charset 'gnus-decoded)))
701           ;; `decode-coding-string' in Emacs offers a third optional
702           ;; arg NOCOPY to avoid consing a new string if the decoding
703           ;; is "trivial".  Unfortunately it currently doesn't
704           ;; consider anything else than a `nil' coding system
705           ;; trivial.
706           ;; `rfc2047-decode-string' is called multiple times for each
707           ;; article during summary buffer generation, and we really
708           ;; want to avoid unnecessary consing.  So we bypass
709           ;; `decode-coding-string' if the string is purely ASCII.
710           (if (and (fboundp 'detect-coding-string)
711                    ;; string is purely ASCII
712                    (eq (detect-coding-string string t) 'undecided))
713               string
714             (mm-decode-coding-string string mail-parse-charset))
715         (mm-string-as-multibyte string)))))
716
717 (defun rfc2047-parse-and-decode (word)
718   "Decode WORD and return it if it is an encoded word.
719 Return WORD if it is not not an encoded word or if the charset isn't
720 decodable."
721   (if (not (string-match rfc2047-encoded-word-regexp word))
722       word
723     (or
724      (condition-case nil
725          (rfc2047-decode
726           (match-string 1 word)
727           (string-to-char (match-string 2 word))
728           (match-string 3 word))
729        (error word))
730      word)))                            ; un-decodable
731
732 (defun rfc2047-pad-base64 (string)
733   "Pad STRING to quartets."
734   ;; Be more liberal to accept buggy base64 strings. If
735   ;; base64-decode-string accepts buggy strings, this function could
736   ;; be aliased to identity.
737   (if (= 0 (mod (length string) 4))
738       string
739     (when (string-match "=+$" string)
740       (setq string (substring string 0 (match-beginning 0))))
741     (case (mod (length string) 4)
742       (0 string)
743       (1 string) ;; Error, don't pad it.
744       (2 (concat string "=="))
745       (3 (concat string "=")))))
746
747 (defun rfc2047-decode (charset encoding string)
748   "Decode STRING from the given MIME CHARSET in the given ENCODING.
749 Valid ENCODINGs are the characters \"B\" and \"Q\".
750 If your Emacs implementation can't decode CHARSET, return nil."
751   (if (stringp charset)
752       (setq charset (intern (downcase charset))))
753   (if (or (not charset)
754           (eq 'gnus-all mail-parse-ignored-charsets)
755           (memq 'gnus-all mail-parse-ignored-charsets)
756           (memq charset mail-parse-ignored-charsets))
757       (setq charset mail-parse-charset))
758   (let ((cs (mm-charset-to-coding-system charset)))
759     (if (and (not cs) charset
760              (listp mail-parse-ignored-charsets)
761              (memq 'gnus-unknown mail-parse-ignored-charsets))
762         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
763     (when cs
764       (when (and (eq cs 'ascii)
765                  mail-parse-charset)
766         (setq cs mail-parse-charset))
767       (mm-decode-coding-string
768        (cond
769         ((char-equal ?B encoding)
770          (base64-decode-string
771           (rfc2047-pad-base64 string)))
772         ((char-equal ?Q encoding)
773          (quoted-printable-decode-string
774           (mm-subst-char-in-string ?_ ? string t)))
775         (t (error "Invalid encoding: %c" encoding)))
776        cs))))
777
778 (provide 'rfc2047)
779
780 ;;; rfc2047.el ends here