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