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