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