]> code.delx.au - gnu-emacs/blob - lisp/mail/rfc2047.el
4cb10e543936a10d6d194ef21668dd6c6134f7a1
[gnu-emacs] / lisp / mail / rfc2047.el
1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
25 ;; Three: Message Header Extensions for Non-ASCII Text".
26
27 ;;; Code:
28
29 (eval-when-compile
30 (require 'cl))
31 (defvar message-posting-charset)
32
33 (require 'mm-util)
34 (require 'ietf-drums)
35 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
36 (require 'mail-prsvr)
37 (require 'rfc2045) ;; rfc2045-encode-string
38 (autoload 'mm-body-7-or-8 "mm-bodies")
39
40 (defvar rfc2047-header-encoding-alist
41 '(("Newsgroups" . nil)
42 ("Followup-To" . nil)
43 ("Message-ID" . nil)
44 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|\\(In-\\)?Reply-To\\|Sender\
45 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
46 (t . mime))
47 "*Header/encoding method alist.
48 The list is traversed sequentially. The keys can either be
49 header regexps or t.
50
51 The values can be:
52
53 1) nil, in which case no encoding is done;
54 2) `mime', in which case the header will be encoded according to RFC2047;
55 3) `address-mime', like `mime', but takes account of the rules for address
56 fields (where quoted strings and comments must be treated separately);
57 4) a charset, in which case it will be encoded as that charset;
58 5) `default', in which case the field will be encoded as the rest
59 of the article.")
60
61 (defvar rfc2047-charset-encoding-alist
62 '((us-ascii . nil)
63 (iso-8859-1 . Q)
64 (iso-8859-2 . Q)
65 (iso-8859-3 . Q)
66 (iso-8859-4 . Q)
67 (iso-8859-5 . B)
68 (koi8-r . B)
69 (iso-8859-7 . B)
70 (iso-8859-8 . B)
71 (iso-8859-9 . Q)
72 (iso-8859-14 . Q)
73 (iso-8859-15 . Q)
74 (iso-2022-jp . B)
75 (iso-2022-kr . B)
76 (gb2312 . B)
77 (gbk . B)
78 (gb18030 . B)
79 (big5 . B)
80 (cn-big5 . B)
81 (cn-gb . B)
82 (cn-gb-2312 . B)
83 (euc-kr . B)
84 (iso-2022-jp-2 . B)
85 (iso-2022-int-1 . B)
86 (viscii . Q))
87 "Alist of MIME charsets to RFC2047 encodings.
88 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
89 quoted-printable and base64 respectively.")
90
91 (defvar rfc2047-encode-function-alist
92 '((Q . rfc2047-q-encode-string)
93 (B . rfc2047-b-encode-string)
94 (nil . identity))
95 "Alist of RFC2047 encodings to encoding functions.")
96
97 (defvar rfc2047-encode-encoded-words t
98 "Whether encoded words should be encoded again.")
99
100 (defvar rfc2047-allow-irregular-q-encoded-words t
101 "*Whether to decode irregular Q-encoded words.")
102
103 (eval-and-compile ;; Necessary to hard code them in `rfc2047-decode-region'.
104 (defconst rfc2047-encoded-word-regexp
105 "=\\?\\([^][\000-\040()<>@,;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
106 \\(B\\?[+/0-9A-Za-z]*=*\
107 \\|Q\\?[ ->@-~]*\
108 \\)\\?="
109 "Regexp that matches encoded word."
110 ;; The patterns for the B encoding and the Q encoding, i.e. the ones
111 ;; beginning with "B" and "Q" respectively, are restricted into only
112 ;; the characters that those encodings may generally use.
113 )
114 (defconst rfc2047-encoded-word-regexp-loose
115 "=\\?\\([^][\000-\040()<>@,;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
116 \\(B\\?[+/0-9A-Za-z]*=*\
117 \\|Q\\?\\(?:\\?+[ -<>@-~]\\)?\\(?:[ ->@-~]+\\?+[ -<>@-~]\\)*[ ->@-~]*\\?*\
118 \\)\\?="
119 "Regexp that matches encoded word allowing loose Q encoding."
120 ;; The pattern for the Q encoding, i.e. the one beginning with "Q",
121 ;; is similar to:
122 ;; "Q\\?\\(\\?+[^\n=?]\\)?\\([^\n?]+\\?+[^\n=?]\\)*[^\n?]*\\?*"
123 ;; <--------1-------><----------2,3----------><--4--><-5->
124 ;; They mean:
125 ;; 1. After "Q?", allow "?"s that follow a character other than "=".
126 ;; 2. Allow "=" after "Q?"; it isn't regarded as the terminator.
127 ;; 3. In the middle of an encoded word, allow "?"s that follow a
128 ;; character other than "=".
129 ;; 4. Allow any characters other than "?" in the middle of an
130 ;; encoded word.
131 ;; 5. At the end, allow "?"s.
132 ))
133
134 ;;;
135 ;;; Functions for encoding RFC2047 messages
136 ;;;
137
138 (defun rfc2047-qp-or-base64 ()
139 "Return the type with which to encode the buffer.
140 This is either `base64' or `quoted-printable'."
141 (save-excursion
142 (let ((limit (min (point-max) (+ 2000 (point-min))))
143 (n8bit 0))
144 (goto-char (point-min))
145 (skip-chars-forward "\x20-\x7f\r\n\t" limit)
146 (while (< (point) limit)
147 (incf n8bit)
148 (forward-char 1)
149 (skip-chars-forward "\x20-\x7f\r\n\t" limit))
150 (if (or (< (* 6 n8bit) (- limit (point-min)))
151 ;; Don't base64, say, a short line with a single
152 ;; non-ASCII char when splitting parts by charset.
153 (= n8bit 1))
154 'quoted-printable
155 'base64))))
156
157 (defun rfc2047-narrow-to-field ()
158 "Narrow the buffer to the header on the current line."
159 (beginning-of-line)
160 (narrow-to-region
161 (point)
162 (progn
163 (forward-line 1)
164 (if (re-search-forward "^[^ \n\t]" nil t)
165 (point-at-bol)
166 (point-max))))
167 (goto-char (point-min)))
168
169 (defun rfc2047-field-value ()
170 "Return the value of the field at point."
171 (save-excursion
172 (save-restriction
173 (rfc2047-narrow-to-field)
174 (re-search-forward ":[ \t\n]*" nil t)
175 (buffer-substring-no-properties (point) (point-max)))))
176
177 (defun rfc2047-quote-special-characters-in-quoted-strings (&optional
178 encodable-regexp)
179 "Quote special characters with `\\'s in quoted strings.
180 Quoting will not be done in a quoted string if it contains characters
181 matching ENCODABLE-REGEXP or it is within parentheses."
182 (goto-char (point-min))
183 (let ((tspecials (concat "[" ietf-drums-tspecials "]"))
184 (start (point))
185 beg end)
186 (with-syntax-table (standard-syntax-table)
187 (while (not (eobp))
188 (if (ignore-errors
189 (forward-list 1)
190 (eq (char-before) ?\)))
191 (forward-list -1)
192 (goto-char (point-max)))
193 (save-restriction
194 (narrow-to-region start (point))
195 (goto-char start)
196 (while (search-forward "\"" nil t)
197 (setq beg (match-beginning 0))
198 (unless (eq (char-before beg) ?\\)
199 (goto-char beg)
200 (setq beg (1+ beg))
201 (condition-case nil
202 (progn
203 (forward-sexp)
204 (setq end (1- (point)))
205 (goto-char beg)
206 (if (and encodable-regexp
207 (re-search-forward encodable-regexp end t))
208 (goto-char (1+ end))
209 (save-restriction
210 (narrow-to-region beg end)
211 (while (re-search-forward tspecials nil 'move)
212 (if (eq (char-before) ?\\)
213 (if (looking-at tspecials) ;; Already quoted.
214 (forward-char)
215 (insert "\\"))
216 (goto-char (match-beginning 0))
217 (insert "\\")
218 (forward-char))))
219 (forward-char)))
220 (error
221 (goto-char beg)))))
222 (goto-char (point-max)))
223 (forward-list 1)
224 (setq start (point))))))
225
226 (defvar rfc2047-encoding-type 'address-mime
227 "The type of encoding done by `rfc2047-encode-region'.
228 This should be dynamically bound around calls to
229 `rfc2047-encode-region' to either `mime' or `address-mime'. See
230 `rfc2047-header-encoding-alist', for definitions.")
231
232 (defun rfc2047-encode-message-header ()
233 "Encode the message header according to `rfc2047-header-encoding-alist'.
234 Should be called narrowed to the head of the message."
235 (interactive "*")
236 (save-excursion
237 (goto-char (point-min))
238 (let (alist elem method charsets)
239 (while (not (eobp))
240 (save-restriction
241 (rfc2047-narrow-to-field)
242 (setq method nil
243 alist rfc2047-header-encoding-alist
244 charsets (mm-find-mime-charset-region (point-min) (point-max)))
245 ;; M$ Outlook boycotts decoding of a header if it consists
246 ;; of two or more encoded words and those charsets differ;
247 ;; it seems to decode all words in a header from a charset
248 ;; found first in the header. So, we unify the charsets into
249 ;; a single one used for encoding the whole text in a header.
250 (let ((mm-coding-system-priorities
251 (if (= (length charsets) 1)
252 (cons (mm-charset-to-coding-system (car charsets))
253 mm-coding-system-priorities)
254 mm-coding-system-priorities)))
255 (while (setq elem (pop alist))
256 (when (or (and (stringp (car elem))
257 (looking-at (car elem)))
258 (eq (car elem) t))
259 (setq alist nil
260 method (cdr elem))))
261 (if (not (rfc2047-encodable-p))
262 (prog2
263 (when (eq method 'address-mime)
264 (rfc2047-quote-special-characters-in-quoted-strings))
265 (if (and (eq (mm-body-7-or-8) '8bit)
266 (mm-multibyte-p)
267 (mm-coding-system-p
268 (car message-posting-charset)))
269 ;; 8 bit must be decoded.
270 (encode-coding-region
271 (point-min) (point-max)
272 (mm-charset-to-coding-system
273 (car message-posting-charset))))
274 ;; No encoding necessary, but folding is nice
275 (when nil
276 (rfc2047-fold-region
277 (save-excursion
278 (goto-char (point-min))
279 (skip-chars-forward "^:")
280 (when (looking-at ": ")
281 (forward-char 2))
282 (point))
283 (point-max))))
284 ;; We found something that may perhaps be encoded.
285 (re-search-forward "^[^:]+: *" nil t)
286 (cond
287 ((eq method 'address-mime)
288 (rfc2047-encode-region (point) (point-max)))
289 ((eq method 'mime)
290 (let ((rfc2047-encoding-type 'mime))
291 (rfc2047-encode-region (point) (point-max))))
292 ((eq method 'default)
293 (if (and (default-value 'enable-multibyte-characters)
294 mail-parse-charset)
295 (encode-coding-region (point) (point-max)
296 mail-parse-charset)))
297 ;; We get this when CC'ing messages to newsgroups with
298 ;; 8-bit names. The group name mail copy just got
299 ;; unconditionally encoded. Previously, it would ask
300 ;; whether to encode, which was quite confusing for the
301 ;; user. If the new behavior is wrong, tell me. I have
302 ;; left the old code commented out below.
303 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
304 ;; Modified by Dave Love, with the commented-out code changed
305 ;; in accordance with changes elsewhere.
306 ((null method)
307 (rfc2047-encode-region (point) (point-max)))
308 ;;; ((null method)
309 ;;; (if (or (message-options-get
310 ;;; 'rfc2047-encode-message-header-encode-any)
311 ;;; (message-options-set
312 ;;; 'rfc2047-encode-message-header-encode-any
313 ;;; (y-or-n-p
314 ;;; "Some texts are not encoded. Encode anyway?")))
315 ;;; (rfc2047-encode-region (point-min) (point-max))
316 ;;; (error "Cannot send unencoded text")))
317 ((mm-coding-system-p method)
318 (when (default-value 'enable-multibyte-characters)
319 (encode-coding-region (point) (point-max) method)))
320 ;; Hm.
321 (t)))
322 (goto-char (point-max))))))))
323
324 ;; Fixme: This, and the require below may not be the Right Thing, but
325 ;; should be safe just before release. -- fx 2001-02-08
326
327 (defun rfc2047-encodable-p ()
328 "Return non-nil if any characters in current buffer need encoding in headers.
329 The buffer may be narrowed."
330 (require 'message) ; for message-posting-charset
331 (let ((charsets
332 (mm-find-mime-charset-region (point-min) (point-max))))
333 (goto-char (point-min))
334 (or (and rfc2047-encode-encoded-words
335 (prog1
336 (re-search-forward rfc2047-encoded-word-regexp nil t)
337 (goto-char (point-min))))
338 (and charsets
339 (not (equal charsets (list (car message-posting-charset))))))))
340
341 ;; Use this syntax table when parsing into regions that may need
342 ;; encoding. Double quotes are string delimiters, backslash is
343 ;; character quoting, and all other RFC 2822 special characters are
344 ;; treated as punctuation so we can use forward-sexp/forward-word to
345 ;; skip to the end of regions appropriately. Nb. ietf-drums does
346 ;; things differently.
347 (defconst rfc2047-syntax-table
348 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
349 (let ((table (make-syntax-table)))
350 ;; The following is done to work for setting all elements of the table;
351 ;; it appears to be the cleanest way.
352 ;; Play safe and don't assume the form of the word syntax entry --
353 ;; copy it from ?a.
354 (set-char-table-range table t (aref (standard-syntax-table) ?a))
355 (modify-syntax-entry ?\\ "\\" 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 table))
368
369 (defun rfc2047-encode-region (b e &optional dont-fold)
370 "Encode words in region B to E that need encoding.
371 By default, the region is treated as containing RFC2822 addresses.
372 Dynamically bind `rfc2047-encoding-type' to change that."
373 (save-restriction
374 (narrow-to-region b e)
375 (let ((encodable-regexp (if rfc2047-encode-encoded-words
376 "[^\000-\177]+\\|=\\?"
377 "[^\000-\177]+"))
378 start ; start of current token
379 end begin csyntax
380 ;; Whether there's an encoded word before the current token,
381 ;; either immediately or separated by space.
382 last-encoded
383 (orig-text (buffer-substring-no-properties b e)))
384 (if (eq 'mime rfc2047-encoding-type)
385 ;; Simple case. Continuous words in which all those contain
386 ;; non-ASCII characters are encoded collectively. Encoding
387 ;; ASCII words, including `Re:' used in Subject headers, is
388 ;; avoided for interoperability with non-MIME clients and
389 ;; for making it easy to find keywords.
390 (progn
391 (goto-char (point-min))
392 (while (progn (skip-chars-forward " \t\n")
393 (not (eobp)))
394 (setq start (point))
395 (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
396 (progn
397 (setq end (match-end 0))
398 (re-search-forward encodable-regexp end t)))
399 (goto-char end))
400 (if (> (point) start)
401 (rfc2047-encode start (point))
402 (goto-char end))))
403 ;; `address-mime' case -- take care of quoted words, comments.
404 (rfc2047-quote-special-characters-in-quoted-strings encodable-regexp)
405 (with-syntax-table rfc2047-syntax-table
406 (goto-char (point-min))
407 (condition-case err ; in case of unbalanced quotes
408 ;; Look for rfc2822-style: sequences of atoms, quoted
409 ;; strings, specials, whitespace. (Specials mustn't be
410 ;; encoded.)
411 (while (not (eobp))
412 ;; Skip whitespace.
413 (skip-chars-forward " \t\n")
414 (setq start (point))
415 (cond
416 ((not (char-after))) ; eob
417 ;; else token start
418 ((eq ?\" (setq csyntax (char-syntax (char-after))))
419 ;; Quoted word.
420 (forward-sexp)
421 (setq end (point))
422 ;; Does it need encoding?
423 (goto-char start)
424 (if (re-search-forward encodable-regexp end 'move)
425 ;; It needs encoding. Strip the quotes first,
426 ;; since encoded words can't occur in quotes.
427 (progn
428 (goto-char end)
429 (delete-char -1)
430 (goto-char start)
431 (delete-char 1)
432 (when last-encoded
433 ;; There was a preceding quoted word. We need
434 ;; to include any separating whitespace in this
435 ;; word to avoid it getting lost.
436 (skip-chars-backward " \t")
437 ;; A space is needed between the encoded words.
438 (insert ? )
439 (setq start (point)
440 end (1+ end)))
441 ;; Adjust the end position for the deleted quotes.
442 (rfc2047-encode start (- end 2))
443 (setq last-encoded t)) ; record that it was encoded
444 (setq last-encoded nil)))
445 ((eq ?. csyntax)
446 ;; Skip other delimiters, but record that they've
447 ;; potentially separated quoted words.
448 (forward-char)
449 (setq last-encoded nil))
450 ((eq ?\) csyntax)
451 (error "Unbalanced parentheses"))
452 ((eq ?\( csyntax)
453 ;; Look for the end of parentheses.
454 (forward-list)
455 ;; Encode text as an unstructured field.
456 (let ((rfc2047-encoding-type 'mime))
457 (rfc2047-encode-region (1+ start) (1- (point))))
458 (skip-chars-forward ")"))
459 (t ; normal token/whitespace sequence
460 ;; Find the end.
461 ;; Skip one ASCII word, or encode continuous words
462 ;; in which all those contain non-ASCII characters.
463 (setq end nil)
464 (while (not (or end (eobp)))
465 (when (looking-at "[\000-\177]+")
466 (setq begin (point)
467 end (match-end 0))
468 (when (progn
469 (while (and (or (re-search-forward
470 "[ \t\n]\\|\\Sw" end 'move)
471 (setq end nil))
472 (eq ?\\ (char-syntax (char-before))))
473 ;; Skip backslash-quoted characters.
474 (forward-char))
475 end)
476 (setq end (match-beginning 0))
477 (if rfc2047-encode-encoded-words
478 (progn
479 (goto-char begin)
480 (when (search-forward "=?" end 'move)
481 (goto-char (match-beginning 0))
482 (setq end nil)))
483 (goto-char end))))
484 ;; Where the value nil of `end' means there may be
485 ;; text to have to be encoded following the point.
486 ;; Otherwise, the point reached to the end of ASCII
487 ;; words separated by whitespace or a special char.
488 (unless end
489 (when (looking-at encodable-regexp)
490 (goto-char (setq begin (match-end 0)))
491 (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
492 (setq end (match-end 0))
493 (progn
494 (while (re-search-forward
495 encodable-regexp end t))
496 (< begin (point)))
497 (goto-char begin)
498 (or (not (re-search-forward "\\Sw" end t))
499 (progn
500 (goto-char (match-beginning 0))
501 nil)))
502 (goto-char end))
503 (when (looking-at "[^ \t\n]+")
504 (setq end (match-end 0))
505 (if (re-search-forward "\\Sw+" end t)
506 ;; There are special characters better
507 ;; to be encoded so that MTAs may parse
508 ;; them safely.
509 (cond ((= end (point)))
510 ((looking-at (concat "\\sw*\\("
511 encodable-regexp
512 "\\)"))
513 (setq end nil))
514 (t
515 (goto-char (1- (match-end 0)))
516 (unless (= (point) (match-beginning 0))
517 ;; Separate encodable text and
518 ;; delimiter.
519 (insert " "))))
520 (goto-char end)
521 (skip-chars-forward " \t\n")
522 (if (and (looking-at "[^ \t\n]+")
523 (string-match encodable-regexp
524 (match-string 0)))
525 (setq end nil)
526 (goto-char end)))))))
527 (skip-chars-backward " \t\n")
528 (setq end (point))
529 (goto-char start)
530 (if (re-search-forward encodable-regexp end 'move)
531 (progn
532 (unless (memq (char-before start) '(nil ?\t ? ))
533 (if (progn
534 (goto-char start)
535 (skip-chars-backward "^ \t\n")
536 (and (looking-at "\\Sw+")
537 (= (match-end 0) start)))
538 ;; Also encode bogus delimiters.
539 (setq start (point))
540 ;; Separate encodable text and delimiter.
541 (goto-char start)
542 (insert " ")
543 (setq start (1+ start)
544 end (1+ end))))
545 (rfc2047-encode start end)
546 (setq last-encoded t))
547 (setq last-encoded nil)))))
548 (error
549 (if (or debug-on-quit debug-on-error)
550 (signal (car err) (cdr err))
551 (error "Invalid data for rfc2047 encoding: %s"
552 (replace-regexp-in-string "[ \t\n]+" " " orig-text))))))))
553 (unless dont-fold
554 (rfc2047-fold-region b (point)))
555 (goto-char (point-max))))
556
557 (defun rfc2047-encode-string (string &optional dont-fold)
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
562 (insert string)
563 (rfc2047-encode-region (point-min) (point-max) dont-fold)
564 (buffer-string)))
565
566 ;; From RFC 2047:
567 ;; 2. Syntax of encoded-words
568 ;; [...]
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.
572 ;;
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.")
579
580 (defun rfc2047-encode-1 (column string cs encoder start crest tail
581 &optional eword)
582 "Subroutine used by `rfc2047-encode'."
583 (cond ((string-equal string "")
584 (or eword ""))
585 ((not rfc2047-encode-max-chars)
586 (concat start
587 (funcall encoder (if cs
588 (encode-coding-string string cs)
589 string))
590 "?="))
591 ((>= column rfc2047-encode-max-chars)
592 (when eword
593 (cond ((string-match "\n[ \t]+\\'" eword)
594 ;; Remove 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)))
602 (t
603 (let ((index 0)
604 (limit (1- (length string)))
605 (prev "")
606 next len)
607 (while (and prev
608 (<= index limit))
609 (setq next (concat start
610 (funcall encoder
611 (if cs
612 (encode-coding-string
613 (substring string 0 (1+ index))
614 cs)
615 (substring string 0 (1+ index))))
616 "?=")
617 len (+ column (length next)))
618 (if (> len rfc2047-encode-max-chars)
619 (setq next prev
620 prev nil)
621 (if (or (< index limit)
622 (<= (+ len (or (string-match "\n" tail)
623 (length tail)))
624 rfc2047-encode-max-chars))
625 (setq prev next
626 index (1+ index))
627 (if (string-match "\\`)+" tail)
628 ;; Break the line after the close parenthesis.
629 (setq tail (concat (substring tail 0 (match-end 0))
630 "\n "
631 (substring tail (match-end 0)))
632 prev next
633 index (1+ index))
634 (setq next prev
635 prev nil)))))
636 (if (> index limit)
637 (concat eword next tail)
638 (if (= 0 index)
639 (if (and eword
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)))
644 (setq crest " "
645 eword (concat eword next)))
646 (when (string-match "\n[ \t]+\\'" eword)
647 ;; Remove 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)))))))
652
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 ;; Use utf-8 as a last resort if determining charset of text fails.
659 (if (memq nil mime-charset)
660 (setq mime-charset (list 'utf-8)))
661 (cond ((> (length mime-charset) 1)
662 (error "Can't rfc2047-encode `%s'"
663 (buffer-substring-no-properties b e)))
664 ((= (length mime-charset) 1)
665 (setq mime-charset (car mime-charset)
666 cs (mm-charset-to-coding-system mime-charset))
667 (unless (and (mm-multibyte-p)
668 (mm-coding-system-p cs))
669 (setq cs nil))
670 (save-restriction
671 (narrow-to-region b e)
672 (setq encoding
673 (or (cdr (assq mime-charset
674 rfc2047-charset-encoding-alist))
675 ;; For the charsets that don't have a preferred
676 ;; encoding, choose the one that's shorter.
677 (if (eq (rfc2047-qp-or-base64) 'base64)
678 'B
679 'Q)))
680 (widen)
681 (goto-char e)
682 (skip-chars-forward "^ \t\n")
683 ;; `tail' may contain a close parenthesis.
684 (setq tail (buffer-substring-no-properties e (point)))
685 (goto-char b)
686 (setq b (point-marker)
687 e (set-marker (make-marker) e))
688 (rfc2047-fold-region (point-at-bol) b)
689 (goto-char b)
690 (skip-chars-backward "^ \t\n")
691 (unless (= 0 (skip-chars-backward " \t"))
692 ;; `crest' may contain whitespace and an open parenthesis.
693 (setq crest (buffer-substring-no-properties (point) b)))
694 (setq eword (rfc2047-encode-1
695 (- b (point-at-bol))
696 (replace-regexp-in-string
697 "\n\\([ \t]?\\)" "\\1"
698 (buffer-substring-no-properties b e))
699 cs
700 (or (cdr (assq encoding
701 rfc2047-encode-function-alist))
702 'identity)
703 (concat "=?" (downcase (symbol-name mime-charset))
704 "?" (upcase (symbol-name encoding)) "?")
705 (or crest " ")
706 tail))
707 (delete-region (if (eq (aref eword 0) ?\n)
708 (if (bolp)
709 ;; The line was folded before encoding.
710 (1- (point))
711 (point))
712 (goto-char b))
713 (+ e (length tail)))
714 ;; `eword' contains `crest' and `tail'.
715 (insert eword)
716 (set-marker b nil)
717 (set-marker e nil)
718 (unless (or (/= 0 (length tail))
719 (eobp)
720 (looking-at "[ \t\n)]"))
721 (insert " "))))
722 (t
723 (goto-char e)))))
724
725 (defun rfc2047-fold-field ()
726 "Fold the current header field."
727 (save-excursion
728 (save-restriction
729 (rfc2047-narrow-to-field)
730 (rfc2047-fold-region (point-min) (point-max)))))
731
732 (defun rfc2047-fold-region (b e)
733 "Fold long lines in region B to E."
734 (save-restriction
735 (narrow-to-region b e)
736 (goto-char (point-min))
737 (let ((break nil)
738 (qword-break nil)
739 (first t)
740 (bol (save-restriction
741 (widen)
742 (point-at-bol))))
743 (while (not (eobp))
744 (when (and (or break qword-break)
745 (> (- (point) bol) 76))
746 (goto-char (or break qword-break))
747 (setq break nil
748 qword-break nil)
749 (skip-chars-backward " \t")
750 (if (looking-at "[ \t]")
751 (insert ?\n)
752 (insert "\n "))
753 (setq bol (1- (point)))
754 ;; Don't break before the first non-LWSP characters.
755 (skip-chars-forward " \t")
756 (unless (eobp)
757 (forward-char 1)))
758 (cond
759 ((eq (char-after) ?\n)
760 (forward-char 1)
761 (setq bol (point)
762 break nil
763 qword-break nil)
764 (skip-chars-forward " \t")
765 (unless (or (eobp) (eq (char-after) ?\n))
766 (forward-char 1)))
767 ((eq (char-after) ?\r)
768 (forward-char 1))
769 ((memq (char-after) '(? ?\t))
770 (skip-chars-forward " \t")
771 (unless first ;; Don't break just after the header name.
772 (setq break (point))))
773 ((not break)
774 (if (not (looking-at "=\\?[^=]"))
775 (if (eq (char-after) ?=)
776 (forward-char 1)
777 (skip-chars-forward "^ \t\n\r="))
778 ;; Don't break at the start of the field.
779 (unless (= (point) b)
780 (setq qword-break (point)))
781 (skip-chars-forward "^ \t\n\r")))
782 (t
783 (skip-chars-forward "^ \t\n\r")))
784 (setq first nil))
785 (when (and (or break qword-break)
786 (> (- (point) bol) 76))
787 (goto-char (or break qword-break))
788 (setq break nil
789 qword-break nil)
790 (if (or (> 0 (skip-chars-backward " \t"))
791 (looking-at "[ \t]"))
792 (insert ?\n)
793 (insert "\n "))
794 (setq bol (1- (point)))
795 ;; Don't break before the first non-LWSP characters.
796 (skip-chars-forward " \t")
797 (unless (eobp)
798 (forward-char 1))))))
799
800 (defun rfc2047-unfold-field ()
801 "Fold the current line."
802 (save-excursion
803 (save-restriction
804 (rfc2047-narrow-to-field)
805 (rfc2047-unfold-region (point-min) (point-max)))))
806
807 (defun rfc2047-unfold-region (b e)
808 "Unfold lines in region B to E."
809 (save-restriction
810 (narrow-to-region b e)
811 (goto-char (point-min))
812 (let ((bol (save-restriction
813 (widen)
814 (point-at-bol)))
815 (eol (point-at-eol)))
816 (forward-line 1)
817 (while (not (eobp))
818 (if (and (looking-at "[ \t]")
819 (< (- (point-at-eol) bol) 76))
820 (delete-region eol (progn
821 (goto-char eol)
822 (skip-chars-forward "\r\n")
823 (point)))
824 (setq bol (point-at-bol)))
825 (setq eol (point-at-eol))
826 (forward-line 1)))))
827
828 (defun rfc2047-b-encode-string (string)
829 "Base64-encode the header contained in STRING."
830 (base64-encode-string string t))
831
832 (autoload 'quoted-printable-encode-region "qp")
833
834 (defun rfc2047-q-encode-string (string)
835 "Quoted-printable-encode the header in STRING."
836 (mm-with-unibyte-buffer
837 (insert string)
838 (quoted-printable-encode-region
839 (point-min) (point-max) nil
840 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
841 ;; Avoid using 8bit characters.
842 ;; This list excludes `especials' (see the RFC2047 syntax),
843 ;; meaning that some characters in non-structured fields will
844 ;; get encoded when they con't need to be. The following is
845 ;; what it used to be.
846 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
847 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
848 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
849 (subst-char-in-region (point-min) (point-max) ? ?_)
850 (buffer-string)))
851
852 (defun rfc2047-encode-parameter (param value)
853 "Return and PARAM=VALUE string encoded in the RFC2047-like style.
854 This is a substitution for the `rfc2231-encode-string' function, that
855 is the standard but many mailers don't support it."
856 (let ((rfc2047-encoding-type 'mime)
857 (rfc2047-encode-max-chars nil))
858 (rfc2045-encode-string param (rfc2047-encode-string value t))))
859
860 ;;;
861 ;;; Functions for decoding RFC2047 messages
862 ;;;
863
864 (defvar rfc2047-quote-decoded-words-containing-tspecials nil
865 "If non-nil, quote decoded words containing special characters.")
866
867 (defvar rfc2047-allow-incomplete-encoded-text t
868 "*Non-nil means allow incomplete encoded-text in successive encoded-words.
869 Dividing of encoded-text in the place other than character boundaries
870 violates RFC2047 section 5, while we have a capability to decode it.
871 If it is non-nil, the decoder will decode B- or Q-encoding in each
872 encoded-word, concatenate them, and decode it by charset. Otherwise,
873 the decoder will fully decode each encoded-word before concatenating
874 them.")
875
876 (defun rfc2047-strip-backslashes-in-quoted-strings ()
877 "Strip backslashes in quoted strings. `\\\"' remains."
878 (goto-char (point-min))
879 (let (beg)
880 (with-syntax-table (standard-syntax-table)
881 (while (search-forward "\"" nil t)
882 (unless (eq (char-before) ?\\)
883 (setq beg (match-end 0))
884 (goto-char (match-beginning 0))
885 (condition-case nil
886 (progn
887 (forward-sexp)
888 (save-restriction
889 (narrow-to-region beg (1- (point)))
890 (goto-char beg)
891 (while (search-forward "\\" nil 'move)
892 (unless (memq (char-after) '(?\"))
893 (delete-char -1))
894 (forward-char)))
895 (forward-char))
896 (error
897 (goto-char beg))))))))
898
899 (defun rfc2047-charset-to-coding-system (charset &optional allow-override)
900 "Return coding-system corresponding to MIME CHARSET.
901 If your Emacs implementation can't decode CHARSET, return nil.
902
903 If allow-override is given, use `mm-charset-override-alist' to
904 map undesired charset names to their replacement. This should
905 only be used for decoding, not for encoding."
906 (when (stringp charset)
907 (setq charset (intern (downcase charset))))
908 (when (or (not charset)
909 (eq 'gnus-all mail-parse-ignored-charsets)
910 (memq 'gnus-all mail-parse-ignored-charsets)
911 (memq charset mail-parse-ignored-charsets))
912 (setq charset mail-parse-charset))
913 (let ((cs (mm-charset-to-coding-system charset nil allow-override)))
914 (cond ((eq cs 'ascii)
915 (setq cs (or (mm-charset-to-coding-system mail-parse-charset)
916 'raw-text)))
917 ((mm-coding-system-p cs))
918 ((and charset
919 (listp mail-parse-ignored-charsets)
920 (memq 'gnus-unknown mail-parse-ignored-charsets))
921 (setq cs (mm-charset-to-coding-system mail-parse-charset))))
922 (if (eq cs 'ascii)
923 'raw-text
924 cs)))
925
926 (autoload 'quoted-printable-decode-string "qp")
927
928 (defun rfc2047-decode-encoded-words (words)
929 "Decode successive encoded-words in WORDS and return a decoded string.
930 Each element of WORDS looks like (CHARSET ENCODING ENCODED-TEXT
931 ENCODED-WORD)."
932 (let (word charset cs encoding text rest)
933 (while words
934 (setq word (pop words))
935 (if (and (setq cs (rfc2047-charset-to-coding-system
936 (setq charset (car word)) t))
937 (condition-case code
938 (cond ((char-equal ?B (nth 1 word))
939 (setq text (base64-decode-string
940 (rfc2047-pad-base64 (nth 2 word)))))
941 ((char-equal ?Q (nth 1 word))
942 (setq text (quoted-printable-decode-string
943 (subst-char-in-string
944 ?_ ? (nth 2 word) t)))))
945 (error
946 (message "%s" (error-message-string code))
947 nil)))
948 (if (and rfc2047-allow-incomplete-encoded-text
949 (eq cs (caar rest)))
950 ;; Concatenate text of which the charset is the same.
951 (setcdr (car rest) (concat (cdar rest) text))
952 (push (cons cs text) rest))
953 ;; Don't decode encoded-word.
954 (push (cons nil (nth 3 word)) rest)))
955 (while rest
956 (setq words (concat
957 (or (and (setq cs (caar rest))
958 (condition-case code
959 (decode-coding-string (cdar rest) cs)
960 (error
961 (message "%s" (error-message-string code))
962 nil)))
963 (concat (when (cdr rest) " ")
964 (cdar rest)
965 (when (and words
966 (not (eq (string-to-char words) ? )))
967 " ")))
968 words)
969 rest (cdr rest)))
970 words))
971
972 ;; Fixme: This should decode in place, not cons intermediate strings.
973 ;; Also check whether it needs to worry about delimiting fields like
974 ;; encoding.
975
976 ;; In fact it's reported that (invalid) encoding of mailboxes in
977 ;; addr-specs is in use, so delimiting fields might help. Probably
978 ;; not decoding a word which isn't properly delimited is good enough
979 ;; and worthwhile (is it more correct or not?), e.g. something like
980 ;; `=?iso-8859-1?q?foo?=@'.
981
982 (defun rfc2047-decode-region (start end &optional address-mime)
983 "Decode MIME-encoded words in region between START and END.
984 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
985 other than `\"' and `\\' in quoted strings."
986 (interactive "r")
987 (let ((case-fold-search t)
988 (eword-regexp
989 (if rfc2047-allow-irregular-q-encoded-words
990 (eval-when-compile
991 (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp-loose "\\)"))
992 (eval-when-compile
993 (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp "\\)"))))
994 b e match words)
995 (save-excursion
996 (save-restriction
997 (narrow-to-region start end)
998 (when address-mime
999 (rfc2047-strip-backslashes-in-quoted-strings))
1000 (goto-char (setq b start))
1001 ;; Look for the encoded-words.
1002 (while (setq match (re-search-forward eword-regexp nil t))
1003 (setq e (match-beginning 1)
1004 end (match-end 0)
1005 words nil)
1006 (while match
1007 (push (list (match-string 2) ;; charset
1008 (char-after (match-beginning 3)) ;; encoding
1009 (substring (match-string 3) 2) ;; encoded-text
1010 (match-string 1)) ;; encoded-word
1011 words)
1012 ;; Look for the subsequent encoded-words.
1013 (when (setq match (looking-at eword-regexp))
1014 (goto-char (setq end (match-end 0)))))
1015 ;; Replace the encoded-words with the decoded one.
1016 (delete-region e end)
1017 (insert (rfc2047-decode-encoded-words (nreverse words)))
1018 (save-restriction
1019 (narrow-to-region e (point))
1020 (goto-char e)
1021 ;; Remove newlines between decoded words, though such
1022 ;; things essentially must not be there.
1023 (while (re-search-forward "[\n\r]+" nil t)
1024 (replace-match " "))
1025 (setq end (point-max))
1026 ;; Quote decoded words if there are special characters
1027 ;; which might violate RFC2822.
1028 (when (and rfc2047-quote-decoded-words-containing-tspecials
1029 (let ((regexp (car (rassq
1030 'address-mime
1031 rfc2047-header-encoding-alist))))
1032 (when regexp
1033 (save-restriction
1034 (widen)
1035 (and
1036 ;; Don't quote words if already quoted.
1037 (not (and (eq (char-before e) ?\")
1038 (eq (char-after end) ?\")))
1039 (progn
1040 (beginning-of-line)
1041 (while (and (memq (char-after) '(? ?\t))
1042 (zerop (forward-line -1))))
1043 (looking-at regexp)))))))
1044 (let (quoted)
1045 (goto-char e)
1046 (skip-chars-forward " \t")
1047 (setq start (point))
1048 (setq quoted (eq (char-after) ?\"))
1049 (goto-char (point-max))
1050 (skip-chars-backward " \t" start)
1051 (if (setq quoted (and quoted
1052 (> (point) (1+ start))
1053 (eq (char-before) ?\")))
1054 (progn
1055 (backward-char)
1056 (setq start (1+ start)
1057 end (point-marker)))
1058 (setq end (point-marker)))
1059 (goto-char start)
1060 (while (search-forward "\"" end t)
1061 (when (prog2
1062 (backward-char)
1063 (zerop (% (skip-chars-backward "\\\\") 2))
1064 (goto-char (match-beginning 0)))
1065 (insert "\\"))
1066 (forward-char))
1067 (when (and (not quoted)
1068 (progn
1069 (goto-char start)
1070 (re-search-forward
1071 (concat "[" ietf-drums-tspecials "]")
1072 end t)))
1073 (goto-char start)
1074 (insert "\"")
1075 (goto-char end)
1076 (insert "\""))
1077 (set-marker end nil)))
1078 (goto-char (point-max)))
1079 (when (and (mm-multibyte-p)
1080 mail-parse-charset
1081 (not (eq mail-parse-charset 'us-ascii))
1082 (not (eq mail-parse-charset 'gnus-decoded)))
1083 (decode-coding-region b e mail-parse-charset))
1084 (setq b (point)))
1085 (when (and (mm-multibyte-p)
1086 mail-parse-charset
1087 (not (eq mail-parse-charset 'us-ascii))
1088 (not (eq mail-parse-charset 'gnus-decoded)))
1089 (decode-coding-region b (point-max) mail-parse-charset))))))
1090
1091 (defun rfc2047-decode-address-region (start end)
1092 "Decode MIME-encoded words in region between START and END.
1093 Backslashes which precede characters other than `\"' and `\\' in quoted
1094 strings are stripped."
1095 (rfc2047-decode-region start end t))
1096
1097 (defun rfc2047-decode-string (string &optional address-mime)
1098 "Decode MIME-encoded STRING and return the result.
1099 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
1100 other than `\"' and `\\' in quoted strings."
1101 (if (string-match "=\\?" string)
1102 (with-temp-buffer
1103 ;; We used to only call mm-enable-multibyte if `m' is non-nil,
1104 ;; but this can't be the right criterion. Don't just revert this
1105 ;; change if it encounters a bug. Please help me fix it
1106 ;; right instead. --Stef
1107 ;; The string returned should always be multibyte in a multibyte
1108 ;; session, i.e. the buffer should be multibyte before
1109 ;; `buffer-string' is called.
1110 (mm-enable-multibyte)
1111 (insert string)
1112 (inline
1113 (rfc2047-decode-region (point-min) (point-max) address-mime))
1114 (buffer-string))
1115 (when address-mime
1116 (setq string
1117 (with-temp-buffer
1118 (when (multibyte-string-p string)
1119 (mm-enable-multibyte))
1120 (insert string)
1121 (rfc2047-strip-backslashes-in-quoted-strings)
1122 (buffer-string))))
1123 ;; Fixme: As above, `m' here is inappropriate.
1124 (if (and ;; m
1125 mail-parse-charset
1126 (not (eq mail-parse-charset 'us-ascii))
1127 (not (eq mail-parse-charset 'gnus-decoded)))
1128 ;; `decode-coding-string' in Emacs offers a third optional
1129 ;; arg NOCOPY to avoid consing a new string if the decoding
1130 ;; is "trivial". Unfortunately it currently doesn't
1131 ;; consider anything else than a nil coding system
1132 ;; trivial.
1133 ;; `rfc2047-decode-string' is called multiple times for each
1134 ;; article during summary buffer generation, and we really
1135 ;; want to avoid unnecessary consing. So we bypass
1136 ;; `decode-coding-string' if the string is purely ASCII.
1137 (if (eq (detect-coding-string string t) 'undecided)
1138 ;; string is purely ASCII
1139 string
1140 (decode-coding-string string mail-parse-charset))
1141 (string-to-multibyte string))))
1142
1143 (defun rfc2047-decode-address-string (string)
1144 "Decode MIME-encoded STRING and return the result.
1145 Backslashes which precede characters other than `\"' and `\\' in quoted
1146 strings are stripped."
1147 (rfc2047-decode-string string t))
1148
1149 (defun rfc2047-pad-base64 (string)
1150 "Pad STRING to quartets."
1151 ;; Be more liberal to accept buggy base64 strings. If
1152 ;; base64-decode-string accepts buggy strings, this function could
1153 ;; be aliased to identity.
1154 (if (= 0 (mod (length string) 4))
1155 string
1156 (when (string-match "=+$" string)
1157 (setq string (substring string 0 (match-beginning 0))))
1158 (case (mod (length string) 4)
1159 (0 string)
1160 (1 string) ;; Error, don't pad it.
1161 (2 (concat string "=="))
1162 (3 (concat string "=")))))
1163
1164 (provide 'rfc2047)
1165
1166 ;;; rfc2047.el ends here