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