(rfc2047-encode-region): Skip \n as whitespace.
[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 ;; Avoid gnus-util for mm- code.
59 (defalias 'rfc2047-point-at-bol
60   (if (fboundp 'point-at-bol)
61       'point-at-bol
62     'line-beginning-position))
63
64 (defalias 'rfc2047-point-at-eol
65   (if (fboundp 'point-at-eol)
66       'point-at-eol
67     'line-end-position))
68
69 (defvar rfc2047-header-encoding-alist
70   '(("Newsgroups" . nil)
71     ("Followup-To" . nil)
72     ("Message-ID" . nil)
73     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
74      address-mime)
75     (t . mime))
76   "*Header/encoding method alist.
77 The list is traversed sequentially.  The keys can either be
78 header regexps or t.
79
80 The values can be:
81
82 1) nil, in which case no encoding is done;
83 2) `mime', in which case the header will be encoded according to RFC2047;
84 3) `address-mime', like `mime', but takes account of the rules for address
85    fields (where quoted strings and comments must be treated separately);
86 4) a charset, in which case it will be encoded as that charset;
87 5) `default', in which case the field will be encoded as the rest
88    of the article.")
89
90 (defvar rfc2047-charset-encoding-alist
91   '((us-ascii . nil)
92     (iso-8859-1 . Q)
93     (iso-8859-2 . Q)
94     (iso-8859-3 . Q)
95     (iso-8859-4 . Q)
96     (iso-8859-5 . B)
97     (koi8-r . B)
98     (iso-8859-7 . B)
99     (iso-8859-8 . B)
100     (iso-8859-9 . Q)
101     (iso-8859-14 . Q)
102     (iso-8859-15 . Q)
103     (iso-2022-jp . B)
104     (iso-2022-kr . B)
105     (gb2312 . B)
106     (big5 . B)
107     (cn-big5 . B)
108     (cn-gb . B)
109     (cn-gb-2312 . B)
110     (euc-kr . B)
111     (iso-2022-jp-2 . B)
112     (iso-2022-int-1 . B))
113   "Alist of MIME charsets to RFC2047 encodings.
114 Valid encodings are nil, `Q' and `B'.  These indicate binary (no) encoding,
115 quoted-printable and base64 respectively.")
116
117 (defvar rfc2047-encoding-function-alist
118   '((Q . rfc2047-q-encode-region)
119     (B . rfc2047-b-encode-region)
120     (nil . ignore))
121   "Alist of RFC2047 encodings to encoding functions.")
122
123 (defvar rfc2047-q-encoding-alist
124   '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
125      . "-A-Za-z0-9!*+/" )
126     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
127     ;; Avoid using 8bit characters.
128     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
129     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
130   "Alist of header regexps and valid Q characters.")
131
132 ;;;
133 ;;; Functions for encoding RFC2047 messages
134 ;;;
135
136 (defun rfc2047-narrow-to-field ()
137   "Narrow the buffer to the header on the current line."
138   (beginning-of-line)
139   (narrow-to-region
140    (point)
141    (progn
142      (forward-line 1)
143      (if (re-search-forward "^[^ \n\t]" nil t)
144          (progn
145            (beginning-of-line)
146            (point))
147        (point-max))))
148   (goto-char (point-min)))
149
150 (defun rfc2047-field-value ()
151   "Return the value of the field at point."
152   (save-excursion
153     (save-restriction
154       (rfc2047-narrow-to-field)
155       (re-search-forward ":[ \t\n]*" nil t)
156       (buffer-substring (point) (point-max)))))
157
158 (defvar rfc2047-encoding-type 'address-mime
159   "The type of encoding done by `rfc2047-encode-region'.
160 This should be dynamically bound around calls to
161 `rfc2047-encode-region' to either `mime' or `address-mime'.  See
162 `rfc2047-header-encoding-alist', for definitions.")
163
164 (defun rfc2047-encode-message-header ()
165   "Encode the message header according to `rfc2047-header-encoding-alist'.
166 Should be called narrowed to the head of the message."
167   (interactive "*")
168   (save-excursion
169     (goto-char (point-min))
170     (let (alist elem method)
171       (while (not (eobp))
172         (save-restriction
173           (rfc2047-narrow-to-field)
174           (if (not (rfc2047-encodable-p))
175               (prog1
176                 (if (and (eq (mm-body-7-or-8) '8bit)
177                          (mm-multibyte-p)
178                          (mm-coding-system-p
179                           (car message-posting-charset)))
180                     ;; 8 bit must be decoded.
181                     (mm-encode-coding-region
182                      (point-min) (point-max)
183                      (mm-charset-to-coding-system
184                       (car message-posting-charset))))
185                 ;; No encoding necessary, but folding is nice
186                 (rfc2047-fold-region
187                  (save-excursion
188                    (goto-char (point-min))
189                    (skip-chars-forward "^:")
190                    (when (looking-at ": ")
191                      (forward-char 2))
192                    (point))
193                  (point-max)))
194             ;; We found something that may perhaps be encoded.
195             (setq method nil
196                   alist rfc2047-header-encoding-alist)
197             (while (setq elem (pop alist))
198               (when (or (and (stringp (car elem))
199                              (looking-at (car elem)))
200                         (eq (car elem) t))
201                 (setq alist nil
202                       method (cdr elem))))
203             (goto-char (point-min))
204             (re-search-forward "^[^:]+: *" nil t)
205             (cond
206              ((eq method 'address-mime)
207               (rfc2047-encode-region (point) (point-max)))
208              ((eq method 'mime)
209               (let (rfc2047-encoding-type)
210                 (rfc2047-encode-region (point) (point-max))))
211              ((eq method 'default)
212               (if (and (featurep 'mule)
213                        (if (boundp 'default-enable-multibyte-characters)
214                            default-enable-multibyte-characters)
215                        mail-parse-charset)
216                   (mm-encode-coding-region (point) (point-max)
217                                            mail-parse-charset)))
218              ;; We get this when CC'ing messsages to newsgroups with
219              ;; 8-bit names.  The group name mail copy just got
220              ;; unconditionally encoded.  Previously, it would ask
221              ;; whether to encode, which was quite confusing for the
222              ;; user.  If the new behaviour is wrong, tell me. I have
223              ;; left the old code commented out below.
224              ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
225              ;; Modified by Dave Love, with the commented-out code changed
226              ;; in accordance with changes elsewhere.
227              ((null method)
228               (rfc2047-encode-region (point) (point-max)))
229 ;;;          ((null method)
230 ;;;           (if (or (message-options-get
231 ;;;                    'rfc2047-encode-message-header-encode-any)
232 ;;;                   (message-options-set
233 ;;;                    'rfc2047-encode-message-header-encode-any
234 ;;;                    (y-or-n-p
235 ;;;                     "Some texts are not encoded. Encode anyway?")))
236 ;;;               (rfc2047-encode-region (point-min) (point-max))
237 ;;;             (error "Cannot send unencoded text")))
238              ((mm-coding-system-p method)
239               (if (and (featurep 'mule)
240                        (if (boundp 'default-enable-multibyte-characters)
241                            default-enable-multibyte-characters))
242                   (mm-encode-coding-region (point) (point-max) method)))
243              ;; Hm.
244              (t)))
245           (goto-char (point-max)))))))
246
247 ;; Fixme: This, and the require below may not be the Right Thing, but
248 ;; should be safe just before release.  -- fx 2001-02-08
249 (eval-when-compile (defvar message-posting-charset))
250
251 (defun rfc2047-encodable-p ()
252   "Return non-nil if any characters in current buffer need encoding in headers.
253 The buffer may be narrowed."
254   (require 'message)                    ; for message-posting-charset
255   (let ((charsets
256          (mm-find-mime-charset-region (point-min) (point-max))))
257     (and charsets (not (equal charsets (list message-posting-charset))))))
258
259 ;; Use this syntax table when parsing into regions that may need
260 ;; encoding.  Double quotes are string delimiters, backslash is
261 ;; character quoting, and all other RFC 2822 special characters are
262 ;; treated as punctuation so we can use forward-sexp/forward-word to
263 ;; skip to the end of regions appropriately.  Nb. ietf-drums does
264 ;; things differently.
265 (defconst rfc2047-syntax-table
266   ;; This is what we should do, but XEmacs doesn't support the optional
267   ;; arg of `make-syntax-table':
268 ;;   (let ((table (make-char-table 'syntax-table '(2))))
269   (let ((table (make-syntax-table)))
270     ;; N.b. this currently doesn't work in Emacs 22.
271     (map-char-table (lambda (k v) (modify-syntax-entry k "w" table)) 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-special-chars')."
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-special-chars')."
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           leading)
521       (forward-line 1)
522       (while (not (eobp))
523         (if (and (looking-at "[ \t]")
524                  (< (- (rfc2047-point-at-eol) bol) 76))
525             (delete-region eol (progn
526                                  (goto-char eol)
527                                  (skip-chars-forward "\r\n")
528                                  (point)))
529           (setq bol (rfc2047-point-at-bol)))
530         (setq eol (rfc2047-point-at-eol))
531         (forward-line 1)))))
532
533 (defun rfc2047-b-encode-region (b e)
534   "Base64-encode the header contained in region B to E."
535   (save-restriction
536     (narrow-to-region (goto-char b) e)
537     (while (not (eobp))
538       (base64-encode-region (point) (progn (end-of-line) (point)) t)
539       (if (and (bolp) (eolp))
540           (delete-backward-char 1))
541       (forward-line))))
542
543 (defun rfc2047-q-encode-region (b e)
544   "Quoted-printable-encode the header in region B to E."
545   (save-excursion
546     (save-restriction
547       (narrow-to-region (goto-char b) e)
548       (let ((alist rfc2047-q-encoding-alist)
549             (bol (save-restriction
550                    (widen)
551                    (rfc2047-point-at-bol))))
552         (while alist
553           (when (looking-at (caar alist))
554             (quoted-printable-encode-region b e nil (cdar alist))
555             (subst-char-in-region (point-min) (point-max) ?  ?_)
556             (setq alist nil))
557           (pop alist))
558         ;; The size of QP encapsulation is about 20, so set limit to
559         ;; 56=76-20.
560         (unless (< (- (point-max) (point-min)) 56)
561           ;; Don't break if it could fit in one line.
562           ;; Let rfc2047-encode-region break it later.
563           (goto-char (1+ (point-min)))
564           (while (and (not (bobp)) (not (eobp)))
565             (goto-char (min (point-max) (+ 56 bol)))
566             (search-backward "=" (- (point) 2) t)
567             (unless (or (bobp) (eobp))
568               (insert ?\n)
569               (setq bol (point)))))))))
570
571 ;;;
572 ;;; Functions for decoding RFC2047 messages
573 ;;;
574
575 (eval-and-compile
576   (defconst rfc2047-encoded-word-regexp
577     "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
578 \\?\\([!->@-~ +]*\\)\\?="))
579
580 ;; Fixme: This should decode in place, not cons intermediate strings.
581 ;; Also check whether it needs to worry about delimiting fields like
582 ;; encoding.
583
584 (defun rfc2047-decode-region (start end)
585   "Decode MIME-encoded words in region between START and END."
586   (interactive "r")
587   (let ((case-fold-search t)
588         b e)
589     (save-excursion
590       (save-restriction
591         (narrow-to-region start end)
592         (goto-char (point-min))
593         ;; Remove whitespace between encoded words.
594         (while (re-search-forward
595                 (eval-when-compile
596                   (concat "\\(" rfc2047-encoded-word-regexp "\\)"
597                           "\\(\n?[ \t]\\)+"
598                           "\\(" rfc2047-encoded-word-regexp "\\)"))
599                 nil t)
600           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
601         ;; Decode the encoded words.
602         (setq b (goto-char (point-min)))
603         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
604           (setq e (match-beginning 0))
605           (insert (rfc2047-parse-and-decode
606                    (prog1
607                        (match-string 0)
608                      (delete-region (match-beginning 0) (match-end 0)))))
609           ;; Remove newlines between decoded words, though such things
610           ;; essentially must not be there.
611           (save-restriction
612             (narrow-to-region e (point))
613             (goto-char e)
614             (while (re-search-forward "[\n\r]+" nil t)
615               (replace-match " "))
616             (goto-char (point-max)))
617           (when (and (mm-multibyte-p)
618                      mail-parse-charset
619                      (not (eq mail-parse-charset 'us-ascii))
620                      (not (eq mail-parse-charset 'gnus-decoded)))
621             (mm-decode-coding-region b e mail-parse-charset))
622           (setq b (point)))
623         (when (and (mm-multibyte-p)
624                    mail-parse-charset
625                    (not (eq mail-parse-charset 'us-ascii))
626                    (not (eq mail-parse-charset 'gnus-decoded)))
627           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
628
629 (defun rfc2047-decode-string (string)
630   "Decode the quoted-printable-encoded STRING and return the results."
631   (let ((m (mm-multibyte-p)))
632     (if (string-match "=\\?" string)
633         (with-temp-buffer
634           ;; Fixme: This logic is wrong, but seems to be required by
635           ;; Gnus summary buffer generation.  The value of `m' depends
636           ;; on the current buffer, not global multibyteness or that
637           ;; of the string.  Also the string returned should always be
638           ;; multibyte in a multibyte session, i.e. the buffer should
639           ;; be multibyte before `buffer-string' is called.
640           (when m
641             (mm-enable-multibyte))
642           (insert string)
643           (inline
644             (rfc2047-decode-region (point-min) (point-max)))
645           (buffer-string))
646       ;; Fixme: As above, `m' here is inappropriate.
647       (if (and m
648                mail-parse-charset
649                (not (eq mail-parse-charset 'us-ascii))
650                (not (eq mail-parse-charset 'gnus-decoded)))
651           (mm-decode-coding-string string mail-parse-charset)
652         (mm-string-as-multibyte string)))))
653
654 (defun rfc2047-parse-and-decode (word)
655   "Decode WORD and return it if it is an encoded word.
656 Return WORD if it is not not an encoded word or if the charset isn't
657 decodable."
658   (if (not (string-match rfc2047-encoded-word-regexp word))
659       word
660     (or
661      (condition-case nil
662          (rfc2047-decode
663           (match-string 1 word)
664           (upcase (match-string 2 word))
665           (match-string 3 word))
666        (error word))
667      word)))                            ; un-decodable
668
669 (defun rfc2047-pad-base64 (string)
670   "Pad STRING to quartets."
671   ;; Be more liberal to accept buggy base64 strings. If
672   ;; base64-decode-string accepts buggy strings, this function could
673   ;; be aliased to identity.
674   (case (mod (length string) 4)
675     (0 string)
676     (1 string) ;; Error, don't pad it.
677     (2 (concat string "=="))
678     (3 (concat string "="))))
679
680 (defun rfc2047-decode (charset encoding string)
681   "Decode STRING from the given MIME CHARSET in the given ENCODING.
682 Valid ENCODINGs are \"B\" and \"Q\".
683 If your Emacs implementation can't decode CHARSET, return nil."
684   (if (stringp charset)
685       (setq charset (intern (downcase charset))))
686   (if (or (not charset)
687           (eq 'gnus-all mail-parse-ignored-charsets)
688           (memq 'gnus-all mail-parse-ignored-charsets)
689           (memq charset mail-parse-ignored-charsets))
690       (setq charset mail-parse-charset))
691   (let ((cs (mm-charset-to-coding-system charset)))
692     (if (and (not cs) charset
693              (listp mail-parse-ignored-charsets)
694              (memq 'gnus-unknown mail-parse-ignored-charsets))
695         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
696     (when cs
697       (when (and (eq cs 'ascii)
698                  mail-parse-charset)
699         (setq cs mail-parse-charset))
700       ;; Fixme: What's this for?  The following comment makes no sense. -- fx
701       (mm-with-unibyte-current-buffer
702         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
703         (mm-decode-coding-string
704          (cond
705           ((equal "B" encoding)
706            (base64-decode-string
707             (rfc2047-pad-base64 string)))
708           ((equal "Q" encoding)
709            (quoted-printable-decode-string
710             (mm-replace-chars-in-string string ?_ ? )))
711           (t (error "Invalid encoding: %s" encoding)))
712          cs)))))
713
714 (provide 'rfc2047)
715
716 ;;; rfc2047.el ends here