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