(with-syntax-table): Define if necessary.
[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     (map-char-table (lambda (k v) (modify-syntax-entry k "w" table)) table)
271     (modify-syntax-entry ?\\ "\\" 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     table))
284
285 (defun rfc2047-encode-region (b e)
286   "Encode words in region B to E that need encoding.
287 By default, the region is treated as containing RFC2822 addresses.
288 Dynamically bind `rfc2047-encoding-type' to change that."
289   (save-restriction
290     (narrow-to-region b e)
291     (if (eq 'mime rfc2047-encoding-type)
292         ;; Simple case -- treat as single word.
293         (progn
294           (goto-char (point-min))
295           ;; Does it need encoding?
296           (skip-chars-forward "\000-\177" e)
297           (unless (eobp)
298             (rfc2047-encode b e)))
299       ;; `address-mime' case -- take care of quoted words, comments.
300       (with-syntax-table rfc2047-syntax-table
301         (let ((start)                   ; start of current token
302               end                       ; end of current token
303               ;; Whether there's an encoded word before the current
304               ;; token, either immediately or separated by space.
305               last-encoded)
306           (goto-char (point-min))
307           (condition-case nil         ; in case of unbalanced quotes
308               ;; Look for rfc2822-style: sequences of atoms, quoted
309               ;; strings, specials, whitespace.  (Specials mustn't be
310               ;; encoded.)
311               (while (not (eobp))
312                 (setq start (point))
313                 ;; Skip whitespace.
314                 (unless (= 0 (skip-chars-forward " \t"))
315                   (setq start (point)))
316                 (cond
317                  ((not (char-after)))   ; eob
318                  ;; else token start
319                  ((eq ?\" (char-syntax (char-after)))
320                   ;; Quoted word.
321                   (forward-sexp)
322                   (setq end (point))
323                   ;; Does it need encoding?
324                   (goto-char start)
325                   (skip-chars-forward "\000-\177" end)
326                   (if (= end (point))
327                       (setq last-encoded  nil)
328                     ;; It needs encoding.  Strip the quotes first,
329                     ;; since encoded words can't occur in quotes.
330                     (goto-char end)
331                     (delete-backward-char 1)
332                     (goto-char start)
333                     (delete-char 1)
334                     (when last-encoded
335                       ;; There was a preceding quoted word.  We need
336                       ;; to include any separating whitespace in this
337                       ;; word to avoid it getting lost.
338                       (skip-chars-backward " \t")
339                       ;; A space is needed between the encoded words.
340                       (insert ? )
341                       (setq start (point)
342                             end (1+ end)))
343                     ;; Adjust the end position for the deleted quotes.
344                     (rfc2047-encode start (- end 2))
345                     (setq last-encoded t))) ; record that it was encoded
346                  ((eq ?. (char-syntax (char-after)))
347                   ;; Skip other delimiters, but record that they've
348                   ;; potentially separated quoted words.
349                   (forward-char)
350                   (setq last-encoded nil))
351                  (t                 ; normal token/whitespace sequence
352                   ;; Find the end.
353                   (forward-word 1)
354                   (skip-chars-backward " \t")
355                   (setq end (point))
356                   ;; Deal with encoding and leading space as for
357                   ;; quoted words.
358                   (goto-char start)
359                   (skip-chars-forward "\000-\177" end)
360                   (if (= end (point))
361                       (setq last-encoded  nil)
362                     (when last-encoded
363                       (goto-char start)
364                       (skip-chars-backward " \t")
365                       (insert ? )
366                       (setq start (point)
367                             end (1+ end)))
368                     (rfc2047-encode start end)
369                     (setq last-encoded t)))))
370             (error (error "Invalid data for rfc2047 encoding: %s"
371                           (buffer-substring b e)))))))
372     (rfc2047-fold-region b (point))))
373
374 (defun rfc2047-encode-string (string)
375   "Encode words in STRING.
376 By default, the string is treated as containing addresses (see
377 `rfc2047-special-chars')."
378   (with-temp-buffer
379     (insert string)
380     (rfc2047-encode-region (point-min) (point-max))
381     (buffer-string)))
382
383 (defun rfc2047-encode (b e)
384   "Encode the word(s) in the region B to E.
385 By default, the region is treated as containing addresses (see
386 `rfc2047-special-chars')."
387   (let* ((mime-charset (mm-find-mime-charset-region b e))
388          (cs (if (> (length mime-charset) 1)
389                  ;; Fixme: Instead of this, try to break region into
390                  ;; parts that can be encoded separately.
391                  (error "Can't rfc2047-encode `%s'"
392                         (buffer-substring b e))
393                (setq mime-charset (car mime-charset))
394                (mm-charset-to-coding-system mime-charset)))
395          ;; Fixme: Better, calculate the number of non-ASCII
396          ;; characters, at least for 8-bit charsets.
397          (encoding (if (assq mime-charset
398                              rfc2047-charset-encoding-alist)
399                        (cdr (assq mime-charset
400                                   rfc2047-charset-encoding-alist))
401                      'B))
402          (start (concat
403                  "=?" (downcase (symbol-name mime-charset)) "?"
404                  (downcase (symbol-name encoding)) "?"))
405          (first t))
406     (if mime-charset
407         (save-restriction
408           (narrow-to-region b e)
409           (when (eq encoding 'B)
410             ;; break into lines before encoding
411             (goto-char (point-min))
412             (while (not (eobp))
413               (goto-char (min (point-max) (+ 15 (point))))
414               (unless (eobp)
415                 (insert ?\n))))
416           (if (and (mm-multibyte-p)
417                    (mm-coding-system-p cs))
418               (mm-encode-coding-region (point-min) (point-max) cs))
419           (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
420                    (point-min) (point-max))
421           (goto-char (point-min))
422           (while (not (eobp))
423             (unless first
424               (insert ? ))
425             (setq first nil)
426             (insert start)
427             (end-of-line)
428             (insert "?=")
429             (forward-line 1))))))
430
431 (defun rfc2047-fold-field ()
432   "Fold the current header field."
433   (save-excursion
434     (save-restriction
435       (rfc2047-narrow-to-field)
436       (rfc2047-fold-region (point-min) (point-max)))))
437
438 (defun rfc2047-fold-region (b e)
439   "Fold long lines in region B to E."
440   (save-restriction
441     (narrow-to-region b e)
442     (goto-char (point-min))
443     (let ((break nil)
444           (qword-break nil)
445           (first t)
446           (bol (save-restriction
447                  (widen)
448                  (rfc2047-point-at-bol))))
449       (while (not (eobp))
450         (when (and (or break qword-break)
451                    (> (- (point) bol) 76))
452           (goto-char (or break qword-break))
453           (setq break nil
454                 qword-break nil)
455           (if (looking-at "[ \t]")
456               (insert ?\n)
457             (insert "\n "))
458           (setq bol (1- (point)))
459           ;; Don't break before the first non-LWSP characters.
460           (skip-chars-forward " \t")
461           (unless (eobp)
462             (forward-char 1)))
463         (cond
464          ((eq (char-after) ?\n)
465           (forward-char 1)
466           (setq bol (point)
467                 break nil
468                 qword-break nil)
469           (skip-chars-forward " \t")
470           (unless (or (eobp) (eq (char-after) ?\n))
471             (forward-char 1)))
472          ((eq (char-after) ?\r)
473           (forward-char 1))
474          ((memq (char-after) '(?  ?\t))
475           (skip-chars-forward " \t")
476           (if first
477               ;; Don't break just after the header name.
478               (setq first nil)
479             (setq break (1- (point)))))
480          ((not break)
481           (if (not (looking-at "=\\?[^=]"))
482               (if (eq (char-after) ?=)
483                   (forward-char 1)
484                 (skip-chars-forward "^ \t\n\r="))
485             (setq qword-break (point))
486             (skip-chars-forward "^ \t\n\r")))
487          (t
488           (skip-chars-forward "^ \t\n\r"))))
489       (when (and (or break qword-break)
490                  (> (- (point) bol) 76))
491         (goto-char (or break qword-break))
492         (setq break nil
493               qword-break nil)
494           (if (looking-at "[ \t]")
495               (insert ?\n)
496             (insert "\n "))
497         (setq bol (1- (point)))
498         ;; Don't break before the first non-LWSP characters.
499         (skip-chars-forward " \t")
500         (unless (eobp)
501           (forward-char 1))))))
502
503 (defun rfc2047-unfold-field ()
504   "Fold the current line."
505   (save-excursion
506     (save-restriction
507       (rfc2047-narrow-to-field)
508       (rfc2047-unfold-region (point-min) (point-max)))))
509
510 (defun rfc2047-unfold-region (b e)
511   "Unfold lines in region B to E."
512   (save-restriction
513     (narrow-to-region b e)
514     (goto-char (point-min))
515     (let ((bol (save-restriction
516                  (widen)
517                  (rfc2047-point-at-bol)))
518           (eol (rfc2047-point-at-eol))
519           leading)
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 ((alist rfc2047-q-encoding-alist)
548             (bol (save-restriction
549                    (widen)
550                    (rfc2047-point-at-bol))))
551         (while alist
552           (when (looking-at (caar alist))
553             (quoted-printable-encode-region b e nil (cdar alist))
554             (subst-char-in-region (point-min) (point-max) ?  ?_)
555             (setq alist nil))
556           (pop alist))
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     (condition-case nil
660         (rfc2047-decode
661          (match-string 1 word)
662          (upcase (match-string 2 word))
663          (match-string 3 word))
664       (error word))))
665
666 (defun rfc2047-pad-base64 (string)
667   "Pad STRING to quartets."
668   ;; Be more liberal to accept buggy base64 strings. If
669   ;; base64-decode-string accepts buggy strings, this function could
670   ;; be aliased to identity.
671   (case (mod (length string) 4)
672     (0 string)
673     (1 string) ;; Error, don't pad it.
674     (2 (concat string "=="))
675     (3 (concat string "="))))
676
677 (defun rfc2047-decode (charset encoding string)
678   "Decode STRING from the given MIME CHARSET in the given ENCODING.
679 Valid ENCODINGs are \"B\" and \"Q\".
680 If your Emacs implementation can't decode CHARSET, return nil."
681   (if (stringp charset)
682       (setq charset (intern (downcase charset))))
683   (if (or (not charset)
684           (eq 'gnus-all mail-parse-ignored-charsets)
685           (memq 'gnus-all mail-parse-ignored-charsets)
686           (memq charset mail-parse-ignored-charsets))
687       (setq charset mail-parse-charset))
688   (let ((cs (mm-charset-to-coding-system charset)))
689     (if (and (not cs) charset
690              (listp mail-parse-ignored-charsets)
691              (memq 'gnus-unknown mail-parse-ignored-charsets))
692         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
693     (when cs
694       (when (and (eq cs 'ascii)
695                  mail-parse-charset)
696         (setq cs mail-parse-charset))
697       ;; Fixme: What's this for?  The following comment makes no sense. -- fx
698       (mm-with-unibyte-current-buffer
699         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
700         (mm-decode-coding-string
701          (cond
702           ((equal "B" encoding)
703            (base64-decode-string
704             (rfc2047-pad-base64 string)))
705           ((equal "Q" encoding)
706            (quoted-printable-decode-string
707             (mm-replace-chars-in-string string ?_ ? )))
708           (t (error "Invalid encoding: %s" encoding)))
709          cs)))))
710
711 (provide 'rfc2047)
712
713 ;;; rfc2047.el ends here