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