1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
3 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004
4 ;; Free Software Foundation, Inc.
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
28 ;; Three: Message Header Extensions for Non-ASCII Text".
34 (defvar message-posting-charset))
38 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
41 (autoload 'mm-body-7-or-8 "mm-bodies")
43 (defvar rfc2047-header-encoding-alist
44 '(("Newsgroups" . nil)
47 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\
48 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
50 "*Header/encoding method alist.
51 The list is traversed sequentially. The keys can either be
56 1) nil, in which case no encoding is done;
57 2) `mime', in which case the header will be encoded according to RFC2047;
58 3) `address-mime', like `mime', but takes account of the rules for address
59 fields (where quoted strings and comments must be treated separately);
60 4) a charset, in which case it will be encoded as that charset;
61 5) `default', in which case the field will be encoded as the rest
64 (defvar rfc2047-charset-encoding-alist
88 "Alist of MIME charsets to RFC2047 encodings.
89 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
90 quoted-printable and base64 respectively.")
92 (defvar rfc2047-encode-function-alist
93 '((Q . rfc2047-q-encode-string)
94 (B . rfc2047-b-encode-string)
96 "Alist of RFC2047 encodings to encoding functions.")
98 (defvar rfc2047-encode-encoded-words t
99 "Whether encoded words should be encoded again.")
102 ;;; Functions for encoding RFC2047 messages
105 (defun rfc2047-qp-or-base64 ()
106 "Return the type with which to encode the buffer.
107 This is either `base64' or `quoted-printable'."
109 (let ((limit (min (point-max) (+ 2000 (point-min))))
111 (goto-char (point-min))
112 (skip-chars-forward "\x20-\x7f\r\n\t" limit)
113 (while (< (point) limit)
116 (skip-chars-forward "\x20-\x7f\r\n\t" limit))
117 (if (or (< (* 6 n8bit) (- limit (point-min)))
118 ;; Don't base64, say, a short line with a single
119 ;; non-ASCII char when splitting parts by charset.
124 (defun rfc2047-narrow-to-field ()
125 "Narrow the buffer to the header on the current line."
131 (if (re-search-forward "^[^ \n\t]" nil t)
134 (goto-char (point-min)))
136 (defun rfc2047-field-value ()
137 "Return the value of the field at point."
140 (rfc2047-narrow-to-field)
141 (re-search-forward ":[ \t\n]*" nil t)
142 (buffer-substring-no-properties (point) (point-max)))))
144 (defvar rfc2047-encoding-type 'address-mime
145 "The type of encoding done by `rfc2047-encode-region'.
146 This should be dynamically bound around calls to
147 `rfc2047-encode-region' to either `mime' or `address-mime'. See
148 `rfc2047-header-encoding-alist', for definitions.")
150 (defun rfc2047-encode-message-header ()
151 "Encode the message header according to `rfc2047-header-encoding-alist'.
152 Should be called narrowed to the head of the message."
155 (goto-char (point-min))
156 (let (alist elem method)
159 (rfc2047-narrow-to-field)
160 (if (not (rfc2047-encodable-p))
162 (if (and (eq (mm-body-7-or-8) '8bit)
165 (car message-posting-charset)))
166 ;; 8 bit must be decoded.
167 (mm-encode-coding-region
168 (point-min) (point-max)
169 (mm-charset-to-coding-system
170 (car message-posting-charset))))
171 ;; No encoding necessary, but folding is nice
175 (goto-char (point-min))
176 (skip-chars-forward "^:")
177 (when (looking-at ": ")
181 ;; We found something that may perhaps be encoded.
183 alist rfc2047-header-encoding-alist)
184 (while (setq elem (pop alist))
185 (when (or (and (stringp (car elem))
186 (looking-at (car elem)))
190 (re-search-forward "^[^:]+: *" nil t)
192 ((eq method 'address-mime)
193 (rfc2047-encode-region (point) (point-max)))
195 (let ((rfc2047-encoding-type 'mime))
196 (rfc2047-encode-region (point) (point-max))))
197 ((eq method 'default)
198 (if (and (featurep 'mule)
199 (if (boundp 'default-enable-multibyte-characters)
200 default-enable-multibyte-characters)
202 (mm-encode-coding-region (point) (point-max)
203 mail-parse-charset)))
204 ;; We get this when CC'ing messsages to newsgroups with
205 ;; 8-bit names. The group name mail copy just got
206 ;; unconditionally encoded. Previously, it would ask
207 ;; whether to encode, which was quite confusing for the
208 ;; user. If the new behaviour is wrong, tell me. I have
209 ;; left the old code commented out below.
210 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
211 ;; Modified by Dave Love, with the commented-out code changed
212 ;; in accordance with changes elsewhere.
214 (rfc2047-encode-region (point) (point-max)))
216 ;;; (if (or (message-options-get
217 ;;; 'rfc2047-encode-message-header-encode-any)
218 ;;; (message-options-set
219 ;;; 'rfc2047-encode-message-header-encode-any
221 ;;; "Some texts are not encoded. Encode anyway?")))
222 ;;; (rfc2047-encode-region (point-min) (point-max))
223 ;;; (error "Cannot send unencoded text")))
224 ((mm-coding-system-p method)
225 (if (and (featurep 'mule)
226 (if (boundp 'default-enable-multibyte-characters)
227 default-enable-multibyte-characters))
228 (mm-encode-coding-region (point) (point-max) method)))
231 (goto-char (point-max)))))))
233 ;; Fixme: This, and the require below may not be the Right Thing, but
234 ;; should be safe just before release. -- fx 2001-02-08
235 (eval-when-compile (defvar message-posting-charset))
237 (defun rfc2047-encodable-p ()
238 "Return non-nil if any characters in current buffer need encoding in headers.
239 The buffer may be narrowed."
240 (require 'message) ; for message-posting-charset
242 (mm-find-mime-charset-region (point-min) (point-max))))
243 (goto-char (point-min))
244 (or (and rfc2047-encode-encoded-words
246 (search-forward "=?" nil t)
247 (goto-char (point-min))))
249 (not (equal charsets (list (car message-posting-charset))))))))
251 ;; Use this syntax table when parsing into regions that may need
252 ;; encoding. Double quotes are string delimiters, backslash is
253 ;; character quoting, and all other RFC 2822 special characters are
254 ;; treated as punctuation so we can use forward-sexp/forward-word to
255 ;; skip to the end of regions appropriately. Nb. ietf-drums does
256 ;; things differently.
257 (defconst rfc2047-syntax-table
258 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
259 (let ((table (make-syntax-table)))
260 ;; The following is done to work for setting all elements of the table
261 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
262 ;; Play safe and don't assume the form of the word syntax entry --
264 (if (fboundp 'set-char-table-range) ; Emacs
265 (funcall (intern "set-char-table-range")
266 table t (aref (standard-syntax-table) ?a))
267 (if (fboundp 'put-char-table)
268 (if (fboundp 'get-char-table) ; warning avoidance
269 (put-char-table t (get-char-table ?a (standard-syntax-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)
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."
290 (narrow-to-region b e)
291 (let ((encodable-regexp (if rfc2047-encode-encoded-words
292 "[^\000-\177]+\\|=\\?"
294 start ; start of current token
296 ;; Whether there's an encoded word before the current token,
297 ;; either immediately or separated by space.
299 (orig-text (buffer-substring-no-properties b e)))
300 (if (eq 'mime rfc2047-encoding-type)
301 ;; Simple case. Continuous words in which all those contain
302 ;; non-ASCII characters are encoded collectively. Encoding
303 ;; ASCII words, including `Re:' used in Subject headers, is
304 ;; avoided for interoperability with non-MIME clients and
305 ;; for making it easy to find keywords.
307 (goto-char (point-min))
308 (while (progn (skip-chars-forward " \t\n")
311 (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
313 (setq end (match-end 0))
314 (re-search-forward encodable-regexp end t)))
316 (if (> (point) start)
317 (rfc2047-encode start (point))
319 ;; `address-mime' case -- take care of quoted words, comments.
320 (with-syntax-table rfc2047-syntax-table
321 (goto-char (point-min))
322 (condition-case err ; in case of unbalanced quotes
323 ;; Look for rfc2822-style: sequences of atoms, quoted
324 ;; strings, specials, whitespace. (Specials mustn't be
328 (skip-chars-forward " \t\n")
331 ((not (char-after))) ; eob
333 ((eq ?\" (setq csyntax (char-syntax (char-after))))
337 ;; Does it need encoding?
339 (if (re-search-forward encodable-regexp end 'move)
340 ;; It needs encoding. Strip the quotes first,
341 ;; since encoded words can't occur in quotes.
344 (delete-backward-char 1)
348 ;; There was a preceding quoted word. We need
349 ;; to include any separating whitespace in this
350 ;; word to avoid it getting lost.
351 (skip-chars-backward " \t")
352 ;; A space is needed between the encoded words.
356 ;; Adjust the end position for the deleted quotes.
357 (rfc2047-encode start (- end 2))
358 (setq last-encoded t)) ; record that it was encoded
359 (setq last-encoded nil)))
361 ;; Skip other delimiters, but record that they've
362 ;; potentially separated quoted words.
364 (setq last-encoded nil))
366 (error "Unbalanced parentheses"))
368 ;; Look for the end of parentheses.
370 ;; Encode text as an unstructured field.
371 (let ((rfc2047-encoding-type 'mime))
372 (rfc2047-encode-region (1+ start) (1- (point))))
373 (skip-chars-forward ")"))
374 (t ; normal token/whitespace sequence
376 ;; Skip one ASCII word, or encode continuous words
377 ;; in which all those contain non-ASCII characters.
379 (while (not (or end (eobp)))
380 (when (looking-at "[\000-\177]+")
384 (while (and (or (re-search-forward
385 "[ \t\n]\\|\\Sw" end 'move)
387 (eq ?\\ (char-syntax (char-before))))
388 ;; Skip backslash-quoted characters.
391 (setq end (match-beginning 0))
392 (if rfc2047-encode-encoded-words
395 (when (search-forward "=?" end 'move)
396 (goto-char (match-beginning 0))
399 ;; Where the value nil of `end' means there may be
400 ;; text to have to be encoded following the point.
401 ;; Otherwise, the point reached to the end of ASCII
402 ;; words separated by whitespace or a special char.
404 (when (looking-at encodable-regexp)
405 (goto-char (setq begin (match-end 0)))
406 (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
407 (setq end (match-end 0))
409 (while (re-search-forward
410 encodable-regexp end t))
413 (or (not (re-search-forward "\\Sw" end t))
415 (goto-char (match-beginning 0))
418 (when (looking-at "[^ \t\n]+")
419 (setq end (match-end 0))
420 (if (re-search-forward "\\Sw+" end t)
421 ;; There are special characters better
422 ;; to be encoded so that MTAs may parse
424 (cond ((= end (point)))
425 ((looking-at encodable-regexp)
428 (goto-char (1- (match-end 0)))
429 (unless (= (point) (match-beginning 0))
430 ;; Separate encodable text and
434 (skip-chars-forward " \t\n")
435 (if (and (looking-at "[^ \t\n]+")
436 (string-match encodable-regexp
439 (goto-char end)))))))
440 (skip-chars-backward " \t\n")
443 (if (re-search-forward encodable-regexp end 'move)
446 (unless (memq (char-before) '(nil ?\t ? ))
447 ;; Separate encodable text and delimiter.
450 (rfc2047-encode (point) end)
451 (setq last-encoded t))
452 (setq last-encoded nil)))))
454 (if (or debug-on-quit debug-on-error)
455 (signal (car err) (cdr err))
456 (error "Invalid data for rfc2047 encoding: %s"
457 (mm-replace-in-string orig-text "[ \t\n]+" " "))))))))
458 (rfc2047-fold-region b (point))
459 (goto-char (point-max))))
461 (defun rfc2047-encode-string (string)
462 "Encode words in STRING.
463 By default, the string is treated as containing addresses (see
464 `rfc2047-encoding-type')."
465 (mm-with-multibyte-buffer
467 (rfc2047-encode-region (point-min) (point-max))
470 (defvar rfc2047-encode-max-chars 76
471 "Maximum characters of each header line that contain encoded-words.
472 If it is nil, encoded-words will not be folded. Too small value may
473 cause an error. Don't change this for no particular reason.")
475 (defun rfc2047-encode-1 (column string cs encoder start crest tail
477 "Subroutine used by `rfc2047-encode'."
478 (cond ((string-equal string "")
480 ((not rfc2047-encode-max-chars)
482 (funcall encoder (if cs
483 (mm-encode-coding-string string cs)
486 ((>= column rfc2047-encode-max-chars)
488 (cond ((string-match "\n[ \t]+\\'" eword)
489 ;; Reomove a superfluous empty line.
490 (setq eword (substring eword 0 (match-beginning 0))))
491 ((string-match "(+\\'" eword)
492 ;; Break the line before the open parenthesis.
493 (setq crest (concat crest (match-string 0 eword))
494 eword (substring eword 0 (match-beginning 0))))))
495 (rfc2047-encode-1 (length crest) string cs encoder start " " tail
496 (concat eword "\n" crest)))
499 (limit (1- (length string)))
504 (setq next (concat start
507 (mm-encode-coding-string
508 (substring string 0 (1+ index))
510 (substring string 0 (1+ index))))
512 len (+ column (length next)))
513 (if (> len rfc2047-encode-max-chars)
516 (if (or (< index limit)
517 (<= (+ len (or (string-match "\n" tail)
519 rfc2047-encode-max-chars))
522 (if (string-match "\\`)+" tail)
523 ;; Break the line after the close parenthesis.
524 (setq tail (concat (substring tail 0 (match-end 0))
526 (substring tail (match-end 0)))
532 (concat eword next tail)
535 (string-match "(+\\'" eword))
536 (setq crest (concat crest (match-string 0 eword))
537 eword (substring eword 0 (match-beginning 0)))
538 (setq eword (concat eword next)))
540 eword (concat eword next)))
541 (when (string-match "\n[ \t]+\\'" eword)
542 ;; Reomove a superfluous empty line.
543 (setq eword (substring eword 0 (match-beginning 0))))
544 (rfc2047-encode-1 (length crest) (substring string index)
545 cs encoder start " " tail
546 (concat eword "\n" crest)))))))
548 (defun rfc2047-encode (b e)
549 "Encode the word(s) in the region B to E.
550 Point moves to the end of the region."
551 (let ((mime-charset (or (mm-find-mime-charset-region b e) (list 'us-ascii)))
552 cs encoding tail crest eword)
553 (cond ((> (length mime-charset) 1)
554 (error "Can't rfc2047-encode `%s'"
555 (buffer-substring-no-properties b e)))
556 ((= (length mime-charset) 1)
557 (setq mime-charset (car mime-charset)
558 cs (mm-charset-to-coding-system mime-charset))
559 (unless (and (mm-multibyte-p)
560 (mm-coding-system-p cs))
563 (narrow-to-region b e)
565 (or (cdr (assq mime-charset
566 rfc2047-charset-encoding-alist))
567 ;; For the charsets that don't have a preferred
568 ;; encoding, choose the one that's shorter.
569 (if (eq (rfc2047-qp-or-base64) 'base64)
574 (skip-chars-forward "^ \t\n")
575 ;; `tail' may contain a close parenthesis.
576 (setq tail (buffer-substring-no-properties e (point)))
578 (setq b (point-marker)
579 e (set-marker (make-marker) e))
580 (rfc2047-fold-region (point-at-bol) b)
582 (skip-chars-backward "^ \t\n")
583 (unless (= 0 (skip-chars-backward " \t"))
584 ;; `crest' may contain whitespace and an open parenthesis.
585 (setq crest (buffer-substring-no-properties (point) b)))
586 (setq eword (rfc2047-encode-1
588 (mm-replace-in-string
589 (buffer-substring-no-properties b e)
590 "\n\\([ \t]?\\)" "\\1")
592 (or (cdr (assq encoding
593 rfc2047-encode-function-alist))
595 (concat "=?" (downcase (symbol-name mime-charset))
596 "?" (upcase (symbol-name encoding)) "?")
599 (delete-region (if (eq (aref eword 0) ?\n)
601 ;; The line was folded before encoding.
606 ;; `eword' contains `crest' and `tail'.
610 (unless (or (/= 0 (length tail))
612 (looking-at "[ \t\n)]"))
617 (defun rfc2047-fold-field ()
618 "Fold the current header field."
621 (rfc2047-narrow-to-field)
622 (rfc2047-fold-region (point-min) (point-max)))))
624 (defun rfc2047-fold-region (b e)
625 "Fold long lines in region B to E."
627 (narrow-to-region b e)
628 (goto-char (point-min))
632 (bol (save-restriction
636 (when (and (or break qword-break)
637 (> (- (point) bol) 76))
638 (goto-char (or break qword-break))
641 (skip-chars-backward " \t")
642 (if (looking-at "[ \t]")
645 (setq bol (1- (point)))
646 ;; Don't break before the first non-LWSP characters.
647 (skip-chars-forward " \t")
651 ((eq (char-after) ?\n)
656 (skip-chars-forward " \t")
657 (unless (or (eobp) (eq (char-after) ?\n))
659 ((eq (char-after) ?\r)
661 ((memq (char-after) '(? ?\t))
662 (skip-chars-forward " \t")
663 (unless first ;; Don't break just after the header name.
664 (setq break (point))))
666 (if (not (looking-at "=\\?[^=]"))
667 (if (eq (char-after) ?=)
669 (skip-chars-forward "^ \t\n\r="))
670 ;; Don't break at the start of the field.
671 (unless (= (point) b)
672 (setq qword-break (point)))
673 (skip-chars-forward "^ \t\n\r")))
675 (skip-chars-forward "^ \t\n\r")))
677 (when (and (or break qword-break)
678 (> (- (point) bol) 76))
679 (goto-char (or break qword-break))
682 (if (or (> 0 (skip-chars-backward " \t"))
683 (looking-at "[ \t]"))
686 (setq bol (1- (point)))
687 ;; Don't break before the first non-LWSP characters.
688 (skip-chars-forward " \t")
690 (forward-char 1))))))
692 (defun rfc2047-unfold-field ()
693 "Fold the current line."
696 (rfc2047-narrow-to-field)
697 (rfc2047-unfold-region (point-min) (point-max)))))
699 (defun rfc2047-unfold-region (b e)
700 "Unfold lines in region B to E."
702 (narrow-to-region b e)
703 (goto-char (point-min))
704 (let ((bol (save-restriction
707 (eol (point-at-eol)))
710 (if (and (looking-at "[ \t]")
711 (< (- (point-at-eol) bol) 76))
712 (delete-region eol (progn
714 (skip-chars-forward "\r\n")
716 (setq bol (point-at-bol)))
717 (setq eol (point-at-eol))
720 (defun rfc2047-b-encode-string (string)
721 "Base64-encode the header contained in STRING."
722 (base64-encode-string string t))
724 (defun rfc2047-q-encode-string (string)
725 "Quoted-printable-encode the header in STRING."
726 (mm-with-unibyte-buffer
728 (quoted-printable-encode-region
729 (point-min) (point-max) nil
730 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
731 ;; Avoid using 8bit characters.
732 ;; This list excludes `especials' (see the RFC2047 syntax),
733 ;; meaning that some characters in non-structured fields will
734 ;; get encoded when they con't need to be. The following is
735 ;; what it used to be.
736 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
737 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
738 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
739 (subst-char-in-region (point-min) (point-max) ? ?_)
742 (defun rfc2047-encode-parameter (param value)
743 "Return and PARAM=VALUE string encoded in the RFC2047-like style.
744 This is a replacement for the `rfc2231-encode-string' function.
746 When attaching files as MIME parts, we should use the RFC2231 encoding
747 to specify the file names containing non-ASCII characters. However,
748 many mail softwares don't support it in practice and recipients won't
749 be able to extract files with correct names. Instead, the RFC2047-like
750 encoding is acceptable generally. This function provides the very
751 RFC2047-like encoding, resigning to such a regrettable trend. To use
752 it, put the following line in your ~/.gnus.el file:
754 \(defalias 'mail-header-encode-parameter 'rfc2047-encode-parameter)
756 (let* ((rfc2047-encoding-type 'mime)
757 (rfc2047-encode-max-chars nil)
758 (string (rfc2047-encode-string value)))
759 (if (string-match "[][()<>@,;:\\\"/?=]" ;; tspecials
761 (format "%s=%S" param string)
762 (concat param "=" string))))
765 ;;; Functions for decoding RFC2047 messages
769 (defconst rfc2047-encoded-word-regexp
770 "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\
771 \\?\\(B\\|Q\\)\\?\\([!->@-~ ]*\\)\\?="))
773 ;; Fixme: This should decode in place, not cons intermediate strings.
774 ;; Also check whether it needs to worry about delimiting fields like
777 ;; In fact it's reported that (invalid) encoding of mailboxes in
778 ;; addr-specs is in use, so delimiting fields might help. Probably
779 ;; not decoding a word which isn't properly delimited is good enough
780 ;; and worthwhile (is it more correct or not?), e.g. something like
781 ;; `=?iso-8859-1?q?foo?=@'.
783 (defun rfc2047-decode-region (start end)
784 "Decode MIME-encoded words in region between START and END."
786 (let ((case-fold-search t)
790 (narrow-to-region start end)
791 (goto-char (point-min))
792 ;; Remove whitespace between encoded words.
793 (while (re-search-forward
795 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
797 "\\(" rfc2047-encoded-word-regexp "\\)"))
799 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
800 ;; Decode the encoded words.
801 (setq b (goto-char (point-min)))
802 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
803 (setq e (match-beginning 0))
804 (insert (rfc2047-parse-and-decode
807 (delete-region (match-beginning 0) (match-end 0)))))
808 ;; Remove newlines between decoded words, though such things
809 ;; essentially must not be there.
811 (narrow-to-region e (point))
813 (while (re-search-forward "[\n\r]+" nil t)
815 (goto-char (point-max)))
816 (when (and (mm-multibyte-p)
818 (not (eq mail-parse-charset 'us-ascii))
819 (not (eq mail-parse-charset 'gnus-decoded)))
820 (mm-decode-coding-region b e mail-parse-charset))
822 (when (and (mm-multibyte-p)
824 (not (eq mail-parse-charset 'us-ascii))
825 (not (eq mail-parse-charset 'gnus-decoded)))
826 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
828 (defun rfc2047-decode-string (string)
829 "Decode the quoted-printable-encoded STRING and return the results."
830 (let ((m (mm-multibyte-p)))
831 (if (string-match "=\\?" string)
833 ;; Fixme: This logic is wrong, but seems to be required by
834 ;; Gnus summary buffer generation. The value of `m' depends
835 ;; on the current buffer, not global multibyteness or that
836 ;; of the string. Also the string returned should always be
837 ;; multibyte in a multibyte session, i.e. the buffer should
838 ;; be multibyte before `buffer-string' is called.
840 (mm-enable-multibyte))
843 (rfc2047-decode-region (point-min) (point-max)))
845 ;; Fixme: As above, `m' here is inappropriate.
848 (not (eq mail-parse-charset 'us-ascii))
849 (not (eq mail-parse-charset 'gnus-decoded)))
850 ;; `decode-coding-string' in Emacs offers a third optional
851 ;; arg NOCOPY to avoid consing a new string if the decoding
852 ;; is "trivial". Unfortunately it currently doesn't
853 ;; consider anything else than a `nil' coding system
855 ;; `rfc2047-decode-string' is called multiple times for each
856 ;; article during summary buffer generation, and we really
857 ;; want to avoid unnecessary consing. So we bypass
858 ;; `decode-coding-string' if the string is purely ASCII.
859 (if (and (fboundp 'detect-coding-string)
860 ;; string is purely ASCII
861 (eq (detect-coding-string string t) 'undecided))
863 (mm-decode-coding-string string mail-parse-charset))
864 (mm-string-as-multibyte string)))))
866 (defun rfc2047-parse-and-decode (word)
867 "Decode WORD and return it if it is an encoded word.
868 Return WORD if it is not not an encoded word or if the charset isn't
870 (if (not (string-match rfc2047-encoded-word-regexp word))
875 (match-string 1 word)
876 (string-to-char (match-string 2 word))
877 (match-string 3 word))
879 word))) ; un-decodable
881 (defun rfc2047-pad-base64 (string)
882 "Pad STRING to quartets."
883 ;; Be more liberal to accept buggy base64 strings. If
884 ;; base64-decode-string accepts buggy strings, this function could
885 ;; be aliased to identity.
886 (if (= 0 (mod (length string) 4))
888 (when (string-match "=+$" string)
889 (setq string (substring string 0 (match-beginning 0))))
890 (case (mod (length string) 4)
892 (1 string) ;; Error, don't pad it.
893 (2 (concat string "=="))
894 (3 (concat string "=")))))
896 (defun rfc2047-decode (charset encoding string)
897 "Decode STRING from the given MIME CHARSET in the given ENCODING.
898 Valid ENCODINGs are the characters \"B\" and \"Q\".
899 If your Emacs implementation can't decode CHARSET, return nil."
900 (if (stringp charset)
901 (setq charset (intern (downcase charset))))
902 (if (or (not charset)
903 (eq 'gnus-all mail-parse-ignored-charsets)
904 (memq 'gnus-all mail-parse-ignored-charsets)
905 (memq charset mail-parse-ignored-charsets))
906 (setq charset mail-parse-charset))
907 (let ((cs (mm-charset-to-coding-system charset)))
908 (if (and (not cs) charset
909 (listp mail-parse-ignored-charsets)
910 (memq 'gnus-unknown mail-parse-ignored-charsets))
911 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
914 (setq cs (or mail-parse-charset 'raw-text)))
915 (mm-decode-coding-string
917 ((char-equal ?B encoding)
918 (base64-decode-string
919 (rfc2047-pad-base64 string)))
920 ((char-equal ?Q encoding)
921 (quoted-printable-decode-string
922 (mm-subst-char-in-string ?_ ? string t)))
923 (t (error "Invalid encoding: %c" encoding)))
928 ;;; rfc2047.el ends here