(rfc2047-point-at-bol, rfc2047-point-at-bol): Eval
[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 (not (equal charsets (list message-posting-charset))))))
259
260 ;; Use this syntax table when parsing into regions that may need
261 ;; encoding.  Double quotes are string delimiters, backslash is
262 ;; character quoting, and all other RFC 2822 special characters are
263 ;; treated as punctuation so we can use forward-sexp/forward-word to
264 ;; skip to the end of regions appropriately.  Nb. ietf-drums does
265 ;; things differently.
266 (defconst rfc2047-syntax-table
267   ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
268   (let ((table (make-syntax-table)))
269     ;; The following is done to work for setting all elements of the table
270     ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
271     ;; Play safe and don't assume the form of the word syntax entry --
272     ;; copy it from ?a.
273     (if (fboundp 'set-char-table-range) ; Emacs
274         (set-char-table-range table t (aref (standard-syntax-table) ?a))
275       (if (fboundp 'put-char-table)
276           (if (fboundp 'get-char-table) ; warning avoidance
277               (put-char-table t (get-char-table ?a (standard-syntax-table))
278                               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     (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     table))
292
293 (defun rfc2047-encode-region (b e)
294   "Encode words in region B to E that need encoding.
295 By default, the region is treated as containing RFC2822 addresses.
296 Dynamically bind `rfc2047-encoding-type' to change that."
297   (save-restriction
298     (narrow-to-region b e)
299     (if (eq 'mime rfc2047-encoding-type)
300         ;; Simple case -- treat as single word.
301         (progn
302           (goto-char (point-min))
303           ;; Does it need encoding?
304           (skip-chars-forward "\000-\177" e)
305           (unless (eobp)
306             (rfc2047-encode b e)))
307       ;; `address-mime' case -- take care of quoted words, comments.
308       (with-syntax-table rfc2047-syntax-table
309         (let ((start)                   ; start of current token
310               end                       ; end of current token
311               ;; Whether there's an encoded word before the current
312               ;; token, either immediately or separated by space.
313               last-encoded)
314           (goto-char (point-min))
315           (condition-case nil           ; in case of unbalanced quotes
316               ;; Look for rfc2822-style: sequences of atoms, quoted
317               ;; strings, specials, whitespace.  (Specials mustn't be
318               ;; encoded.)
319               (while (not (eobp))
320                 (setq start (point))
321                 ;; Skip whitespace.
322                 (unless (= 0 (skip-chars-forward " \t\n"))
323                   (setq start (point)))
324                 (cond
325                  ((not (char-after)))   ; eob
326                  ;; else token start
327                  ((eq ?\" (char-syntax (char-after)))
328                   ;; Quoted word.
329                   (forward-sexp)
330                   (setq end (point))
331                   ;; Does it need encoding?
332                   (goto-char start)
333                   (skip-chars-forward "\000-\177" end)
334                   (if (= end (point))
335                       (setq last-encoded  nil)
336                     ;; It needs encoding.  Strip the quotes first,
337                     ;; since encoded words can't occur in quotes.
338                     (goto-char end)
339                     (delete-backward-char 1)
340                     (goto-char start)
341                     (delete-char 1)
342                     (when last-encoded
343                       ;; There was a preceding quoted word.  We need
344                       ;; to include any separating whitespace in this
345                       ;; word to avoid it getting lost.
346                       (skip-chars-backward " \t")
347                       ;; A space is needed between the encoded words.
348                       (insert ? )
349                       (setq start (point)
350                             end (1+ end)))
351                     ;; Adjust the end position for the deleted quotes.
352                     (rfc2047-encode start (- end 2))
353                     (setq last-encoded t))) ; record that it was encoded
354                  ((eq ?. (char-syntax (char-after)))
355                   ;; Skip other delimiters, but record that they've
356                   ;; potentially separated quoted words.
357                   (forward-char)
358                   (setq last-encoded nil))
359                  (t                 ; normal token/whitespace sequence
360                   ;; Find the end.
361                   (forward-word 1)
362                   (skip-chars-backward " \t")
363                   (setq end (point))
364                   ;; Deal with encoding and leading space as for
365                   ;; quoted words.
366                   (goto-char start)
367                   (skip-chars-forward "\000-\177" end)
368                   (if (= end (point))
369                       (setq last-encoded  nil)
370                     (when last-encoded
371                       (goto-char start)
372                       (skip-chars-backward " \t")
373                       (insert ? )
374                       (setq start (point)
375                             end (1+ end)))
376                     (rfc2047-encode start end)
377                     (setq last-encoded t)))))
378             (error (error "Invalid data for rfc2047 encoding: %s"
379                           (buffer-substring b e)))))))
380     (rfc2047-fold-region b (point))))
381
382 (defun rfc2047-encode-string (string)
383   "Encode words in STRING.
384 By default, the string is treated as containing addresses (see
385 `rfc2047-special-chars')."
386   (with-temp-buffer
387     (insert string)
388     (rfc2047-encode-region (point-min) (point-max))
389     (buffer-string)))
390
391 (defun rfc2047-encode (b e)
392   "Encode the word(s) in the region B to E.
393 By default, the region is treated as containing addresses (see
394 `rfc2047-special-chars')."
395   (let* ((mime-charset (mm-find-mime-charset-region b e))
396          (cs (if (> (length mime-charset) 1)
397                  ;; Fixme: Instead of this, try to break region into
398                  ;; parts that can be encoded separately.
399                  (error "Can't rfc2047-encode `%s'"
400                         (buffer-substring b e))
401                (setq mime-charset (car mime-charset))
402                (mm-charset-to-coding-system mime-charset)))
403          ;; Fixme: Better, calculate the number of non-ASCII
404          ;; characters, at least for 8-bit charsets.
405          (encoding (if (assq mime-charset
406                              rfc2047-charset-encoding-alist)
407                        (cdr (assq mime-charset
408                                   rfc2047-charset-encoding-alist))
409                      'B))
410          (start (concat
411                  "=?" (downcase (symbol-name mime-charset)) "?"
412                  (downcase (symbol-name encoding)) "?"))
413          (first t))
414     (if mime-charset
415         (save-restriction
416           (narrow-to-region b e)
417           (when (eq encoding 'B)
418             ;; break into lines before encoding
419             (goto-char (point-min))
420             (while (not (eobp))
421               (goto-char (min (point-max) (+ 15 (point))))
422               (unless (eobp)
423                 (insert ?\n))))
424           (if (and (mm-multibyte-p)
425                    (mm-coding-system-p cs))
426               (mm-encode-coding-region (point-min) (point-max) cs))
427           (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
428                    (point-min) (point-max))
429           (goto-char (point-min))
430           (while (not (eobp))
431             (unless first
432               (insert ? ))
433             (setq first nil)
434             (insert start)
435             (end-of-line)
436             (insert "?=")
437             (forward-line 1))))))
438
439 (defun rfc2047-fold-field ()
440   "Fold the current header field."
441   (save-excursion
442     (save-restriction
443       (rfc2047-narrow-to-field)
444       (rfc2047-fold-region (point-min) (point-max)))))
445
446 (defun rfc2047-fold-region (b e)
447   "Fold long lines in region B to E."
448   (save-restriction
449     (narrow-to-region b e)
450     (goto-char (point-min))
451     (let ((break nil)
452           (qword-break nil)
453           (first t)
454           (bol (save-restriction
455                  (widen)
456                  (rfc2047-point-at-bol))))
457       (while (not (eobp))
458         (when (and (or break qword-break)
459                    (> (- (point) bol) 76))
460           (goto-char (or break qword-break))
461           (setq break nil
462                 qword-break nil)
463           (if (looking-at "[ \t]")
464               (insert ?\n)
465             (insert "\n "))
466           (setq bol (1- (point)))
467           ;; Don't break before the first non-LWSP characters.
468           (skip-chars-forward " \t")
469           (unless (eobp)
470             (forward-char 1)))
471         (cond
472          ((eq (char-after) ?\n)
473           (forward-char 1)
474           (setq bol (point)
475                 break nil
476                 qword-break nil)
477           (skip-chars-forward " \t")
478           (unless (or (eobp) (eq (char-after) ?\n))
479             (forward-char 1)))
480          ((eq (char-after) ?\r)
481           (forward-char 1))
482          ((memq (char-after) '(?  ?\t))
483           (skip-chars-forward " \t")
484           (if first
485               ;; Don't break just after the header name.
486               (setq first nil)
487             (setq break (1- (point)))))
488          ((not break)
489           (if (not (looking-at "=\\?[^=]"))
490               (if (eq (char-after) ?=)
491                   (forward-char 1)
492                 (skip-chars-forward "^ \t\n\r="))
493             (setq qword-break (point))
494             (skip-chars-forward "^ \t\n\r")))
495          (t
496           (skip-chars-forward "^ \t\n\r"))))
497       (when (and (or break qword-break)
498                  (> (- (point) bol) 76))
499         (goto-char (or break qword-break))
500         (setq break nil
501               qword-break nil)
502           (if (looking-at "[ \t]")
503               (insert ?\n)
504             (insert "\n "))
505         (setq bol (1- (point)))
506         ;; Don't break before the first non-LWSP characters.
507         (skip-chars-forward " \t")
508         (unless (eobp)
509           (forward-char 1))))))
510
511 (defun rfc2047-unfold-field ()
512   "Fold the current line."
513   (save-excursion
514     (save-restriction
515       (rfc2047-narrow-to-field)
516       (rfc2047-unfold-region (point-min) (point-max)))))
517
518 (defun rfc2047-unfold-region (b e)
519   "Unfold lines in region B to E."
520   (save-restriction
521     (narrow-to-region b e)
522     (goto-char (point-min))
523     (let ((bol (save-restriction
524                  (widen)
525                  (rfc2047-point-at-bol)))
526           (eol (rfc2047-point-at-eol)))
527       (forward-line 1)
528       (while (not (eobp))
529         (if (and (looking-at "[ \t]")
530                  (< (- (rfc2047-point-at-eol) bol) 76))
531             (delete-region eol (progn
532                                  (goto-char eol)
533                                  (skip-chars-forward "\r\n")
534                                  (point)))
535           (setq bol (rfc2047-point-at-bol)))
536         (setq eol (rfc2047-point-at-eol))
537         (forward-line 1)))))
538
539 (defun rfc2047-b-encode-region (b e)
540   "Base64-encode the header contained in region B to E."
541   (save-restriction
542     (narrow-to-region (goto-char b) e)
543     (while (not (eobp))
544       (base64-encode-region (point) (progn (end-of-line) (point)) t)
545       (if (and (bolp) (eolp))
546           (delete-backward-char 1))
547       (forward-line))))
548
549 (defun rfc2047-q-encode-region (b e)
550   "Quoted-printable-encode the header in region B to E."
551   (save-excursion
552     (save-restriction
553       (narrow-to-region (goto-char b) e)
554       (let ((alist rfc2047-q-encoding-alist)
555             (bol (save-restriction
556                    (widen)
557                    (rfc2047-point-at-bol))))
558         (while alist
559           (when (looking-at (caar alist))
560             (quoted-printable-encode-region b e nil (cdar alist))
561             (subst-char-in-region (point-min) (point-max) ?  ?_)
562             (setq alist nil))
563           (pop alist))
564         ;; The size of QP encapsulation is about 20, so set limit to
565         ;; 56=76-20.
566         (unless (< (- (point-max) (point-min)) 56)
567           ;; Don't break if it could fit in one line.
568           ;; Let rfc2047-encode-region break it later.
569           (goto-char (1+ (point-min)))
570           (while (and (not (bobp)) (not (eobp)))
571             (goto-char (min (point-max) (+ 56 bol)))
572             (search-backward "=" (- (point) 2) t)
573             (unless (or (bobp) (eobp))
574               (insert ?\n)
575               (setq bol (point)))))))))
576
577 ;;;
578 ;;; Functions for decoding RFC2047 messages
579 ;;;
580
581 (eval-and-compile
582   (defconst rfc2047-encoded-word-regexp
583     "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
584 \\?\\([!->@-~ +]*\\)\\?="))
585
586 ;; Fixme: This should decode in place, not cons intermediate strings.
587 ;; Also check whether it needs to worry about delimiting fields like
588 ;; encoding.
589
590 (defun rfc2047-decode-region (start end)
591   "Decode MIME-encoded words in region between START and END."
592   (interactive "r")
593   (let ((case-fold-search t)
594         b e)
595     (save-excursion
596       (save-restriction
597         (narrow-to-region start end)
598         (goto-char (point-min))
599         ;; Remove whitespace between encoded words.
600         (while (re-search-forward
601                 (eval-when-compile
602                   (concat "\\(" rfc2047-encoded-word-regexp "\\)"
603                           "\\(\n?[ \t]\\)+"
604                           "\\(" rfc2047-encoded-word-regexp "\\)"))
605                 nil t)
606           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
607         ;; Decode the encoded words.
608         (setq b (goto-char (point-min)))
609         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
610           (setq e (match-beginning 0))
611           (insert (rfc2047-parse-and-decode
612                    (prog1
613                        (match-string 0)
614                      (delete-region (match-beginning 0) (match-end 0)))))
615           ;; Remove newlines between decoded words, though such things
616           ;; essentially must not be there.
617           (save-restriction
618             (narrow-to-region e (point))
619             (goto-char e)
620             (while (re-search-forward "[\n\r]+" nil t)
621               (replace-match " "))
622             (goto-char (point-max)))
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 e mail-parse-charset))
628           (setq b (point)))
629         (when (and (mm-multibyte-p)
630                    mail-parse-charset
631                    (not (eq mail-parse-charset 'us-ascii))
632                    (not (eq mail-parse-charset 'gnus-decoded)))
633           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
634
635 (defun rfc2047-decode-string (string)
636   "Decode the quoted-printable-encoded STRING and return the results."
637   (let ((m (mm-multibyte-p)))
638     (if (string-match "=\\?" string)
639         (with-temp-buffer
640           ;; Fixme: This logic is wrong, but seems to be required by
641           ;; Gnus summary buffer generation.  The value of `m' depends
642           ;; on the current buffer, not global multibyteness or that
643           ;; of the string.  Also the string returned should always be
644           ;; multibyte in a multibyte session, i.e. the buffer should
645           ;; be multibyte before `buffer-string' is called.
646           (when m
647             (mm-enable-multibyte))
648           (insert string)
649           (inline
650             (rfc2047-decode-region (point-min) (point-max)))
651           (buffer-string))
652       ;; Fixme: As above, `m' here is inappropriate.
653       (if (and m
654                mail-parse-charset
655                (not (eq mail-parse-charset 'us-ascii))
656                (not (eq mail-parse-charset 'gnus-decoded)))
657           (mm-decode-coding-string string mail-parse-charset)
658         (mm-string-as-multibyte string)))))
659
660 (defun rfc2047-parse-and-decode (word)
661   "Decode WORD and return it if it is an encoded word.
662 Return WORD if it is not not an encoded word or if the charset isn't
663 decodable."
664   (if (not (string-match rfc2047-encoded-word-regexp word))
665       word
666     (or
667      (condition-case nil
668          (rfc2047-decode
669           (match-string 1 word)
670           (upcase (match-string 2 word))
671           (match-string 3 word))
672        (error word))
673      word)))                            ; un-decodable
674
675 (defun rfc2047-pad-base64 (string)
676   "Pad STRING to quartets."
677   ;; Be more liberal to accept buggy base64 strings. If
678   ;; base64-decode-string accepts buggy strings, this function could
679   ;; be aliased to identity.
680   (case (mod (length string) 4)
681     (0 string)
682     (1 string) ;; Error, don't pad it.
683     (2 (concat string "=="))
684     (3 (concat string "="))))
685
686 (defun rfc2047-decode (charset encoding string)
687   "Decode STRING from the given MIME CHARSET in the given ENCODING.
688 Valid ENCODINGs are \"B\" and \"Q\".
689 If your Emacs implementation can't decode CHARSET, return nil."
690   (if (stringp charset)
691       (setq charset (intern (downcase charset))))
692   (if (or (not charset)
693           (eq 'gnus-all mail-parse-ignored-charsets)
694           (memq 'gnus-all mail-parse-ignored-charsets)
695           (memq charset mail-parse-ignored-charsets))
696       (setq charset mail-parse-charset))
697   (let ((cs (mm-charset-to-coding-system charset)))
698     (if (and (not cs) charset
699              (listp mail-parse-ignored-charsets)
700              (memq 'gnus-unknown mail-parse-ignored-charsets))
701         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
702     (when cs
703       (when (and (eq cs 'ascii)
704                  mail-parse-charset)
705         (setq cs mail-parse-charset))
706       ;; Fixme: What's this for?  The following comment makes no sense. -- fx
707       (mm-with-unibyte-current-buffer
708         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
709         (mm-decode-coding-string
710          (cond
711           ((equal "B" encoding)
712            (base64-decode-string
713             (rfc2047-pad-base64 string)))
714           ((equal "Q" encoding)
715            (quoted-printable-decode-string
716             (mm-replace-chars-in-string string ?_ ? )))
717           (t (error "Invalid encoding: %s" encoding)))
718          cs)))))
719
720 (provide 'rfc2047)
721
722 ;;; rfc2047.el ends here