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