1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
3 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004,
4 ;; 2005, 2006 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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, 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))
39 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
42 (autoload 'mm-body-7-or-8 "mm-bodies")
44 (defvar rfc2047-header-encoding-alist
45 '(("Newsgroups" . nil)
48 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|\\(In-\\)?Reply-To\\|Sender\
49 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
51 "*Header/encoding method alist.
52 The list is traversed sequentially. The keys can either be
57 1) nil, in which case no encoding is done;
58 2) `mime', in which case the header will be encoded according to RFC2047;
59 3) `address-mime', like `mime', but takes account of the rules for address
60 fields (where quoted strings and comments must be treated separately);
61 4) a charset, in which case it will be encoded as that charset;
62 5) `default', in which case the field will be encoded as the rest
65 (defvar rfc2047-charset-encoding-alist
89 "Alist of MIME charsets to RFC2047 encodings.
90 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
91 quoted-printable and base64 respectively.")
93 (defvar rfc2047-encode-function-alist
94 '((Q . rfc2047-q-encode-string)
95 (B . rfc2047-b-encode-string)
97 "Alist of RFC2047 encodings to encoding functions.")
99 (defvar rfc2047-encode-encoded-words t
100 "Whether encoded words should be encoded again.")
103 ;;; Functions for encoding RFC2047 messages
106 (defun rfc2047-qp-or-base64 ()
107 "Return the type with which to encode the buffer.
108 This is either `base64' or `quoted-printable'."
110 (let ((limit (min (point-max) (+ 2000 (point-min))))
112 (goto-char (point-min))
113 (skip-chars-forward "\x20-\x7f\r\n\t" limit)
114 (while (< (point) limit)
117 (skip-chars-forward "\x20-\x7f\r\n\t" limit))
118 (if (or (< (* 6 n8bit) (- limit (point-min)))
119 ;; Don't base64, say, a short line with a single
120 ;; non-ASCII char when splitting parts by charset.
125 (defun rfc2047-narrow-to-field ()
126 "Narrow the buffer to the header on the current line."
132 (if (re-search-forward "^[^ \n\t]" nil t)
135 (goto-char (point-min)))
137 (defun rfc2047-field-value ()
138 "Return the value of the field at point."
141 (rfc2047-narrow-to-field)
142 (re-search-forward ":[ \t\n]*" nil t)
143 (buffer-substring-no-properties (point) (point-max)))))
145 (defun rfc2047-quote-special-characters-in-quoted-strings (&optional
147 "Quote special characters with `\\'s in quoted strings.
148 Quoting will not be done in a quoted string if it contains characters
149 matching ENCODABLE-REGEXP."
150 (goto-char (point-min))
151 (let ((tspecials (concat "[" ietf-drums-tspecials "]"))
153 (with-syntax-table (standard-syntax-table)
154 (while (search-forward "\"" nil t)
155 (setq beg (match-beginning 0))
156 (unless (eq (char-before beg) ?\\)
162 (setq end (1- (point)))
164 (if (and encodable-regexp
165 (re-search-forward encodable-regexp end t))
168 (narrow-to-region beg end)
169 (while (re-search-forward tspecials nil 'move)
170 (if (eq (char-before) ?\\)
171 (if (looking-at tspecials) ;; Already quoted.
174 (goto-char (match-beginning 0))
179 (goto-char beg))))))))
181 (defvar rfc2047-encoding-type 'address-mime
182 "The type of encoding done by `rfc2047-encode-region'.
183 This should be dynamically bound around calls to
184 `rfc2047-encode-region' to either `mime' or `address-mime'. See
185 `rfc2047-header-encoding-alist', for definitions.")
187 (defun rfc2047-encode-message-header ()
188 "Encode the message header according to `rfc2047-header-encoding-alist'.
189 Should be called narrowed to the head of the message."
192 (goto-char (point-min))
193 (let (alist elem method)
196 (rfc2047-narrow-to-field)
198 alist rfc2047-header-encoding-alist)
199 (while (setq elem (pop alist))
200 (when (or (and (stringp (car elem))
201 (looking-at (car elem)))
205 (if (not (rfc2047-encodable-p))
207 (when (eq method 'address-mime)
208 (rfc2047-quote-special-characters-in-quoted-strings))
209 (if (and (eq (mm-body-7-or-8) '8bit)
212 (car message-posting-charset)))
213 ;; 8 bit must be decoded.
214 (mm-encode-coding-region
215 (point-min) (point-max)
216 (mm-charset-to-coding-system
217 (car message-posting-charset))))
218 ;; No encoding necessary, but folding is nice
222 (goto-char (point-min))
223 (skip-chars-forward "^:")
224 (when (looking-at ": ")
228 ;; We found something that may perhaps be encoded.
229 (re-search-forward "^[^:]+: *" nil t)
231 ((eq method 'address-mime)
232 (rfc2047-encode-region (point) (point-max)))
234 (let ((rfc2047-encoding-type 'mime))
235 (rfc2047-encode-region (point) (point-max))))
236 ((eq method 'default)
237 (if (and (featurep 'mule)
238 (if (boundp 'default-enable-multibyte-characters)
239 default-enable-multibyte-characters)
241 (mm-encode-coding-region (point) (point-max)
242 mail-parse-charset)))
243 ;; We get this when CC'ing messsages to newsgroups with
244 ;; 8-bit names. The group name mail copy just got
245 ;; unconditionally encoded. Previously, it would ask
246 ;; whether to encode, which was quite confusing for the
247 ;; user. If the new behaviour is wrong, tell me. I have
248 ;; left the old code commented out below.
249 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
250 ;; Modified by Dave Love, with the commented-out code changed
251 ;; in accordance with changes elsewhere.
253 (rfc2047-encode-region (point) (point-max)))
255 ;;; (if (or (message-options-get
256 ;;; 'rfc2047-encode-message-header-encode-any)
257 ;;; (message-options-set
258 ;;; 'rfc2047-encode-message-header-encode-any
260 ;;; "Some texts are not encoded. Encode anyway?")))
261 ;;; (rfc2047-encode-region (point-min) (point-max))
262 ;;; (error "Cannot send unencoded text")))
263 ((mm-coding-system-p method)
264 (if (and (featurep 'mule)
265 (if (boundp 'default-enable-multibyte-characters)
266 default-enable-multibyte-characters))
267 (mm-encode-coding-region (point) (point-max) method)))
270 (goto-char (point-max)))))))
272 ;; Fixme: This, and the require below may not be the Right Thing, but
273 ;; should be safe just before release. -- fx 2001-02-08
274 (eval-when-compile (defvar message-posting-charset))
276 (defun rfc2047-encodable-p ()
277 "Return non-nil if any characters in current buffer need encoding in headers.
278 The buffer may be narrowed."
279 (require 'message) ; for message-posting-charset
281 (mm-find-mime-charset-region (point-min) (point-max))))
282 (goto-char (point-min))
283 (or (and rfc2047-encode-encoded-words
285 (search-forward "=?" nil t)
286 (goto-char (point-min))))
288 (not (equal charsets (list (car message-posting-charset))))))))
290 ;; Use this syntax table when parsing into regions that may need
291 ;; encoding. Double quotes are string delimiters, backslash is
292 ;; character quoting, and all other RFC 2822 special characters are
293 ;; treated as punctuation so we can use forward-sexp/forward-word to
294 ;; skip to the end of regions appropriately. Nb. ietf-drums does
295 ;; things differently.
296 (defconst rfc2047-syntax-table
297 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
298 (let ((table (make-syntax-table)))
299 ;; The following is done to work for setting all elements of the table
300 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
301 ;; Play safe and don't assume the form of the word syntax entry --
303 (if (fboundp 'set-char-table-range) ; Emacs
304 (funcall (intern "set-char-table-range")
305 table t (aref (standard-syntax-table) ?a))
306 (if (fboundp 'put-char-table)
307 (if (fboundp 'get-char-table) ; warning avoidance
308 (put-char-table t (get-char-table ?a (standard-syntax-table))
310 (modify-syntax-entry ?\\ "\\" table)
311 (modify-syntax-entry ?\" "\"" table)
312 (modify-syntax-entry ?\( "(" table)
313 (modify-syntax-entry ?\) ")" table)
314 (modify-syntax-entry ?\< "." table)
315 (modify-syntax-entry ?\> "." table)
316 (modify-syntax-entry ?\[ "." table)
317 (modify-syntax-entry ?\] "." table)
318 (modify-syntax-entry ?: "." table)
319 (modify-syntax-entry ?\; "." table)
320 (modify-syntax-entry ?, "." table)
321 (modify-syntax-entry ?@ "." table)
324 (defun rfc2047-encode-region (b e)
325 "Encode words in region B to E that need encoding.
326 By default, the region is treated as containing RFC2822 addresses.
327 Dynamically bind `rfc2047-encoding-type' to change that."
329 (narrow-to-region b e)
330 (let ((encodable-regexp (if rfc2047-encode-encoded-words
331 "[^\000-\177]+\\|=\\?"
333 start ; start of current token
335 ;; Whether there's an encoded word before the current token,
336 ;; either immediately or separated by space.
338 (orig-text (buffer-substring-no-properties b e)))
339 (if (eq 'mime rfc2047-encoding-type)
340 ;; Simple case. Continuous words in which all those contain
341 ;; non-ASCII characters are encoded collectively. Encoding
342 ;; ASCII words, including `Re:' used in Subject headers, is
343 ;; avoided for interoperability with non-MIME clients and
344 ;; for making it easy to find keywords.
346 (goto-char (point-min))
347 (while (progn (skip-chars-forward " \t\n")
350 (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
352 (setq end (match-end 0))
353 (re-search-forward encodable-regexp end t)))
355 (if (> (point) start)
356 (rfc2047-encode start (point))
358 ;; `address-mime' case -- take care of quoted words, comments.
359 (rfc2047-quote-special-characters-in-quoted-strings encodable-regexp)
360 (with-syntax-table rfc2047-syntax-table
361 (goto-char (point-min))
362 (condition-case err ; in case of unbalanced quotes
363 ;; Look for rfc2822-style: sequences of atoms, quoted
364 ;; strings, specials, whitespace. (Specials mustn't be
368 (skip-chars-forward " \t\n")
371 ((not (char-after))) ; eob
373 ((eq ?\" (setq csyntax (char-syntax (char-after))))
377 ;; Does it need encoding?
379 (if (re-search-forward encodable-regexp end 'move)
380 ;; It needs encoding. Strip the quotes first,
381 ;; since encoded words can't occur in quotes.
384 (delete-backward-char 1)
388 ;; There was a preceding quoted word. We need
389 ;; to include any separating whitespace in this
390 ;; word to avoid it getting lost.
391 (skip-chars-backward " \t")
392 ;; A space is needed between the encoded words.
396 ;; Adjust the end position for the deleted quotes.
397 (rfc2047-encode start (- end 2))
398 (setq last-encoded t)) ; record that it was encoded
399 (setq last-encoded nil)))
401 ;; Skip other delimiters, but record that they've
402 ;; potentially separated quoted words.
404 (setq last-encoded nil))
406 (error "Unbalanced parentheses"))
408 ;; Look for the end of parentheses.
410 ;; Encode text as an unstructured field.
411 (let ((rfc2047-encoding-type 'mime))
412 (rfc2047-encode-region (1+ start) (1- (point))))
413 (skip-chars-forward ")"))
414 (t ; normal token/whitespace sequence
416 ;; Skip one ASCII word, or encode continuous words
417 ;; in which all those contain non-ASCII characters.
419 (while (not (or end (eobp)))
420 (when (looking-at "[\000-\177]+")
424 (while (and (or (re-search-forward
425 "[ \t\n]\\|\\Sw" end 'move)
427 (eq ?\\ (char-syntax (char-before))))
428 ;; Skip backslash-quoted characters.
431 (setq end (match-beginning 0))
432 (if rfc2047-encode-encoded-words
435 (when (search-forward "=?" end 'move)
436 (goto-char (match-beginning 0))
439 ;; Where the value nil of `end' means there may be
440 ;; text to have to be encoded following the point.
441 ;; Otherwise, the point reached to the end of ASCII
442 ;; words separated by whitespace or a special char.
444 (when (looking-at encodable-regexp)
445 (goto-char (setq begin (match-end 0)))
446 (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
447 (setq end (match-end 0))
449 (while (re-search-forward
450 encodable-regexp end t))
453 (or (not (re-search-forward "\\Sw" end t))
455 (goto-char (match-beginning 0))
458 (when (looking-at "[^ \t\n]+")
459 (setq end (match-end 0))
460 (if (re-search-forward "\\Sw+" end t)
461 ;; There are special characters better
462 ;; to be encoded so that MTAs may parse
464 (cond ((= end (point)))
465 ((looking-at (concat "\\sw*\\("
470 (goto-char (1- (match-end 0)))
471 (unless (= (point) (match-beginning 0))
472 ;; Separate encodable text and
476 (skip-chars-forward " \t\n")
477 (if (and (looking-at "[^ \t\n]+")
478 (string-match encodable-regexp
481 (goto-char end)))))))
482 (skip-chars-backward " \t\n")
485 (if (re-search-forward encodable-regexp end 'move)
487 (unless (memq (char-before start) '(nil ?\t ? ))
490 (skip-chars-backward "^ \t\n")
491 (and (looking-at "\\Sw+")
492 (= (match-end 0) start)))
493 ;; Also encode bogus delimiters.
495 ;; Separate encodable text and delimiter.
498 (setq start (1+ start)
500 (rfc2047-encode start end)
501 (setq last-encoded t))
502 (setq last-encoded nil)))))
504 (if (or debug-on-quit debug-on-error)
505 (signal (car err) (cdr err))
506 (error "Invalid data for rfc2047 encoding: %s"
507 (mm-replace-in-string orig-text "[ \t\n]+" " "))))))))
508 (rfc2047-fold-region b (point))
509 (goto-char (point-max))))
511 (defun rfc2047-encode-string (string)
512 "Encode words in STRING.
513 By default, the string is treated as containing addresses (see
514 `rfc2047-encoding-type')."
515 (mm-with-multibyte-buffer
517 (rfc2047-encode-region (point-min) (point-max))
520 (defvar rfc2047-encode-max-chars 76
521 "Maximum characters of each header line that contain encoded-words.
522 If it is nil, encoded-words will not be folded. Too small value may
523 cause an error. Don't change this for no particular reason.")
525 (defun rfc2047-encode-1 (column string cs encoder start crest tail
527 "Subroutine used by `rfc2047-encode'."
528 (cond ((string-equal string "")
530 ((not rfc2047-encode-max-chars)
532 (funcall encoder (if cs
533 (mm-encode-coding-string string cs)
536 ((>= column rfc2047-encode-max-chars)
538 (cond ((string-match "\n[ \t]+\\'" eword)
539 ;; Reomove a superfluous empty line.
540 (setq eword (substring eword 0 (match-beginning 0))))
541 ((string-match "(+\\'" eword)
542 ;; Break the line before the open parenthesis.
543 (setq crest (concat crest (match-string 0 eword))
544 eword (substring eword 0 (match-beginning 0))))))
545 (rfc2047-encode-1 (length crest) string cs encoder start " " tail
546 (concat eword "\n" crest)))
549 (limit (1- (length string)))
554 (setq next (concat start
557 (mm-encode-coding-string
558 (substring string 0 (1+ index))
560 (substring string 0 (1+ index))))
562 len (+ column (length next)))
563 (if (> len rfc2047-encode-max-chars)
566 (if (or (< index limit)
567 (<= (+ len (or (string-match "\n" tail)
569 rfc2047-encode-max-chars))
572 (if (string-match "\\`)+" tail)
573 ;; Break the line after the close parenthesis.
574 (setq tail (concat (substring tail 0 (match-end 0))
576 (substring tail (match-end 0)))
582 (concat eword next tail)
585 (string-match "(+\\'" eword))
586 (setq crest (concat crest (match-string 0 eword))
587 eword (substring eword 0 (match-beginning 0)))
588 (setq eword (concat eword next)))
590 eword (concat eword next)))
591 (when (string-match "\n[ \t]+\\'" eword)
592 ;; Reomove a superfluous empty line.
593 (setq eword (substring eword 0 (match-beginning 0))))
594 (rfc2047-encode-1 (length crest) (substring string index)
595 cs encoder start " " tail
596 (concat eword "\n" crest)))))))
598 (defun rfc2047-encode (b e)
599 "Encode the word(s) in the region B to E.
600 Point moves to the end of the region."
601 (let ((mime-charset (or (mm-find-mime-charset-region b e) (list 'us-ascii)))
602 cs encoding tail crest eword)
603 (cond ((> (length mime-charset) 1)
604 (error "Can't rfc2047-encode `%s'"
605 (buffer-substring-no-properties b e)))
606 ((= (length mime-charset) 1)
607 (setq mime-charset (car mime-charset)
608 cs (mm-charset-to-coding-system mime-charset))
609 (unless (and (mm-multibyte-p)
610 (mm-coding-system-p cs))
613 (narrow-to-region b e)
615 (or (cdr (assq mime-charset
616 rfc2047-charset-encoding-alist))
617 ;; For the charsets that don't have a preferred
618 ;; encoding, choose the one that's shorter.
619 (if (eq (rfc2047-qp-or-base64) 'base64)
624 (skip-chars-forward "^ \t\n")
625 ;; `tail' may contain a close parenthesis.
626 (setq tail (buffer-substring-no-properties e (point)))
628 (setq b (point-marker)
629 e (set-marker (make-marker) e))
630 (rfc2047-fold-region (point-at-bol) b)
632 (skip-chars-backward "^ \t\n")
633 (unless (= 0 (skip-chars-backward " \t"))
634 ;; `crest' may contain whitespace and an open parenthesis.
635 (setq crest (buffer-substring-no-properties (point) b)))
636 (setq eword (rfc2047-encode-1
638 (mm-replace-in-string
639 (buffer-substring-no-properties b e)
640 "\n\\([ \t]?\\)" "\\1")
642 (or (cdr (assq encoding
643 rfc2047-encode-function-alist))
645 (concat "=?" (downcase (symbol-name mime-charset))
646 "?" (upcase (symbol-name encoding)) "?")
649 (delete-region (if (eq (aref eword 0) ?\n)
651 ;; The line was folded before encoding.
656 ;; `eword' contains `crest' and `tail'.
660 (unless (or (/= 0 (length tail))
662 (looking-at "[ \t\n)]"))
667 (defun rfc2047-fold-field ()
668 "Fold the current header field."
671 (rfc2047-narrow-to-field)
672 (rfc2047-fold-region (point-min) (point-max)))))
674 (defun rfc2047-fold-region (b e)
675 "Fold long lines in region B to E."
677 (narrow-to-region b e)
678 (goto-char (point-min))
682 (bol (save-restriction
686 (when (and (or break qword-break)
687 (> (- (point) bol) 76))
688 (goto-char (or break qword-break))
691 (skip-chars-backward " \t")
692 (if (looking-at "[ \t]")
695 (setq bol (1- (point)))
696 ;; Don't break before the first non-LWSP characters.
697 (skip-chars-forward " \t")
701 ((eq (char-after) ?\n)
706 (skip-chars-forward " \t")
707 (unless (or (eobp) (eq (char-after) ?\n))
709 ((eq (char-after) ?\r)
711 ((memq (char-after) '(? ?\t))
712 (skip-chars-forward " \t")
713 (unless first ;; Don't break just after the header name.
714 (setq break (point))))
716 (if (not (looking-at "=\\?[^=]"))
717 (if (eq (char-after) ?=)
719 (skip-chars-forward "^ \t\n\r="))
720 ;; Don't break at the start of the field.
721 (unless (= (point) b)
722 (setq qword-break (point)))
723 (skip-chars-forward "^ \t\n\r")))
725 (skip-chars-forward "^ \t\n\r")))
727 (when (and (or break qword-break)
728 (> (- (point) bol) 76))
729 (goto-char (or break qword-break))
732 (if (or (> 0 (skip-chars-backward " \t"))
733 (looking-at "[ \t]"))
736 (setq bol (1- (point)))
737 ;; Don't break before the first non-LWSP characters.
738 (skip-chars-forward " \t")
740 (forward-char 1))))))
742 (defun rfc2047-unfold-field ()
743 "Fold the current line."
746 (rfc2047-narrow-to-field)
747 (rfc2047-unfold-region (point-min) (point-max)))))
749 (defun rfc2047-unfold-region (b e)
750 "Unfold lines in region B to E."
752 (narrow-to-region b e)
753 (goto-char (point-min))
754 (let ((bol (save-restriction
757 (eol (point-at-eol)))
760 (if (and (looking-at "[ \t]")
761 (< (- (point-at-eol) bol) 76))
762 (delete-region eol (progn
764 (skip-chars-forward "\r\n")
766 (setq bol (point-at-bol)))
767 (setq eol (point-at-eol))
770 (defun rfc2047-b-encode-string (string)
771 "Base64-encode the header contained in STRING."
772 (base64-encode-string string t))
774 (defun rfc2047-q-encode-string (string)
775 "Quoted-printable-encode the header in STRING."
776 (mm-with-unibyte-buffer
778 (quoted-printable-encode-region
779 (point-min) (point-max) nil
780 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
781 ;; Avoid using 8bit characters.
782 ;; This list excludes `especials' (see the RFC2047 syntax),
783 ;; meaning that some characters in non-structured fields will
784 ;; get encoded when they con't need to be. The following is
785 ;; what it used to be.
786 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
787 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
788 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
789 (subst-char-in-region (point-min) (point-max) ? ?_)
792 (defun rfc2047-encode-parameter (param value)
793 "Return and PARAM=VALUE string encoded in the RFC2047-like style.
794 This is a replacement for the `rfc2231-encode-string' function.
796 When attaching files as MIME parts, we should use the RFC2231 encoding
797 to specify the file names containing non-ASCII characters. However,
798 many mail softwares don't support it in practice and recipients won't
799 be able to extract files with correct names. Instead, the RFC2047-like
800 encoding is acceptable generally. This function provides the very
801 RFC2047-like encoding, resigning to such a regrettable trend. To use
802 it, put the following line in your ~/.gnus.el file:
804 \(defalias 'mail-header-encode-parameter 'rfc2047-encode-parameter)
806 (let* ((rfc2047-encoding-type 'mime)
807 (rfc2047-encode-max-chars nil)
808 (string (rfc2047-encode-string value)))
809 (if (string-match (concat "[" ietf-drums-tspecials "]") string)
810 (format "%s=%S" param string)
811 (concat param "=" string))))
814 ;;; Functions for decoding RFC2047 messages
818 (defconst rfc2047-encoded-word-regexp
819 "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\
820 \\?\\(B\\|Q\\)\\?\\([!->@-~ ]*\\)\\?="))
822 (defvar rfc2047-quote-decoded-words-containing-tspecials nil
823 "If non-nil, quote decoded words containing special characters.")
825 (defvar rfc2047-allow-incomplete-encoded-text t
826 "*Non-nil means allow incomplete encoded-text in successive encoded-words.
827 Dividing of encoded-text in the place other than character boundaries
828 violates RFC2047 section 5, while we have a capability to decode it.
829 If it is non-nil, the decoder will decode B- or Q-encoding in each
830 encoded-word, concatenate them, and decode it by charset. Otherwise,
831 the decoder will fully decode each encoded-word before concatenating
834 (defun rfc2047-strip-backslashes-in-quoted-strings ()
835 "Strip backslashes in quoted strings. `\\\"' remains."
836 (goto-char (point-min))
838 (with-syntax-table (standard-syntax-table)
839 (while (search-forward "\"" nil t)
840 (unless (eq (char-before) ?\\)
841 (setq beg (match-end 0))
842 (goto-char (match-beginning 0))
847 (narrow-to-region beg (1- (point)))
849 (while (search-forward "\\" nil 'move)
850 (unless (memq (char-after) '(?\"))
851 (delete-backward-char 1))
855 (goto-char beg))))))))
857 (defun rfc2047-charset-to-coding-system (charset)
858 "Return coding-system corresponding to MIME CHARSET.
859 If your Emacs implementation can't decode CHARSET, return nil."
860 (when (stringp charset)
861 (setq charset (intern (downcase charset))))
862 (when (or (not charset)
863 (eq 'gnus-all mail-parse-ignored-charsets)
864 (memq 'gnus-all mail-parse-ignored-charsets)
865 (memq charset mail-parse-ignored-charsets))
866 (setq charset mail-parse-charset))
867 (let ((cs (mm-charset-to-coding-system charset)))
868 (cond ((eq cs 'ascii)
869 (setq cs (or (mm-charset-to-coding-system mail-parse-charset)
871 ((mm-coding-system-p cs))
873 (listp mail-parse-ignored-charsets)
874 (memq 'gnus-unknown mail-parse-ignored-charsets))
875 (setq cs (mm-charset-to-coding-system mail-parse-charset))))
880 (defun rfc2047-decode-encoded-words (words)
881 "Decode successive encoded-words in WORDS and return a decoded string.
882 Each element of WORDS looks like (CHARSET ENCODING ENCODED-TEXT
884 (let (word charset cs encoding text rest)
886 (setq word (pop words))
887 (if (and (setq cs (rfc2047-charset-to-coding-system
888 (setq charset (car word))))
890 (cond ((char-equal ?B (nth 1 word))
891 (setq text (base64-decode-string
892 (rfc2047-pad-base64 (nth 2 word)))))
893 ((char-equal ?Q (nth 1 word))
894 (setq text (quoted-printable-decode-string
895 (mm-subst-char-in-string
896 ?_ ? (nth 2 word) t)))))
898 (message "%s" (error-message-string code))
900 (if (and rfc2047-allow-incomplete-encoded-text
902 ;; Concatenate text of which the charset is the same.
903 (setcdr (car rest) (concat (cdar rest) text))
904 (push (cons cs text) rest))
905 ;; Don't decode encoded-word.
906 (push (cons nil (nth 3 word)) rest)))
909 (or (and (setq cs (caar rest))
911 (mm-decode-coding-string (cdar rest) cs)
913 (message "%s" (error-message-string code))
915 (concat (when (cdr rest) " ")
918 (not (eq (string-to-char words) ? )))
924 ;; Fixme: This should decode in place, not cons intermediate strings.
925 ;; Also check whether it needs to worry about delimiting fields like
928 ;; In fact it's reported that (invalid) encoding of mailboxes in
929 ;; addr-specs is in use, so delimiting fields might help. Probably
930 ;; not decoding a word which isn't properly delimited is good enough
931 ;; and worthwhile (is it more correct or not?), e.g. something like
932 ;; `=?iso-8859-1?q?foo?=@'.
934 (defun rfc2047-decode-region (start end &optional address-mime)
935 "Decode MIME-encoded words in region between START and END.
936 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
937 other than `\"' and `\\' in quoted strings."
939 (let ((case-fold-search t)
940 (eword-regexp (eval-when-compile
941 ;; Ignore whitespace between encoded-words.
942 (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp
947 (narrow-to-region start end)
949 (rfc2047-strip-backslashes-in-quoted-strings))
950 (goto-char (setq b start))
951 ;; Look for the encoded-words.
952 (while (setq match (re-search-forward eword-regexp nil t))
953 (setq e (match-beginning 1)
957 (push (list (match-string 2) ;; charset
958 (char-after (match-beginning 3)) ;; encoding
959 (match-string 4) ;; encoded-text
960 (match-string 1)) ;; encoded-word
962 ;; Look for the subsequent encoded-words.
963 (when (setq match (looking-at eword-regexp))
964 (goto-char (setq end (match-end 0)))))
965 ;; Replace the encoded-words with the decoded one.
966 (delete-region e end)
967 (insert (rfc2047-decode-encoded-words (nreverse words)))
969 (narrow-to-region e (point))
971 ;; Remove newlines between decoded words, though such
972 ;; things essentially must not be there.
973 (while (re-search-forward "[\n\r]+" nil t)
975 ;; Quote decoded words if there are special characters
976 ;; which might violate RFC2822.
977 (when (and rfc2047-quote-decoded-words-containing-tspecials
978 (let ((regexp (car (rassq
980 rfc2047-header-encoding-alist))))
985 (while (and (memq (char-after) '(? ?\t))
986 (zerop (forward-line -1))))
987 (looking-at regexp)))))
990 (skip-chars-forward " \t")
992 (setq quoted (eq (char-after) ?\"))
993 (goto-char (point-max))
994 (skip-chars-backward " \t")
995 (if (setq quoted (and quoted
996 (> (point) (1+ start))
997 (eq (char-before) ?\")))
1000 (setq start (1+ start)
1001 end (point-marker)))
1002 (setq end (point-marker)))
1004 (while (search-forward "\"" end t)
1007 (zerop (% (skip-chars-backward "\\\\") 2))
1008 (goto-char (match-beginning 0)))
1011 (when (and (not quoted)
1015 (concat "[" ietf-drums-tspecials "]")
1021 (set-marker end nil)))
1022 (goto-char (point-max)))
1023 (when (and (mm-multibyte-p)
1025 (not (eq mail-parse-charset 'us-ascii))
1026 (not (eq mail-parse-charset 'gnus-decoded)))
1027 (mm-decode-coding-region b e mail-parse-charset))
1029 (when (and (mm-multibyte-p)
1031 (not (eq mail-parse-charset 'us-ascii))
1032 (not (eq mail-parse-charset 'gnus-decoded)))
1033 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
1035 (defun rfc2047-decode-address-region (start end)
1036 "Decode MIME-encoded words in region between START and END.
1037 Backslashes which precede characters other than `\"' and `\\' in quoted
1038 strings are stripped."
1039 (rfc2047-decode-region start end t))
1041 (defun rfc2047-decode-string (string &optional address-mime)
1042 "Decode MIME-encoded STRING and return the result.
1043 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
1044 other than `\"' and `\\' in quoted strings."
1045 (let ((m (mm-multibyte-p)))
1046 (if (string-match "=\\?" string)
1048 ;; Fixme: This logic is wrong, but seems to be required by
1049 ;; Gnus summary buffer generation. The value of `m' depends
1050 ;; on the current buffer, not global multibyteness or that
1051 ;; of the string. Also the string returned should always be
1052 ;; multibyte in a multibyte session, i.e. the buffer should
1053 ;; be multibyte before `buffer-string' is called.
1055 (mm-enable-multibyte))
1058 (rfc2047-decode-region (point-min) (point-max) address-mime))
1063 (when (mm-multibyte-string-p string)
1064 (mm-enable-multibyte))
1066 (rfc2047-strip-backslashes-in-quoted-strings)
1068 ;; Fixme: As above, `m' here is inappropriate.
1071 (not (eq mail-parse-charset 'us-ascii))
1072 (not (eq mail-parse-charset 'gnus-decoded)))
1073 ;; `decode-coding-string' in Emacs offers a third optional
1074 ;; arg NOCOPY to avoid consing a new string if the decoding
1075 ;; is "trivial". Unfortunately it currently doesn't
1076 ;; consider anything else than a `nil' coding system
1078 ;; `rfc2047-decode-string' is called multiple times for each
1079 ;; article during summary buffer generation, and we really
1080 ;; want to avoid unnecessary consing. So we bypass
1081 ;; `decode-coding-string' if the string is purely ASCII.
1082 (if (and (fboundp 'detect-coding-string)
1083 ;; string is purely ASCII
1084 (eq (detect-coding-string string t) 'undecided))
1086 (mm-decode-coding-string string mail-parse-charset))
1087 (mm-string-as-multibyte string)))))
1089 (defun rfc2047-decode-address-string (string)
1090 "Decode MIME-encoded STRING and return the result.
1091 Backslashes which precede characters other than `\"' and `\\' in quoted
1092 strings are stripped."
1093 (rfc2047-decode-string string t))
1095 (defun rfc2047-pad-base64 (string)
1096 "Pad STRING to quartets."
1097 ;; Be more liberal to accept buggy base64 strings. If
1098 ;; base64-decode-string accepts buggy strings, this function could
1099 ;; be aliased to identity.
1100 (if (= 0 (mod (length string) 4))
1102 (when (string-match "=+$" string)
1103 (setq string (substring string 0 (match-beginning 0))))
1104 (case (mod (length string) 4)
1106 (1 string) ;; Error, don't pad it.
1107 (2 (concat string "=="))
1108 (3 (concat string "=")))))
1112 ;;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
1113 ;;; rfc2047.el ends here