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