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