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