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