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