1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;; 2007, 2008, 2009, 2010 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 3 of the License, or
13 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
25 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three: Message Header Extensions for Non-ASCII Text".
32 (defvar message-posting-charset
)
36 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
38 (require 'rfc2045
) ;; rfc2045-encode-string
39 (autoload 'mm-body-7-or-8
"mm-bodies")
41 (defvar rfc2047-header-encoding-alist
42 '(("Newsgroups" . nil
)
45 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|\\(In-\\)?Reply-To\\|Sender\
46 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime
)
48 "*Header/encoding method alist.
49 The list is traversed sequentially. The keys can either be
54 1) nil, in which case no encoding is done;
55 2) `mime', in which case the header will be encoded according to RFC2047;
56 3) `address-mime', like `mime', but takes account of the rules for address
57 fields (where quoted strings and comments must be treated separately);
58 4) a charset, in which case it will be encoded as that charset;
59 5) `default', in which case the field will be encoded as the rest
62 (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.")
101 (defvar rfc2047-allow-irregular-q-encoded-words t
102 "*Whether to decode irregular Q-encoded words.")
104 (eval-and-compile ;; Necessary to hard code them in `rfc2047-decode-region'.
105 (defconst rfc2047-encoded-word-regexp
106 "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
107 \\(B\\?[+/0-9A-Za-z]*=*\
110 "Regexp that matches encoded word."
111 ;; The patterns for the B encoding and the Q encoding, i.e. the ones
112 ;; beginning with "B" and "Q" respectively, are restricted into only
113 ;; the characters that those encodings may generally use.
115 (defconst rfc2047-encoded-word-regexp-loose
116 "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
117 \\(B\\?[+/0-9A-Za-z]*=*\
118 \\|Q\\?\\(?:\\?+[ -<>@-~]\\)?\\(?:[ ->@-~]+\\?+[ -<>@-~]\\)*[ ->@-~]*\\?*\
120 "Regexp that matches encoded word allowing loose Q encoding."
121 ;; The pattern for the Q encoding, i.e. the one beginning with "Q",
123 ;; "Q\\?\\(\\?+[^\n=?]\\)?\\([^\n?]+\\?+[^\n=?]\\)*[^\n?]*\\?*"
124 ;; <--------1-------><----------2,3----------><--4--><-5->
126 ;; 1. After "Q?", allow "?"s that follow a character other than "=".
127 ;; 2. Allow "=" after "Q?"; it isn't regarded as the terminator.
128 ;; 3. In the middle of an encoded word, allow "?"s that follow a
129 ;; character other than "=".
130 ;; 4. Allow any characters other than "?" in the middle of an
132 ;; 5. At the end, allow "?"s.
136 ;;; Functions for encoding RFC2047 messages
139 (defun rfc2047-qp-or-base64 ()
140 "Return the type with which to encode the buffer.
141 This is either `base64' or `quoted-printable'."
143 (let ((limit (min (point-max) (+ 2000 (point-min))))
145 (goto-char (point-min))
146 (skip-chars-forward "\x20-\x7f\r\n\t" limit
)
147 (while (< (point) limit
)
150 (skip-chars-forward "\x20-\x7f\r\n\t" limit
))
151 (if (or (< (* 6 n8bit
) (- limit
(point-min)))
152 ;; Don't base64, say, a short line with a single
153 ;; non-ASCII char when splitting parts by charset.
158 (defun rfc2047-narrow-to-field ()
159 "Narrow the buffer to the header on the current line."
165 (if (re-search-forward "^[^ \n\t]" nil t
)
168 (goto-char (point-min)))
170 (defun rfc2047-field-value ()
171 "Return the value of the field at point."
174 (rfc2047-narrow-to-field)
175 (re-search-forward ":[ \t\n]*" nil t
)
176 (buffer-substring-no-properties (point) (point-max)))))
178 (defun rfc2047-quote-special-characters-in-quoted-strings (&optional
180 "Quote special characters with `\\'s in quoted strings.
181 Quoting will not be done in a quoted string if it contains characters
182 matching ENCODABLE-REGEXP or it is within parentheses."
183 (goto-char (point-min))
184 (let ((tspecials (concat "[" ietf-drums-tspecials
"]"))
187 (with-syntax-table (standard-syntax-table)
191 (eq (char-before) ?\
)))
193 (goto-char (point-max)))
195 (narrow-to-region start
(point))
197 (while (search-forward "\"" nil t
)
198 (setq beg
(match-beginning 0))
199 (unless (eq (char-before beg
) ?
\\)
205 (setq end
(1- (point)))
207 (if (and encodable-regexp
208 (re-search-forward encodable-regexp end t
))
211 (narrow-to-region beg end
)
212 (while (re-search-forward tspecials nil
'move
)
213 (if (eq (char-before) ?
\\)
214 (if (looking-at tspecials
) ;; Already quoted.
217 (goto-char (match-beginning 0))
223 (goto-char (point-max)))
225 (setq start
(point))))))
227 (defvar rfc2047-encoding-type
'address-mime
228 "The type of encoding done by `rfc2047-encode-region'.
229 This should be dynamically bound around calls to
230 `rfc2047-encode-region' to either `mime' or `address-mime'. See
231 `rfc2047-header-encoding-alist', for definitions.")
233 (defun rfc2047-encode-message-header ()
234 "Encode the message header according to `rfc2047-header-encoding-alist'.
235 Should be called narrowed to the head of the message."
238 (goto-char (point-min))
239 (let (alist elem method
)
242 (rfc2047-narrow-to-field)
244 alist rfc2047-header-encoding-alist
)
245 (while (setq elem
(pop alist
))
246 (when (or (and (stringp (car elem
))
247 (looking-at (car elem
)))
251 (if (not (rfc2047-encodable-p))
253 (when (eq method
'address-mime
)
254 (rfc2047-quote-special-characters-in-quoted-strings))
255 (if (and (eq (mm-body-7-or-8) '8bit
)
258 (car message-posting-charset
)))
259 ;; 8 bit must be decoded.
260 (mm-encode-coding-region
261 (point-min) (point-max)
262 (mm-charset-to-coding-system
263 (car message-posting-charset
))))
264 ;; No encoding necessary, but folding is nice
268 (goto-char (point-min))
269 (skip-chars-forward "^:")
270 (when (looking-at ": ")
274 ;; We found something that may perhaps be encoded.
275 (re-search-forward "^[^:]+: *" nil t
)
277 ((eq method
'address-mime
)
278 (rfc2047-encode-region (point) (point-max)))
280 (let ((rfc2047-encoding-type 'mime
))
281 (rfc2047-encode-region (point) (point-max))))
282 ((eq method
'default
)
283 (if (and (featurep 'mule
)
284 (if (boundp 'enable-multibyte-characters
)
285 (default-value 'enable-multibyte-characters
))
287 (mm-encode-coding-region (point) (point-max)
288 mail-parse-charset
)))
289 ;; We get this when CC'ing messsages to newsgroups with
290 ;; 8-bit names. The group name mail copy just got
291 ;; unconditionally encoded. Previously, it would ask
292 ;; whether to encode, which was quite confusing for the
293 ;; user. If the new behavior is wrong, tell me. I have
294 ;; left the old code commented out below.
295 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
296 ;; Modified by Dave Love, with the commented-out code changed
297 ;; in accordance with changes elsewhere.
299 (rfc2047-encode-region (point) (point-max)))
301 ;;; (if (or (message-options-get
302 ;;; 'rfc2047-encode-message-header-encode-any)
303 ;;; (message-options-set
304 ;;; 'rfc2047-encode-message-header-encode-any
306 ;;; "Some texts are not encoded. Encode anyway?")))
307 ;;; (rfc2047-encode-region (point-min) (point-max))
308 ;;; (error "Cannot send unencoded text")))
309 ((mm-coding-system-p method
)
310 (if (or (and (featurep 'mule
)
311 (if (boundp 'enable-multibyte-characters
)
312 (default-value 'enable-multibyte-characters
)))
313 (featurep 'file-coding
))
314 (mm-encode-coding-region (point) (point-max) method
)))
317 (goto-char (point-max)))))))
319 ;; Fixme: This, and the require below may not be the Right Thing, but
320 ;; should be safe just before release. -- fx 2001-02-08
322 (defun rfc2047-encodable-p ()
323 "Return non-nil if any characters in current buffer need encoding in headers.
324 The buffer may be narrowed."
325 (require 'message
) ; for message-posting-charset
327 (mm-find-mime-charset-region (point-min) (point-max))))
328 (goto-char (point-min))
329 (or (and rfc2047-encode-encoded-words
331 (re-search-forward rfc2047-encoded-word-regexp nil t
)
332 (goto-char (point-min))))
334 (not (equal charsets
(list (car message-posting-charset
))))))))
336 ;; Use this syntax table when parsing into regions that may need
337 ;; encoding. Double quotes are string delimiters, backslash is
338 ;; character quoting, and all other RFC 2822 special characters are
339 ;; treated as punctuation so we can use forward-sexp/forward-word to
340 ;; skip to the end of regions appropriately. Nb. ietf-drums does
341 ;; things differently.
342 (defconst rfc2047-syntax-table
343 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
344 (let ((table (make-syntax-table)))
345 ;; The following is done to work for setting all elements of the table
346 ;; in Emacs 21-23 and XEmacs; it appears to be the cleanest way.
347 ;; Play safe and don't assume the form of the word syntax entry --
349 (if (fboundp 'set-char-table-range
) ; Emacs
350 (funcall (intern "set-char-table-range")
351 table t
(aref (standard-syntax-table) ?a
))
352 (if (fboundp 'put-char-table
)
353 (if (fboundp 'get-char-table
) ; warning avoidance
354 (put-char-table t
(get-char-table ?a
(standard-syntax-table))
356 (modify-syntax-entry ?
\\ "\\" table
)
357 (modify-syntax-entry ?
\" "\"" table
)
358 (modify-syntax-entry ?\
( "(" table
)
359 (modify-syntax-entry ?\
) ")" table
)
360 (modify-syntax-entry ?\
< "." table
)
361 (modify-syntax-entry ?\
> "." table
)
362 (modify-syntax-entry ?\
[ "." table
)
363 (modify-syntax-entry ?\
] "." table
)
364 (modify-syntax-entry ?
: "." table
)
365 (modify-syntax-entry ?\
; "." table)
366 (modify-syntax-entry ?
, "." table
)
367 (modify-syntax-entry ?
@ "." table
)
370 (defun rfc2047-encode-region (b e
)
371 "Encode words in region B to E that need encoding.
372 By default, the region is treated as containing RFC2822 addresses.
373 Dynamically bind `rfc2047-encoding-type' to change that."
375 (narrow-to-region b e
)
376 (let ((encodable-regexp (if rfc2047-encode-encoded-words
377 "[^\000-\177]+\\|=\\?"
379 start
; start of current token
381 ;; Whether there's an encoded word before the current token,
382 ;; either immediately or separated by space.
384 (orig-text (buffer-substring-no-properties b e
)))
385 (if (eq 'mime rfc2047-encoding-type
)
386 ;; Simple case. Continuous words in which all those contain
387 ;; non-ASCII characters are encoded collectively. Encoding
388 ;; ASCII words, including `Re:' used in Subject headers, is
389 ;; avoided for interoperability with non-MIME clients and
390 ;; for making it easy to find keywords.
392 (goto-char (point-min))
393 (while (progn (skip-chars-forward " \t\n")
396 (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
398 (setq end
(match-end 0))
399 (re-search-forward encodable-regexp end t
)))
401 (if (> (point) start
)
402 (rfc2047-encode start
(point))
404 ;; `address-mime' case -- take care of quoted words, comments.
405 (rfc2047-quote-special-characters-in-quoted-strings encodable-regexp
)
406 (with-syntax-table rfc2047-syntax-table
407 (goto-char (point-min))
408 (condition-case err
; in case of unbalanced quotes
409 ;; Look for rfc2822-style: sequences of atoms, quoted
410 ;; strings, specials, whitespace. (Specials mustn't be
414 (skip-chars-forward " \t\n")
417 ((not (char-after))) ; eob
419 ((eq ?
\" (setq csyntax
(char-syntax (char-after))))
423 ;; Does it need encoding?
425 (if (re-search-forward encodable-regexp end
'move
)
426 ;; It needs encoding. Strip the quotes first,
427 ;; since encoded words can't occur in quotes.
434 ;; There was a preceding quoted word. We need
435 ;; to include any separating whitespace in this
436 ;; word to avoid it getting lost.
437 (skip-chars-backward " \t")
438 ;; A space is needed between the encoded words.
442 ;; Adjust the end position for the deleted quotes.
443 (rfc2047-encode start
(- end
2))
444 (setq last-encoded t
)) ; record that it was encoded
445 (setq last-encoded nil
)))
447 ;; Skip other delimiters, but record that they've
448 ;; potentially separated quoted words.
450 (setq last-encoded nil
))
452 (error "Unbalanced parentheses"))
454 ;; Look for the end of parentheses.
456 ;; Encode text as an unstructured field.
457 (let ((rfc2047-encoding-type 'mime
))
458 (rfc2047-encode-region (1+ start
) (1- (point))))
459 (skip-chars-forward ")"))
460 (t ; normal token/whitespace sequence
462 ;; Skip one ASCII word, or encode continuous words
463 ;; in which all those contain non-ASCII characters.
465 (while (not (or end
(eobp)))
466 (when (looking-at "[\000-\177]+")
470 (while (and (or (re-search-forward
471 "[ \t\n]\\|\\Sw" end
'move
)
473 (eq ?
\\ (char-syntax (char-before))))
474 ;; Skip backslash-quoted characters.
477 (setq end
(match-beginning 0))
478 (if rfc2047-encode-encoded-words
481 (when (search-forward "=?" end
'move
)
482 (goto-char (match-beginning 0))
485 ;; Where the value nil of `end' means there may be
486 ;; text to have to be encoded following the point.
487 ;; Otherwise, the point reached to the end of ASCII
488 ;; words separated by whitespace or a special char.
490 (when (looking-at encodable-regexp
)
491 (goto-char (setq begin
(match-end 0)))
492 (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
493 (setq end
(match-end 0))
495 (while (re-search-forward
496 encodable-regexp end t
))
499 (or (not (re-search-forward "\\Sw" end t
))
501 (goto-char (match-beginning 0))
504 (when (looking-at "[^ \t\n]+")
505 (setq end
(match-end 0))
506 (if (re-search-forward "\\Sw+" end t
)
507 ;; There are special characters better
508 ;; to be encoded so that MTAs may parse
510 (cond ((= end
(point)))
511 ((looking-at (concat "\\sw*\\("
516 (goto-char (1- (match-end 0)))
517 (unless (= (point) (match-beginning 0))
518 ;; Separate encodable text and
522 (skip-chars-forward " \t\n")
523 (if (and (looking-at "[^ \t\n]+")
524 (string-match encodable-regexp
527 (goto-char end
)))))))
528 (skip-chars-backward " \t\n")
531 (if (re-search-forward encodable-regexp end
'move
)
533 (unless (memq (char-before start
) '(nil ?
\t ?
))
536 (skip-chars-backward "^ \t\n")
537 (and (looking-at "\\Sw+")
538 (= (match-end 0) start
)))
539 ;; Also encode bogus delimiters.
541 ;; Separate encodable text and delimiter.
544 (setq start
(1+ start
)
546 (rfc2047-encode start end
)
547 (setq last-encoded t
))
548 (setq last-encoded nil
)))))
550 (if (or debug-on-quit debug-on-error
)
551 (signal (car err
) (cdr err
))
552 (error "Invalid data for rfc2047 encoding: %s"
553 (mm-replace-in-string orig-text
"[ \t\n]+" " "))))))))
554 (rfc2047-fold-region b
(point))
555 (goto-char (point-max))))
557 (defun rfc2047-encode-string (string)
558 "Encode words in STRING.
559 By default, the string is treated as containing addresses (see
560 `rfc2047-encoding-type')."
561 (mm-with-multibyte-buffer
563 (rfc2047-encode-region (point-min) (point-max))
567 ;; 2. Syntax of encoded-words
569 ;; While there is no limit to the length of a multiple-line header
570 ;; field, each line of a header field that contains one or more
571 ;; 'encoded-word's is limited to 76 characters.
573 ;; In `rfc2047-encode-parameter' it is bound to nil, so don't defconst it.
574 (defvar rfc2047-encode-max-chars
76
575 "Maximum characters of each header line that contain encoded-words.
576 According to RFC 2047, it is 76. If it is nil, encoded-words
577 will not be folded. Too small value may cause an error. You
578 should not change this value.")
580 (defun rfc2047-encode-1 (column string cs encoder start crest tail
582 "Subroutine used by `rfc2047-encode'."
583 (cond ((string-equal string
"")
585 ((not rfc2047-encode-max-chars
)
587 (funcall encoder
(if cs
588 (mm-encode-coding-string string cs
)
591 ((>= column rfc2047-encode-max-chars
)
593 (cond ((string-match "\n[ \t]+\\'" eword
)
594 ;; Reomove a superfluous empty line.
595 (setq eword
(substring eword
0 (match-beginning 0))))
596 ((string-match "(+\\'" eword
)
597 ;; Break the line before the open parenthesis.
598 (setq crest
(concat crest
(match-string 0 eword
))
599 eword
(substring eword
0 (match-beginning 0))))))
600 (rfc2047-encode-1 (length crest
) string cs encoder start
" " tail
601 (concat eword
"\n" crest
)))
604 (limit (1- (length string
)))
609 (setq next
(concat start
612 (mm-encode-coding-string
613 (substring string
0 (1+ index
))
615 (substring string
0 (1+ index
))))
617 len
(+ column
(length next
)))
618 (if (> len rfc2047-encode-max-chars
)
621 (if (or (< index limit
)
622 (<= (+ len
(or (string-match "\n" tail
)
624 rfc2047-encode-max-chars
))
627 (if (string-match "\\`)+" tail
)
628 ;; Break the line after the close parenthesis.
629 (setq tail
(concat (substring tail
0 (match-end 0))
631 (substring tail
(match-end 0)))
637 (concat eword next tail
)
640 (string-match "(+\\'" eword
))
641 (setq crest
(concat crest
(match-string 0 eword
))
642 eword
(substring eword
0 (match-beginning 0)))
643 (setq eword
(concat eword next
)))
645 eword
(concat eword next
)))
646 (when (string-match "\n[ \t]+\\'" eword
)
647 ;; Reomove a superfluous empty line.
648 (setq eword
(substring eword
0 (match-beginning 0))))
649 (rfc2047-encode-1 (length crest
) (substring string index
)
650 cs encoder start
" " tail
651 (concat eword
"\n" crest
)))))))
653 (defun rfc2047-encode (b e
)
654 "Encode the word(s) in the region B to E.
655 Point moves to the end of the region."
656 (let ((mime-charset (or (mm-find-mime-charset-region b e
) (list 'us-ascii
)))
657 cs encoding tail crest eword
)
658 (cond ((> (length mime-charset
) 1)
659 (error "Can't rfc2047-encode `%s'"
660 (buffer-substring-no-properties b e
)))
661 ((= (length mime-charset
) 1)
662 (setq mime-charset
(car mime-charset
)
663 cs
(mm-charset-to-coding-system mime-charset
))
664 (unless (and (mm-multibyte-p)
665 (mm-coding-system-p cs
))
668 (narrow-to-region b e
)
670 (or (cdr (assq mime-charset
671 rfc2047-charset-encoding-alist
))
672 ;; For the charsets that don't have a preferred
673 ;; encoding, choose the one that's shorter.
674 (if (eq (rfc2047-qp-or-base64) 'base64
)
679 (skip-chars-forward "^ \t\n")
680 ;; `tail' may contain a close parenthesis.
681 (setq tail
(buffer-substring-no-properties e
(point)))
683 (setq b
(point-marker)
684 e
(set-marker (make-marker) e
))
685 (rfc2047-fold-region (point-at-bol) b
)
687 (skip-chars-backward "^ \t\n")
688 (unless (= 0 (skip-chars-backward " \t"))
689 ;; `crest' may contain whitespace and an open parenthesis.
690 (setq crest
(buffer-substring-no-properties (point) b
)))
691 (setq eword
(rfc2047-encode-1
693 (mm-replace-in-string
694 (buffer-substring-no-properties b e
)
695 "\n\\([ \t]?\\)" "\\1")
697 (or (cdr (assq encoding
698 rfc2047-encode-function-alist
))
700 (concat "=?" (downcase (symbol-name mime-charset
))
701 "?" (upcase (symbol-name encoding
)) "?")
704 (delete-region (if (eq (aref eword
0) ?
\n)
706 ;; The line was folded before encoding.
711 ;; `eword' contains `crest' and `tail'.
715 (unless (or (/= 0 (length tail
))
717 (looking-at "[ \t\n)]"))
722 (defun rfc2047-fold-field ()
723 "Fold the current header field."
726 (rfc2047-narrow-to-field)
727 (rfc2047-fold-region (point-min) (point-max)))))
729 (defun rfc2047-fold-region (b e
)
730 "Fold long lines in region B to E."
732 (narrow-to-region b e
)
733 (goto-char (point-min))
737 (bol (save-restriction
741 (when (and (or break qword-break
)
742 (> (- (point) bol
) 76))
743 (goto-char (or break qword-break
))
746 (skip-chars-backward " \t")
747 (if (looking-at "[ \t]")
750 (setq bol
(1- (point)))
751 ;; Don't break before the first non-LWSP characters.
752 (skip-chars-forward " \t")
756 ((eq (char-after) ?
\n)
761 (skip-chars-forward " \t")
762 (unless (or (eobp) (eq (char-after) ?
\n))
764 ((eq (char-after) ?
\r)
766 ((memq (char-after) '(? ?
\t))
767 (skip-chars-forward " \t")
768 (unless first
;; Don't break just after the header name.
769 (setq break
(point))))
771 (if (not (looking-at "=\\?[^=]"))
772 (if (eq (char-after) ?
=)
774 (skip-chars-forward "^ \t\n\r="))
775 ;; Don't break at the start of the field.
776 (unless (= (point) b
)
777 (setq qword-break
(point)))
778 (skip-chars-forward "^ \t\n\r")))
780 (skip-chars-forward "^ \t\n\r")))
782 (when (and (or break qword-break
)
783 (> (- (point) bol
) 76))
784 (goto-char (or break qword-break
))
787 (if (or (> 0 (skip-chars-backward " \t"))
788 (looking-at "[ \t]"))
791 (setq bol
(1- (point)))
792 ;; Don't break before the first non-LWSP characters.
793 (skip-chars-forward " \t")
795 (forward-char 1))))))
797 (defun rfc2047-unfold-field ()
798 "Fold the current line."
801 (rfc2047-narrow-to-field)
802 (rfc2047-unfold-region (point-min) (point-max)))))
804 (defun rfc2047-unfold-region (b e
)
805 "Unfold lines in region B to E."
807 (narrow-to-region b e
)
808 (goto-char (point-min))
809 (let ((bol (save-restriction
812 (eol (point-at-eol)))
815 (if (and (looking-at "[ \t]")
816 (< (- (point-at-eol) bol
) 76))
817 (delete-region eol
(progn
819 (skip-chars-forward "\r\n")
821 (setq bol
(point-at-bol)))
822 (setq eol
(point-at-eol))
825 (defun rfc2047-b-encode-string (string)
826 "Base64-encode the header contained in STRING."
827 (base64-encode-string string t
))
829 (autoload 'quoted-printable-encode-region
"qp")
831 (defun rfc2047-q-encode-string (string)
832 "Quoted-printable-encode the header in STRING."
833 (mm-with-unibyte-buffer
835 (quoted-printable-encode-region
836 (point-min) (point-max) nil
837 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
838 ;; Avoid using 8bit characters.
839 ;; This list excludes `especials' (see the RFC2047 syntax),
840 ;; meaning that some characters in non-structured fields will
841 ;; get encoded when they con't need to be. The following is
842 ;; what it used to be.
843 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
844 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
845 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
846 (subst-char-in-region (point-min) (point-max) ? ?_
)
849 (defun rfc2047-encode-parameter (param value
)
850 "Return and PARAM=VALUE string encoded in the RFC2047-like style.
851 This is a replacement for the `rfc2231-encode-string' function.
853 When attaching files as MIME parts, we should use the RFC2231 encoding
854 to specify the file names containing non-ASCII characters. However,
855 many mail softwares don't support it in practice and recipients won't
856 be able to extract files with correct names. Instead, the RFC2047-like
857 encoding is acceptable generally. This function provides the very
858 RFC2047-like encoding, resigning to such a regrettable trend. To use
859 it, put the following line in your ~/.gnus.el file:
861 \(defalias 'mail-header-encode-parameter 'rfc2047-encode-parameter)
863 (let ((rfc2047-encoding-type 'mime
)
864 (rfc2047-encode-max-chars nil
))
865 (rfc2045-encode-string param
(rfc2047-encode-string value
))))
868 ;;; Functions for decoding RFC2047 messages
871 (defvar rfc2047-quote-decoded-words-containing-tspecials nil
872 "If non-nil, quote decoded words containing special characters.")
874 (defvar rfc2047-allow-incomplete-encoded-text t
875 "*Non-nil means allow incomplete encoded-text in successive encoded-words.
876 Dividing of encoded-text in the place other than character boundaries
877 violates RFC2047 section 5, while we have a capability to decode it.
878 If it is non-nil, the decoder will decode B- or Q-encoding in each
879 encoded-word, concatenate them, and decode it by charset. Otherwise,
880 the decoder will fully decode each encoded-word before concatenating
883 (defun rfc2047-strip-backslashes-in-quoted-strings ()
884 "Strip backslashes in quoted strings. `\\\"' remains."
885 (goto-char (point-min))
887 (with-syntax-table (standard-syntax-table)
888 (while (search-forward "\"" nil t
)
889 (unless (eq (char-before) ?
\\)
890 (setq beg
(match-end 0))
891 (goto-char (match-beginning 0))
896 (narrow-to-region beg
(1- (point)))
898 (while (search-forward "\\" nil
'move
)
899 (unless (memq (char-after) '(?
\"))
904 (goto-char beg
))))))))
906 (defun rfc2047-charset-to-coding-system (charset &optional allow-override
)
907 "Return coding-system corresponding to MIME CHARSET.
908 If your Emacs implementation can't decode CHARSET, return nil.
910 If allow-override is given, use `mm-charset-override-alist' to
911 map undesired charset names to their replacement. This should
912 only be used for decoding, not for encoding."
913 (when (stringp charset
)
914 (setq charset
(intern (downcase charset
))))
915 (when (or (not charset
)
916 (eq 'gnus-all mail-parse-ignored-charsets
)
917 (memq 'gnus-all mail-parse-ignored-charsets
)
918 (memq charset mail-parse-ignored-charsets
))
919 (setq charset mail-parse-charset
))
920 (let ((cs (mm-charset-to-coding-system charset nil allow-override
)))
921 (cond ((eq cs
'ascii
)
922 (setq cs
(or (mm-charset-to-coding-system mail-parse-charset
)
924 ((mm-coding-system-p cs
))
926 (listp mail-parse-ignored-charsets
)
927 (memq 'gnus-unknown mail-parse-ignored-charsets
))
928 (setq cs
(mm-charset-to-coding-system mail-parse-charset
))))
933 (autoload 'quoted-printable-decode-string
"qp")
935 (defun rfc2047-decode-encoded-words (words)
936 "Decode successive encoded-words in WORDS and return a decoded string.
937 Each element of WORDS looks like (CHARSET ENCODING ENCODED-TEXT
939 (let (word charset cs encoding text rest
)
941 (setq word
(pop words
))
942 (if (and (setq cs
(rfc2047-charset-to-coding-system
943 (setq charset
(car word
)) t
))
945 (cond ((char-equal ?B
(nth 1 word
))
946 (setq text
(base64-decode-string
947 (rfc2047-pad-base64 (nth 2 word
)))))
948 ((char-equal ?Q
(nth 1 word
))
949 (setq text
(quoted-printable-decode-string
950 (mm-subst-char-in-string
951 ?_ ?
(nth 2 word
) t
)))))
953 (message "%s" (error-message-string code
))
955 (if (and rfc2047-allow-incomplete-encoded-text
957 ;; Concatenate text of which the charset is the same.
958 (setcdr (car rest
) (concat (cdar rest
) text
))
959 (push (cons cs text
) rest
))
960 ;; Don't decode encoded-word.
961 (push (cons nil
(nth 3 word
)) rest
)))
964 (or (and (setq cs
(caar rest
))
966 (mm-decode-coding-string (cdar rest
) cs
)
968 (message "%s" (error-message-string code
))
970 (concat (when (cdr rest
) " ")
973 (not (eq (string-to-char words
) ?
)))
979 ;; Fixme: This should decode in place, not cons intermediate strings.
980 ;; Also check whether it needs to worry about delimiting fields like
983 ;; In fact it's reported that (invalid) encoding of mailboxes in
984 ;; addr-specs is in use, so delimiting fields might help. Probably
985 ;; not decoding a word which isn't properly delimited is good enough
986 ;; and worthwhile (is it more correct or not?), e.g. something like
987 ;; `=?iso-8859-1?q?foo?=@'.
989 (defun rfc2047-decode-region (start end
&optional address-mime
)
990 "Decode MIME-encoded words in region between START and END.
991 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
992 other than `\"' and `\\' in quoted strings."
994 (let ((case-fold-search t
)
996 (if rfc2047-allow-irregular-q-encoded-words
998 (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp-loose
"\\)"))
1000 (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp
"\\)"))))
1004 (narrow-to-region start end
)
1006 (rfc2047-strip-backslashes-in-quoted-strings))
1007 (goto-char (setq b start
))
1008 ;; Look for the encoded-words.
1009 (while (setq match
(re-search-forward eword-regexp nil t
))
1010 (setq e
(match-beginning 1)
1014 (push (list (match-string 2) ;; charset
1015 (char-after (match-beginning 3)) ;; encoding
1016 (substring (match-string 3) 2) ;; encoded-text
1017 (match-string 1)) ;; encoded-word
1019 ;; Look for the subsequent encoded-words.
1020 (when (setq match
(looking-at eword-regexp
))
1021 (goto-char (setq end
(match-end 0)))))
1022 ;; Replace the encoded-words with the decoded one.
1023 (delete-region e end
)
1024 (insert (rfc2047-decode-encoded-words (nreverse words
)))
1026 (narrow-to-region e
(point))
1028 ;; Remove newlines between decoded words, though such
1029 ;; things essentially must not be there.
1030 (while (re-search-forward "[\n\r]+" nil t
)
1031 (replace-match " "))
1032 (setq end
(point-max))
1033 ;; Quote decoded words if there are special characters
1034 ;; which might violate RFC2822.
1035 (when (and rfc2047-quote-decoded-words-containing-tspecials
1036 (let ((regexp (car (rassq
1038 rfc2047-header-encoding-alist
))))
1043 ;; Don't quote words if already quoted.
1044 (not (and (eq (char-before e
) ?
\")
1045 (eq (char-after end
) ?
\")))
1048 (while (and (memq (char-after) '(? ?
\t))
1049 (zerop (forward-line -
1))))
1050 (looking-at regexp
)))))))
1053 (skip-chars-forward " \t")
1054 (setq start
(point))
1055 (setq quoted
(eq (char-after) ?
\"))
1056 (goto-char (point-max))
1057 (skip-chars-backward " \t" start
)
1058 (if (setq quoted
(and quoted
1059 (> (point) (1+ start
))
1060 (eq (char-before) ?
\")))
1063 (setq start
(1+ start
)
1064 end
(point-marker)))
1065 (setq end
(point-marker)))
1067 (while (search-forward "\"" end t
)
1070 (zerop (%
(skip-chars-backward "\\\\") 2))
1071 (goto-char (match-beginning 0)))
1074 (when (and (not quoted
)
1078 (concat "[" ietf-drums-tspecials
"]")
1084 (set-marker end nil
)))
1085 (goto-char (point-max)))
1086 (when (and (mm-multibyte-p)
1088 (not (eq mail-parse-charset
'us-ascii
))
1089 (not (eq mail-parse-charset
'gnus-decoded
)))
1090 (mm-decode-coding-region b e mail-parse-charset
))
1092 (when (and (mm-multibyte-p)
1094 (not (eq mail-parse-charset
'us-ascii
))
1095 (not (eq mail-parse-charset
'gnus-decoded
)))
1096 (mm-decode-coding-region b
(point-max) mail-parse-charset
))))))
1098 (defun rfc2047-decode-address-region (start end
)
1099 "Decode MIME-encoded words in region between START and END.
1100 Backslashes which precede characters other than `\"' and `\\' in quoted
1101 strings are stripped."
1102 (rfc2047-decode-region start end t
))
1104 (defun rfc2047-decode-string (string &optional address-mime
)
1105 "Decode MIME-encoded STRING and return the result.
1106 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
1107 other than `\"' and `\\' in quoted strings."
1108 ;; (let ((m (mm-multibyte-p)))
1109 (if (string-match "=\\?" string
)
1111 ;; We used to only call mm-enable-multibyte if `m' is non-nil,
1112 ;; but this can't be the right criterion. Don't just revert this
1113 ;; change if it encounters a bug. Please help me fix it
1114 ;; right instead. --Stef
1115 ;; The string returned should always be multibyte in a multibyte
1116 ;; session, i.e. the buffer should be multibyte before
1117 ;; `buffer-string' is called.
1118 (mm-enable-multibyte)
1121 (rfc2047-decode-region (point-min) (point-max) address-mime
))
1126 (when (mm-multibyte-string-p string
)
1127 (mm-enable-multibyte))
1129 (rfc2047-strip-backslashes-in-quoted-strings)
1131 ;; Fixme: As above, `m' here is inappropriate.
1134 (not (eq mail-parse-charset
'us-ascii
))
1135 (not (eq mail-parse-charset
'gnus-decoded
)))
1136 ;; `decode-coding-string' in Emacs offers a third optional
1137 ;; arg NOCOPY to avoid consing a new string if the decoding
1138 ;; is "trivial". Unfortunately it currently doesn't
1139 ;; consider anything else than a `nil' coding system
1141 ;; `rfc2047-decode-string' is called multiple times for each
1142 ;; article during summary buffer generation, and we really
1143 ;; want to avoid unnecessary consing. So we bypass
1144 ;; `decode-coding-string' if the string is purely ASCII.
1145 (if (and (fboundp 'detect-coding-string
)
1146 ;; string is purely ASCII
1147 (eq (detect-coding-string string t
) 'undecided
))
1149 (mm-decode-coding-string string mail-parse-charset
))
1150 (mm-string-to-multibyte string
)))) ;; )
1152 (defun rfc2047-decode-address-string (string)
1153 "Decode MIME-encoded STRING and return the result.
1154 Backslashes which precede characters other than `\"' and `\\' in quoted
1155 strings are stripped."
1156 (rfc2047-decode-string string t
))
1158 (defun rfc2047-pad-base64 (string)
1159 "Pad STRING to quartets."
1160 ;; Be more liberal to accept buggy base64 strings. If
1161 ;; base64-decode-string accepts buggy strings, this function could
1162 ;; be aliased to identity.
1163 (if (= 0 (mod (length string
) 4))
1165 (when (string-match "=+$" string
)
1166 (setq string
(substring string
0 (match-beginning 0))))
1167 (case (mod (length string
) 4)
1169 (1 string
) ;; Error, don't pad it.
1170 (2 (concat string
"=="))
1171 (3 (concat string
"=")))))
1175 ;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
1176 ;;; rfc2047.el ends here