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