Merge from emacs--devo--0
[gnus] / lisp / mml.el
1 ;;; mml.el --- A package for parsing and validating MML documents
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 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 3, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 ;; For Emacs < 22.2.
29 (eval-and-compile
30   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
31
32 (require 'mm-util)
33 (require 'mm-bodies)
34 (require 'mm-encode)
35 (require 'mm-decode)
36 (require 'mml-sec)
37 (eval-when-compile (require 'cl))
38
39 (eval-and-compile
40   (autoload 'message-make-message-id "message")
41   (autoload 'gnus-setup-posting-charset "gnus-msg")
42   (autoload 'gnus-make-local-hook "gnus-util")
43   (autoload 'message-fetch-field "message")
44   (autoload 'message-mark-active-p "message")
45   (autoload 'message-info "message")
46   (autoload 'fill-flowed-encode "flow-fill")
47   (autoload 'message-posting-charset "message")
48   (autoload 'dnd-get-local-file-name "dnd"))
49
50 (defvar gnus-article-mime-handles)
51 (defvar gnus-mouse-2)
52 (defvar gnus-newsrc-hashtb)
53 (defvar message-default-charset)
54 (defvar message-deletable-headers)
55 (defvar message-options)
56 (defvar message-posting-charset)
57 (defvar message-required-mail-headers)
58 (defvar message-required-news-headers)
59 (defvar dnd-protocol-alist)
60 (defvar mml-dnd-protocol-alist)
61
62 (defcustom mml-content-type-parameters
63   '(name access-type expiration size permission format)
64   "*A list of acceptable parameters in MML tag.
65 These parameters are generated in Content-Type header if exists."
66   :version "22.1"
67   :type '(repeat (symbol :tag "Parameter"))
68   :group 'message)
69
70 (defcustom mml-content-disposition-parameters
71   '(filename creation-date modification-date read-date)
72   "*A list of acceptable parameters in MML tag.
73 These parameters are generated in Content-Disposition header if exists."
74   :version "22.1"
75   :type '(repeat (symbol :tag "Parameter"))
76   :group 'message)
77
78 (defcustom mml-content-disposition-alist
79   '((text (rtf . "attachment") (t . "inline"))
80     (t . "attachment"))
81   "Alist of MIME types or regexps matching file names and default dispositions.
82 Each element should be one of the following three forms:
83
84   (REGEXP . DISPOSITION)
85   (SUPERTYPE (SUBTYPE . DISPOSITION) (SUBTYPE . DISPOSITION)...)
86   (TYPE . DISPOSITION)
87
88 Where REGEXP is a string which matches the file name (if any) of an
89 attachment, SUPERTYPE, SUBTYPE and TYPE should be symbols which are a
90 MIME supertype (e.g., text), a MIME subtype (e.g., plain) and a MIME
91 type (e.g., text/plain) respectively, and DISPOSITION should be either
92 the string \"attachment\" or the string \"inline\".  The value t for
93 SUPERTYPE, SUBTYPE or TYPE matches any of those types.  The first
94 match found will be used."
95   :version "23.0" ;; No Gnus
96   :type (let ((dispositions '(radio :format "DISPOSITION: %v"
97                                     :value "attachment"
98                                     (const :format "%v " "attachment")
99                                     (const :format "%v\n" "inline"))))
100           `(repeat
101             :offset 0
102             (choice :format "%[Value Menu%]%v"
103                     (cons :tag "(REGEXP . DISPOSITION)" :extra-offset 4
104                           (regexp :tag "REGEXP" :value ".*")
105                           ,dispositions)
106                     (cons :tag "(SUPERTYPE (SUBTYPE . DISPOSITION)...)"
107                           :indent 0
108                           (symbol :tag "    SUPERTYPE" :value text)
109                           (repeat :format "%v%i\n" :offset 0 :extra-offset 4
110                                   (cons :format "%v" :extra-offset 5
111                                         (symbol :tag "SUBTYPE" :value t)
112                                         ,dispositions)))
113                     (cons :tag "(TYPE . DISPOSITION)" :extra-offset 4
114                           (symbol :tag "TYPE" :value t)
115                           ,dispositions))))
116   :group 'message)
117
118 (defcustom mml-insert-mime-headers-always nil
119   "If non-nil, always put Content-Type: text/plain at top of empty parts.
120 It is necessary to work against a bug in certain clients."
121   :version "22.1"
122   :type 'boolean
123   :group 'message)
124
125 (defvar mml-tweak-type-alist nil
126   "A list of (TYPE . FUNCTION) for tweaking MML parts.
127 TYPE is a string containing a regexp to match the MIME type.  FUNCTION
128 is a Lisp function which is called with the MML handle to tweak the
129 part.  This variable is used only when no TWEAK parameter exists in
130 the MML handle.")
131
132 (defvar mml-tweak-function-alist nil
133   "A list of (NAME . FUNCTION) for tweaking MML parts.
134 NAME is a string containing the name of the TWEAK parameter in the MML
135 handle.  FUNCTION is a Lisp function which is called with the MML
136 handle to tweak the part.")
137
138 (defvar mml-tweak-sexp-alist
139   '((mml-externalize-attachments . mml-tweak-externalize-attachments))
140   "A list of (SEXP . FUNCTION) for tweaking MML parts.
141 SEXP is an s-expression.  If the evaluation of SEXP is non-nil, FUNCTION
142 is called.  FUNCTION is a Lisp function which is called with the MML
143 handle to tweak the part.")
144
145 (defvar mml-externalize-attachments nil
146   "*If non-nil, local-file attachments are generated as external parts.")
147
148 (defvar mml-generate-multipart-alist nil
149   "*Alist of multipart generation functions.
150 Each entry has the form (NAME . FUNCTION), where
151 NAME is a string containing the name of the part (without the
152 leading \"/multipart/\"),
153 FUNCTION is a Lisp function which is called to generate the part.
154
155 The Lisp function has to supply the appropriate MIME headers and the
156 contents of this part.")
157
158 (defvar mml-syntax-table
159   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
160     (modify-syntax-entry ?\\ "/" table)
161     (modify-syntax-entry ?< "(" table)
162     (modify-syntax-entry ?> ")" table)
163     (modify-syntax-entry ?@ "w" table)
164     (modify-syntax-entry ?/ "w" table)
165     (modify-syntax-entry ?= " " table)
166     (modify-syntax-entry ?* " " table)
167     (modify-syntax-entry ?\; " " table)
168     (modify-syntax-entry ?\' " " table)
169     table))
170
171 (defvar mml-boundary-function 'mml-make-boundary
172   "A function called to suggest a boundary.
173 The function may be called several times, and should try to make a new
174 suggestion each time.  The function is called with one parameter,
175 which is a number that says how many times the function has been
176 called for this message.")
177
178 (defvar mml-confirmation-set nil
179   "A list of symbols, each of which disables some warning.
180 `unknown-encoding': always send messages contain characters with
181 unknown encoding; `use-ascii': always use ASCII for those characters
182 with unknown encoding; `multipart': always send messages with more than
183 one charsets.")
184
185 (defvar mml-generate-default-type "text/plain"
186   "Content type by which the Content-Type header can be omitted.
187 The Content-Type header will not be put in the MIME part if the type
188 equals the value and there's no parameter (e.g. charset, format, etc.)
189 and `mml-insert-mime-headers-always' is nil.  The value will be bound
190 to \"message/rfc822\" when encoding an article to be forwarded as a MIME
191 part.  This is for the internal use, you should never modify the value.")
192
193 (defvar mml-buffer-list nil)
194
195 (defun mml-generate-new-buffer (name)
196   (let ((buf (generate-new-buffer name)))
197     (push buf mml-buffer-list)
198     buf))
199
200 (defun mml-destroy-buffers ()
201   (let (kill-buffer-hook)
202     (mapc 'kill-buffer mml-buffer-list)
203     (setq mml-buffer-list nil)))
204
205 (defun mml-parse ()
206   "Parse the current buffer as an MML document."
207   (save-excursion
208     (goto-char (point-min))
209     (with-syntax-table mml-syntax-table
210       (mml-parse-1))))
211
212 (defun mml-parse-1 ()
213   "Parse the current buffer as an MML document."
214   (let (struct tag point contents charsets warn use-ascii no-markup-p raw)
215     (while (and (not (eobp))
216                 (not (looking-at "<#/multipart")))
217       (cond
218        ((looking-at "<#secure")
219         ;; The secure part is essentially a meta-meta tag, which
220         ;; expands to either a part tag if there are no other parts in
221         ;; the document or a multipart tag if there are other parts
222         ;; included in the message
223         (let* (secure-mode
224                (taginfo (mml-read-tag))
225                (keyfile (cdr (assq 'keyfile taginfo)))
226                (certfile (cdr (assq 'certfile taginfo)))
227                (recipients (cdr (assq 'recipients taginfo)))
228                (sender (cdr (assq 'sender taginfo)))
229                (location (cdr (assq 'tag-location taginfo)))
230                (mode (cdr (assq 'mode taginfo)))
231                (method (cdr (assq 'method taginfo)))
232                tags)
233           (save-excursion
234             (if (re-search-forward
235                  "<#/?\\(multipart\\|part\\|external\\|mml\\)." nil t)
236                 (setq secure-mode "multipart")
237               (setq secure-mode "part")))
238           (save-excursion
239             (goto-char location)
240             (re-search-forward "<#secure[^\n]*>\n"))
241           (delete-region (match-beginning 0) (match-end 0))
242           (cond ((string= mode "sign")
243                  (setq tags (list "sign" method)))
244                 ((string= mode "encrypt")
245                  (setq tags (list "encrypt" method)))
246                 ((string= mode "signencrypt")
247                  (setq tags (list "sign" method "encrypt" method))))
248           (eval `(mml-insert-tag ,secure-mode
249                                  ,@tags
250                                  ,(if keyfile "keyfile")
251                                  ,keyfile
252                                  ,(if certfile "certfile")
253                                  ,certfile
254                                  ,(if recipients "recipients")
255                                  ,recipients
256                                  ,(if sender "sender")
257                                  ,sender))
258           ;; restart the parse
259           (goto-char location)))
260        ((looking-at "<#multipart")
261         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
262        ((looking-at "<#external")
263         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
264               struct))
265        (t
266         (if (or (looking-at "<#part") (looking-at "<#mml"))
267             (setq tag (mml-read-tag)
268                   no-markup-p nil
269                   warn nil)
270           (setq tag (list 'part '(type . "text/plain"))
271                 no-markup-p t
272                 warn t))
273         (setq raw (cdr (assq 'raw tag))
274               point (point)
275               contents (mml-read-part (eq 'mml (car tag)))
276               charsets (cond
277                         (raw nil)
278                         ((assq 'charset tag)
279                          (list
280                           (intern (downcase (cdr (assq 'charset tag))))))
281                         (t
282                          (mm-find-mime-charset-region point (point)
283                                                       mm-hack-charsets))))
284         (when (and (not raw) (memq nil charsets))
285           (if (or (memq 'unknown-encoding mml-confirmation-set)
286                   (message-options-get 'unknown-encoding)
287                   (and (y-or-n-p "\
288 Message contains characters with unknown encoding.  Really send? ")
289                        (message-options-set 'unknown-encoding t)))
290               (if (setq use-ascii
291                         (or (memq 'use-ascii mml-confirmation-set)
292                             (message-options-get 'use-ascii)
293                             (and (y-or-n-p "Use ASCII as charset? ")
294                                  (message-options-set 'use-ascii t))))
295                   (setq charsets (delq nil charsets))
296                 (setq warn nil))
297             (error "Edit your message to remove those characters")))
298         (if (or raw
299                 (eq 'mml (car tag))
300                 (< (length charsets) 2))
301             (if (or (not no-markup-p)
302                     (string-match "[^ \t\r\n]" contents))
303                 ;; Don't create blank parts.
304                 (push (nconc tag (list (cons 'contents contents)))
305                       struct))
306           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
307                           tag point (point) use-ascii)))
308             (when (and warn
309                        (not (memq 'multipart mml-confirmation-set))
310                        (not (message-options-get 'multipart))
311                        (not (and (y-or-n-p (format "\
312 A message part needs to be split into %d charset parts.  Really send? "
313                                                    (length nstruct)))
314                                  (message-options-set 'multipart t))))
315               (error "Edit your message to use only one charset"))
316             (setq struct (nconc nstruct struct)))))))
317     (unless (eobp)
318       (forward-line 1))
319     (nreverse struct)))
320
321 (defun mml-parse-singlepart-with-multiple-charsets
322   (orig-tag beg end &optional use-ascii)
323   (save-excursion
324     (save-restriction
325       (narrow-to-region beg end)
326       (goto-char (point-min))
327       (let ((current (or (mm-mime-charset (mm-charset-after))
328                          (and use-ascii 'us-ascii)))
329             charset struct space newline paragraph)
330         (while (not (eobp))
331           (setq charset (mm-mime-charset (mm-charset-after)))
332           (cond
333            ;; The charset remains the same.
334            ((eq charset 'us-ascii))
335            ((or (and use-ascii (not charset))
336                 (eq charset current))
337             (setq space nil
338                   newline nil
339                   paragraph nil))
340            ;; The initial charset was ascii.
341            ((eq current 'us-ascii)
342             (setq current charset
343                   space nil
344                   newline nil
345                   paragraph nil))
346            ;; We have a change in charsets.
347            (t
348             (push (append
349                    orig-tag
350                    (list (cons 'contents
351                                (buffer-substring-no-properties
352                                 beg (or paragraph newline space (point))))))
353                   struct)
354             (setq beg (or paragraph newline space (point))
355                   current charset
356                   space nil
357                   newline nil
358                   paragraph nil)))
359           ;; Compute places where it might be nice to break the part.
360           (cond
361            ((memq (following-char) '(?  ?\t))
362             (setq space (1+ (point))))
363            ((and (eq (following-char) ?\n)
364                  (not (bobp))
365                  (eq (char-after (1- (point))) ?\n))
366             (setq paragraph (point)))
367            ((eq (following-char) ?\n)
368             (setq newline (1+ (point)))))
369           (forward-char 1))
370         ;; Do the final part.
371         (unless (= beg (point))
372           (push (append orig-tag
373                         (list (cons 'contents
374                                     (buffer-substring-no-properties
375                                      beg (point)))))
376                 struct))
377         struct))))
378
379 (defun mml-read-tag ()
380   "Read a tag and return the contents."
381   (let ((orig-point (point))
382         contents name elem val)
383     (forward-char 2)
384     (setq name (buffer-substring-no-properties
385                 (point) (progn (forward-sexp 1) (point))))
386     (skip-chars-forward " \t\n")
387     (while (not (looking-at ">[ \t]*\n?"))
388       (setq elem (buffer-substring-no-properties
389                   (point) (progn (forward-sexp 1) (point))))
390       (skip-chars-forward "= \t\n")
391       (setq val (buffer-substring-no-properties
392                  (point) (progn (forward-sexp 1) (point))))
393       (when (string-match "^\"\\(.*\\)\"$" val)
394         (setq val (match-string 1 val)))
395       (push (cons (intern elem) val) contents)
396       (skip-chars-forward " \t\n"))
397     (goto-char (match-end 0))
398     ;; Don't skip the leading space.
399     ;;(skip-chars-forward " \t\n")
400     ;; Put the tag location into the returned contents
401     (setq contents (append (list (cons 'tag-location orig-point)) contents))
402     (cons (intern name) (nreverse contents))))
403
404 (defun mml-buffer-substring-no-properties-except-hard-newlines (start end)
405   (let ((str (buffer-substring-no-properties start end))
406         (bufstart start) tmp)
407     (while (setq tmp (text-property-any start end 'hard 't))
408       (set-text-properties (- tmp bufstart) (- tmp bufstart -1)
409                            '(hard t) str)
410       (setq start (1+ tmp)))
411     str))
412
413 (defun mml-read-part (&optional mml)
414   "Return the buffer up till the next part, multipart or closing part or multipart.
415 If MML is non-nil, return the buffer up till the correspondent mml tag."
416   (let ((beg (point)) (count 1))
417     ;; If the tag ended at the end of the line, we go to the next line.
418     (when (looking-at "[ \t]*\n")
419       (forward-line 1))
420     (if mml
421         (progn
422           (while (and (> count 0) (not (eobp)))
423             (if (re-search-forward "<#\\(/\\)?mml." nil t)
424                 (setq count (+ count (if (match-beginning 1) -1 1)))
425               (goto-char (point-max))))
426           (mml-buffer-substring-no-properties-except-hard-newlines
427            beg (if (> count 0)
428                    (point)
429                  (match-beginning 0))))
430       (if (re-search-forward
431            "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
432           (prog1
433               (mml-buffer-substring-no-properties-except-hard-newlines
434                beg (match-beginning 0))
435             (if (or (not (match-beginning 1))
436                     (equal (match-string 2) "multipart"))
437                 (goto-char (match-beginning 0))
438               (when (looking-at "[ \t]*\n")
439                 (forward-line 1))))
440         (mml-buffer-substring-no-properties-except-hard-newlines
441          beg (goto-char (point-max)))))))
442
443 (defvar mml-boundary nil)
444 (defvar mml-base-boundary "-=-=")
445 (defvar mml-multipart-number 0)
446
447 (defun mml-generate-mime ()
448   "Generate a MIME message based on the current MML document."
449   (let ((cont (mml-parse))
450         (mml-multipart-number mml-multipart-number))
451     (if (not cont)
452         nil
453       (mm-with-multibyte-buffer
454         (if (and (consp (car cont))
455                  (= (length cont) 1))
456             (mml-generate-mime-1 (car cont))
457           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
458                                       cont)))
459         (buffer-string)))))
460
461 (defun mml-generate-mime-1 (cont)
462   (let ((mm-use-ultra-safe-encoding
463          (or mm-use-ultra-safe-encoding (assq 'sign cont))))
464     (save-restriction
465       (narrow-to-region (point) (point))
466       (mml-tweak-part cont)
467       (cond
468        ((or (eq (car cont) 'part) (eq (car cont) 'mml))
469         (let* ((raw (cdr (assq 'raw cont)))
470                (filename (cdr (assq 'filename cont)))
471                (type (or (cdr (assq 'type cont))
472                          (if filename
473                              (or (mm-default-file-encoding filename)
474                                  "application/octet-stream")
475                            "text/plain")))
476                (charset (cdr (assq 'charset cont)))
477                (coding (mm-charset-to-coding-system charset))
478                encoding flowed coded)
479           (cond ((eq coding 'ascii)
480                  (setq charset nil
481                        coding nil))
482                 (charset
483                  (setq charset (intern (downcase charset)))))
484           (if (and (not raw)
485                    (member (car (split-string type "/")) '("text" "message")))
486               (progn
487                 (with-temp-buffer
488                   (cond
489                    ((cdr (assq 'buffer cont))
490                     (insert-buffer-substring (cdr (assq 'buffer cont))))
491                    ((and filename
492                          (not (equal (cdr (assq 'nofile cont)) "yes")))
493                     (let ((coding-system-for-read coding))
494                       (mm-insert-file-contents filename)))
495                    ((eq 'mml (car cont))
496                     (insert (cdr (assq 'contents cont))))
497                    (t
498                     (save-restriction
499                       (narrow-to-region (point) (point))
500                       (insert (cdr (assq 'contents cont)))
501                       ;; Remove quotes from quoted tags.
502                       (goto-char (point-min))
503                       (while (re-search-forward
504                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\)"
505                               nil t)
506                         (delete-region (+ (match-beginning 0) 2)
507                                        (+ (match-beginning 0) 3))))))
508                   (cond
509                    ((eq (car cont) 'mml)
510                     (let ((mml-boundary (mml-compute-boundary cont))
511                           ;; It is necessary for the case where this
512                           ;; function is called recursively since
513                           ;; `m-g-d-t' will be bound to "message/rfc822"
514                           ;; when encoding an article to be forwarded.
515                           (mml-generate-default-type "text/plain"))
516                       (mml-to-mime))
517                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
518                       ;; ignore 0x1b, it is part of iso-2022-jp
519                       (setq encoding (mm-body-7-or-8))))
520                    ((string= (car (split-string type "/")) "message")
521                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
522                       ;; ignore 0x1b, it is part of iso-2022-jp
523                       (setq encoding (mm-body-7-or-8))))
524                    (t
525                     ;; Only perform format=flowed filling on text/plain
526                     ;; parts where there either isn't a format parameter
527                     ;; in the mml tag or it says "flowed" and there
528                     ;; actually are hard newlines in the text.
529                     (let (use-hard-newlines)
530                       (when (and (string= type "text/plain")
531                                  (not (string= (cdr (assq 'sign cont)) "pgp"))
532                                  (or (null (assq 'format cont))
533                                      (string= (cdr (assq 'format cont))
534                                               "flowed"))
535                                  (setq use-hard-newlines
536                                        (text-property-any
537                                         (point-min) (point-max) 'hard 't)))
538                         (fill-flowed-encode)
539                         ;; Indicate that `mml-insert-mime-headers' should
540                         ;; insert a "; format=flowed" string unless the
541                         ;; user has already specified it.
542                         (setq flowed (null (assq 'format cont)))))
543                     ;; Prefer `utf-8' for text/calendar parts.
544                     (if (or charset
545                             (not (string= type "text/calendar")))
546                         (setq charset (mm-encode-body charset))
547                       (let ((mm-coding-system-priorities
548                              (cons 'utf-8 mm-coding-system-priorities)))
549                         (setq charset (mm-encode-body))))
550                     (setq encoding (mm-body-encoding
551                                     charset (cdr (assq 'encoding cont))))))
552                   (setq coded (buffer-string)))
553                 (mml-insert-mime-headers cont type charset encoding flowed)
554                 (insert "\n")
555                 (insert coded))
556             (mm-with-unibyte-buffer
557               (cond
558                ((cdr (assq 'buffer cont))
559                 (insert (mm-string-as-unibyte
560                          (with-current-buffer (cdr (assq 'buffer cont))
561                            (buffer-string)))))
562                ((and filename
563                      (not (equal (cdr (assq 'nofile cont)) "yes")))
564                 (let ((coding-system-for-read mm-binary-coding-system))
565                   (mm-insert-file-contents filename nil nil nil nil t))
566                 (unless charset
567                   (setq charset (mm-coding-system-to-mime-charset
568                                  (mm-find-buffer-file-coding-system
569                                   filename)))))
570                (t
571                 (let ((contents (cdr (assq 'contents cont))))
572                   (if (if (featurep 'xemacs)
573                           (string-match "[^\000-\377]" contents)
574                         (mm-multibyte-string-p contents))
575                       (progn
576                         (mm-enable-multibyte)
577                         (insert contents)
578                         (unless raw
579                           (setq charset (mm-encode-body charset))))
580                     (insert contents)))))
581               (setq encoding (mm-encode-buffer type)
582                     coded (mm-string-as-multibyte (buffer-string))))
583             (mml-insert-mime-headers cont type charset encoding nil)
584             (insert "\n" coded))))
585        ((eq (car cont) 'external)
586         (insert "Content-Type: message/external-body")
587         (let ((parameters (mml-parameter-string
588                            cont '(expiration size permission)))
589               (name (cdr (assq 'name cont)))
590               (url (cdr (assq 'url cont))))
591           (when name
592             (setq name (mml-parse-file-name name))
593             (if (stringp name)
594                 (mml-insert-parameter
595                  (mail-header-encode-parameter "name" name)
596                  "access-type=local-file")
597               (mml-insert-parameter
598                (mail-header-encode-parameter
599                 "name" (file-name-nondirectory (nth 2 name)))
600                (mail-header-encode-parameter "site" (nth 1 name))
601                (mail-header-encode-parameter
602                 "directory" (file-name-directory (nth 2 name))))
603               (mml-insert-parameter
604                (concat "access-type="
605                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
606                            "anon-ftp"
607                          "ftp")))))
608           (when url
609             (mml-insert-parameter
610              (mail-header-encode-parameter "url" url)
611              "access-type=url"))
612           (when parameters
613             (mml-insert-parameter-string
614              cont '(expiration size permission)))
615           (insert "\n\n")
616           (insert "Content-Type: "
617                   (or (cdr (assq 'type cont))
618                       (if name
619                           (or (mm-default-file-encoding name)
620                               "application/octet-stream")
621                         "text/plain"))
622                   "\n")
623           (insert "Content-ID: " (message-make-message-id) "\n")
624           (insert "Content-Transfer-Encoding: "
625                   (or (cdr (assq 'encoding cont)) "binary"))
626           (insert "\n\n")
627           (insert (or (cdr (assq 'contents cont))))
628           (insert "\n")))
629        ((eq (car cont) 'multipart)
630         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
631                (mml-generate-default-type (if (equal type "digest")
632                                               "message/rfc822"
633                                             "text/plain"))
634                (handler (assoc type mml-generate-multipart-alist)))
635           (if handler
636               (funcall (cdr handler) cont)
637             ;; No specific handler.  Use default one.
638             (let ((mml-boundary (mml-compute-boundary cont)))
639               (insert (format "Content-Type: multipart/%s; boundary=\"%s\""
640                               type mml-boundary)
641                       (if (cdr (assq 'start cont))
642                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
643                         "\n"))
644               (let ((cont cont) part)
645                 (while (setq part (pop cont))
646                   ;; Skip `multipart' and attributes.
647                   (when (and (consp part) (consp (cdr part)))
648                     (insert "\n--" mml-boundary "\n")
649                     (mml-generate-mime-1 part)
650                     (goto-char (point-max)))))
651               (insert "\n--" mml-boundary "--\n")))))
652        (t
653         (error "Invalid element: %S" cont)))
654       ;; handle sign & encrypt tags in a semi-smart way.
655       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
656             (encrypt-item (assoc (cdr (assq 'encrypt cont))
657                                  mml-encrypt-alist))
658             sender recipients)
659         (when (or sign-item encrypt-item)
660           (when (setq sender (cdr (assq 'sender cont)))
661             (message-options-set 'mml-sender sender)
662             (message-options-set 'message-sender sender))
663           (if (setq recipients (cdr (assq 'recipients cont)))
664               (message-options-set 'message-recipients recipients))
665           (let ((style (mml-signencrypt-style
666                         (first (or sign-item encrypt-item)))))
667             ;; check if: we're both signing & encrypting, both methods
668             ;; are the same (why would they be different?!), and that
669             ;; the signencrypt style allows for combined operation.
670             (if (and sign-item encrypt-item (equal (first sign-item)
671                                                    (first encrypt-item))
672                      (equal style 'combined))
673                 (funcall (nth 1 encrypt-item) cont t)
674               ;; otherwise, revert to the old behavior.
675               (when sign-item
676                 (funcall (nth 1 sign-item) cont))
677               (when encrypt-item
678                 (funcall (nth 1 encrypt-item) cont)))))))))
679
680 (defun mml-compute-boundary (cont)
681   "Return a unique boundary that does not exist in CONT."
682   (let ((mml-boundary (funcall mml-boundary-function
683                                (incf mml-multipart-number))))
684     ;; This function tries again and again until it has found
685     ;; a unique boundary.
686     (while (not (catch 'not-unique
687                   (mml-compute-boundary-1 cont))))
688     mml-boundary))
689
690 (defun mml-compute-boundary-1 (cont)
691   (let (filename)
692     (cond
693      ((eq (car cont) 'part)
694       (with-temp-buffer
695         (cond
696          ((cdr (assq 'buffer cont))
697           (insert-buffer-substring (cdr (assq 'buffer cont))))
698          ((and (setq filename (cdr (assq 'filename cont)))
699                (not (equal (cdr (assq 'nofile cont)) "yes")))
700           (mm-insert-file-contents filename nil nil nil nil t))
701          (t
702           (insert (cdr (assq 'contents cont)))))
703         (goto-char (point-min))
704         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
705                                  nil t)
706           (setq mml-boundary (funcall mml-boundary-function
707                                       (incf mml-multipart-number)))
708           (throw 'not-unique nil))))
709      ((eq (car cont) 'multipart)
710       (mapc 'mml-compute-boundary-1 (cddr cont))))
711     t))
712
713 (defun mml-make-boundary (number)
714   (concat (make-string (% number 60) ?=)
715           (if (> number 17)
716               (format "%x" number)
717             "")
718           mml-base-boundary))
719
720 (defun mml-content-disposition (type &optional filename)
721   "Return a default disposition name suitable to TYPE or FILENAME."
722   (let ((defs mml-content-disposition-alist)
723         disposition def types)
724     (while (and (not disposition) defs)
725       (setq def (pop defs))
726       (cond ((stringp (car def))
727              (when (and filename
728                         (string-match (car def) filename))
729                (setq disposition (cdr def))))
730             ((consp (cdr def))
731              (when (string= (car (setq types (split-string type "/")))
732                             (car def))
733                (setq type (cadr types)
734                      types (cdr def))
735                (while (and (not disposition) types)
736                  (setq def (pop types))
737                  (when (or (eq (car def) t) (string= type (car def)))
738                    (setq disposition (cdr def))))))
739             (t
740              (when (or (eq (car def) t) (string= type (car def)))
741                (setq disposition (cdr def))))))
742     (or disposition "attachment")))
743
744 (defun mml-insert-mime-headers (cont type charset encoding flowed)
745   (let (parameters id disposition description)
746     (setq parameters
747           (mml-parameter-string
748            cont mml-content-type-parameters))
749     (when (or charset
750               parameters
751               flowed
752               (not (equal type mml-generate-default-type))
753               mml-insert-mime-headers-always)
754       (when (consp charset)
755         (error
756          "Can't encode a part with several charsets"))
757       (insert "Content-Type: " type)
758       (when charset
759         (mml-insert-parameter
760          (mail-header-encode-parameter "charset" (symbol-name charset))))
761       (when flowed
762         (mml-insert-parameter "format=flowed"))
763       (when parameters
764         (mml-insert-parameter-string
765          cont mml-content-type-parameters))
766       (insert "\n"))
767     (when (setq id (cdr (assq 'id cont)))
768       (insert "Content-ID: " id "\n"))
769     (setq parameters
770           (mml-parameter-string
771            cont mml-content-disposition-parameters))
772     (when (or (setq disposition (cdr (assq 'disposition cont)))
773               parameters)
774       (insert "Content-Disposition: "
775               (or disposition
776                   (mml-content-disposition type (cdr (assq 'filename cont)))))
777       (when parameters
778         (mml-insert-parameter-string
779          cont mml-content-disposition-parameters))
780       (insert "\n"))
781     (unless (eq encoding '7bit)
782       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
783     (when (setq description (cdr (assq 'description cont)))
784       (insert "Content-Description: ")
785       (setq description (prog1
786                             (point)
787                           (insert description "\n")))
788       (mail-encode-encoded-word-region description (point)))))
789
790 (defun mml-parameter-string (cont types)
791   (let ((string "")
792         value type)
793     (while (setq type (pop types))
794       (when (setq value (cdr (assq type cont)))
795         ;; Strip directory component from the filename parameter.
796         (when (eq type 'filename)
797           (setq value (file-name-nondirectory value)))
798         (setq string (concat string "; "
799                              (mail-header-encode-parameter
800                               (symbol-name type) value)))))
801     (when (not (zerop (length string)))
802       string)))
803
804 (defun mml-insert-parameter-string (cont types)
805   (let (value type)
806     (while (setq type (pop types))
807       (when (setq value (cdr (assq type cont)))
808         ;; Strip directory component from the filename parameter.
809         (when (eq type 'filename)
810           (setq value (file-name-nondirectory value)))
811         (mml-insert-parameter
812          (mail-header-encode-parameter
813           (symbol-name type) value))))))
814
815 (defvar ange-ftp-name-format)
816 (defvar efs-path-regexp)
817
818 (defun mml-parse-file-name (path)
819   (if (if (boundp 'efs-path-regexp)
820           (string-match efs-path-regexp path)
821         (if (boundp 'ange-ftp-name-format)
822             (string-match (car ange-ftp-name-format) path)))
823       (list (match-string 1 path) (match-string 2 path)
824             (substring path (1+ (match-end 2))))
825     path))
826
827 (defun mml-insert-buffer (buffer)
828   "Insert BUFFER at point and quote any MML markup."
829   (save-restriction
830     (narrow-to-region (point) (point))
831     (insert-buffer-substring buffer)
832     (mml-quote-region (point-min) (point-max))
833     (goto-char (point-max))))
834
835 ;;;
836 ;;; Transforming MIME to MML
837 ;;;
838
839 (defun mime-to-mml (&optional handles)
840   "Translate the current buffer (which should be a message) into MML.
841 If HANDLES is non-nil, use it instead reparsing the buffer."
842   ;; First decode the head.
843   (save-restriction
844     (message-narrow-to-head)
845     (let ((rfc2047-quote-decoded-words-containing-tspecials t))
846       (mail-decode-encoded-word-region (point-min) (point-max))))
847   (unless handles
848     (setq handles (mm-dissect-buffer t)))
849   (goto-char (point-min))
850   (search-forward "\n\n" nil t)
851   (delete-region (point) (point-max))
852   (if (stringp (car handles))
853       (mml-insert-mime handles)
854     (mml-insert-mime handles t))
855   (mm-destroy-parts handles)
856   (save-restriction
857     (message-narrow-to-head)
858     ;; Remove them, they are confusing.
859     (message-remove-header "Content-Type")
860     (message-remove-header "MIME-Version")
861     (message-remove-header "Content-Disposition")
862     (message-remove-header "Content-Transfer-Encoding")))
863
864 (defun mml-to-mime ()
865   "Translate the current buffer from MML to MIME."
866   (message-encode-message-body)
867   (save-restriction
868     (message-narrow-to-headers-or-head)
869     ;; Skip past any From_ headers.
870     (while (looking-at "From ")
871       (forward-line 1))
872     (let ((mail-parse-charset message-default-charset))
873       (mail-encode-encoded-word-buffer))))
874
875 (defun mml-insert-mime (handle &optional no-markup)
876   (let (textp buffer mmlp)
877     ;; Determine type and stuff.
878     (unless (stringp (car handle))
879       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
880         (save-excursion
881           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
882           (mm-insert-part handle 'no-cache)
883           (if (setq mmlp (equal (mm-handle-media-type handle)
884                                 "message/rfc822"))
885               (mime-to-mml)))))
886     (if mmlp
887         (mml-insert-mml-markup handle nil t t)
888       (unless (and no-markup
889                    (equal (mm-handle-media-type handle) "text/plain"))
890         (mml-insert-mml-markup handle buffer textp)))
891     (cond
892      (mmlp
893       (insert-buffer-substring buffer)
894       (goto-char (point-max))
895       (insert "<#/mml>\n"))
896      ((stringp (car handle))
897       (mapc 'mml-insert-mime (cdr handle))
898       (insert "<#/multipart>\n"))
899      (textp
900       (let ((charset (mail-content-type-get
901                       (mm-handle-type handle) 'charset))
902             (start (point)))
903         (if (eq charset 'gnus-decoded)
904             (mm-insert-part handle)
905           (insert (mm-decode-string (mm-get-part handle) charset)))
906         (mml-quote-region start (point)))
907       (goto-char (point-max)))
908      (t
909       (insert "<#/part>\n")))))
910
911 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
912   "Take a MIME handle and insert an MML tag."
913   (if (stringp (car handle))
914       (progn
915         (insert "<#multipart type=" (mm-handle-media-subtype handle))
916         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
917           (when start
918             (insert " start=\"" start "\"")))
919         (insert ">\n"))
920     (if mmlp
921         (insert "<#mml type=" (mm-handle-media-type handle))
922       (insert "<#part type=" (mm-handle-media-type handle)))
923     (dolist (elem (append (cdr (mm-handle-type handle))
924                           (cdr (mm-handle-disposition handle))))
925       (unless (symbolp (cdr elem))
926         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
927     (when (mm-handle-id handle)
928       (insert " id=\"" (mm-handle-id handle) "\""))
929     (when (mm-handle-disposition handle)
930       (insert " disposition=" (car (mm-handle-disposition handle))))
931     (when buffer
932       (insert " buffer=\"" (buffer-name buffer) "\""))
933     (when nofile
934       (insert " nofile=yes"))
935     (when (mm-handle-description handle)
936       (insert " description=\"" (mm-handle-description handle) "\""))
937     (insert ">\n")))
938
939 (defun mml-insert-parameter (&rest parameters)
940   "Insert PARAMETERS in a nice way."
941   (let (start end)
942     (dolist (param parameters)
943       (insert ";")
944       (setq start (point))
945       (insert " " param)
946       (setq end (point))
947       (goto-char start)
948       (end-of-line)
949       (if (> (current-column) 76)
950           (progn
951             (goto-char start)
952             (insert "\n")
953             (goto-char (1+ end)))
954         (goto-char end)))))
955
956 ;;;
957 ;;; Mode for inserting and editing MML forms
958 ;;;
959
960 (defvar mml-mode-map
961   (let ((sign (make-sparse-keymap))
962         (encrypt (make-sparse-keymap))
963         (signpart (make-sparse-keymap))
964         (encryptpart (make-sparse-keymap))
965         (map (make-sparse-keymap))
966         (main (make-sparse-keymap)))
967     (define-key map "\C-s" 'mml-secure-message-sign)
968     (define-key map "\C-c" 'mml-secure-message-encrypt)
969     (define-key map "\C-e" 'mml-secure-message-sign-encrypt)
970     (define-key map "\C-p\C-s" 'mml-secure-sign)
971     (define-key map "\C-p\C-c" 'mml-secure-encrypt)
972     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
973     (define-key sign "o" 'mml-secure-message-sign-pgp)
974     (define-key sign "s" 'mml-secure-message-sign-smime)
975     (define-key signpart "p" 'mml-secure-sign-pgpmime)
976     (define-key signpart "o" 'mml-secure-sign-pgp)
977     (define-key signpart "s" 'mml-secure-sign-smime)
978     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
979     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
980     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
981     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
982     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
983     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
984     (define-key map "\C-n" 'mml-unsecure-message)
985     (define-key map "f" 'mml-attach-file)
986     (define-key map "b" 'mml-attach-buffer)
987     (define-key map "e" 'mml-attach-external)
988     (define-key map "q" 'mml-quote-region)
989     (define-key map "m" 'mml-insert-multipart)
990     (define-key map "p" 'mml-insert-part)
991     (define-key map "v" 'mml-validate)
992     (define-key map "P" 'mml-preview)
993     (define-key map "s" sign)
994     (define-key map "S" signpart)
995     (define-key map "c" encrypt)
996     (define-key map "C" encryptpart)
997     ;;(define-key map "n" 'mml-narrow-to-part)
998     ;; `M-m' conflicts with `back-to-indentation'.
999     ;; (define-key main "\M-m" map)
1000     (define-key main "\C-c\C-m" map)
1001     main))
1002
1003 (easy-menu-define
1004   mml-menu mml-mode-map ""
1005   `("Attachments"
1006     ["Attach File..." mml-attach-file
1007      ,@(if (featurep 'xemacs) '(t)
1008          '(:help "Attach a file at point"))]
1009     ["Attach Buffer..." mml-attach-buffer
1010      ,@(if (featurep 'xemacs) '(t)
1011          '(:help "Attach a buffer to the outgoing MIME message"))]
1012     ["Attach External..." mml-attach-external
1013      ,@(if (featurep 'xemacs) '(t)
1014          '(:help "Attach reference to file"))]
1015     ;;
1016     ("Change Security Method"
1017      ["PGP/MIME"
1018       (lambda () (interactive) (setq mml-secure-method "pgpmime"))
1019       ,@(if (featurep 'xemacs) nil
1020           '(:help "Set Security Method to PGP/MIME"))
1021       :style radio
1022       :selected (equal mml-secure-method "pgpmime") ]
1023      ["S/MIME"
1024       (lambda () (interactive) (setq mml-secure-method "smime"))
1025       ,@(if (featurep 'xemacs) nil
1026           '(:help "Set Security Method to S/MIME"))
1027       :style radio
1028       :selected (equal mml-secure-method "smime") ]
1029      ["Inline PGP"
1030       (lambda () (interactive) (setq mml-secure-method "pgp"))
1031       ,@(if (featurep 'xemacs) nil
1032           '(:help "Set Security Method to inline PGP"))
1033       :style radio
1034       :selected (equal mml-secure-method "pgp") ] )
1035     ;;
1036     ["Sign Message" mml-secure-message-sign t]
1037     ["Encrypt Message" mml-secure-message-encrypt t]
1038     ["Sign and Encrypt Message" mml-secure-message-sign-encrypt t]
1039     ["Encrypt/Sign off" mml-unsecure-message
1040      ,@(if (featurep 'xemacs) '(t)
1041          '(:help "Don't Encrypt/Sign Message"))]
1042     ;; Maybe we could remove these, because people who write MML most probably
1043     ;; don't use the menu:
1044     ["Insert Part..." mml-insert-part
1045      :active (message-in-body-p)]
1046     ["Insert Multipart..." mml-insert-multipart
1047      :active (message-in-body-p)]
1048     ;;
1049     ;; Do we have separate encrypt and encrypt/sign commands for parts?
1050     ["Sign Part" mml-secure-sign t]
1051     ["Encrypt Part" mml-secure-encrypt t]
1052     ;;["Narrow" mml-narrow-to-part t]
1053     ["Quote MML in region" mml-quote-region
1054      :active (message-mark-active-p)
1055      ,@(if (featurep 'xemacs) nil
1056          '(:help "Quote MML tags in region"))]
1057     ["Validate MML" mml-validate t]
1058     ["Preview" mml-preview t]
1059     "----"
1060     ["Emacs MIME manual" (lambda () (interactive) (message-info 4))
1061      ,@(if (featurep 'xemacs) '(t)
1062          '(:help "Display the Emacs MIME manual"))]
1063     ["PGG manual" (lambda () (interactive) (message-info 16))
1064      ,@(if (featurep 'xemacs) '(t)
1065          '(:help "Display the PGG manual"))]))
1066
1067 (defvar mml-mode nil
1068   "Minor mode for editing MML.")
1069
1070 (defun mml-mode (&optional arg)
1071   "Minor mode for editing MML.
1072 MML is the MIME Meta Language, a minor mode for composing MIME articles.
1073 See Info node `(emacs-mime)Composing'.
1074
1075 \\{mml-mode-map}"
1076   (interactive "P")
1077   (when (set (make-local-variable 'mml-mode)
1078              (if (null arg) (not mml-mode)
1079                (> (prefix-numeric-value arg) 0)))
1080     (add-minor-mode 'mml-mode " MML" mml-mode-map)
1081     (easy-menu-add mml-menu mml-mode-map)
1082     (when (boundp 'dnd-protocol-alist)
1083       (set (make-local-variable 'dnd-protocol-alist)
1084            (append mml-dnd-protocol-alist dnd-protocol-alist)))
1085     (run-hooks 'mml-mode-hook)))
1086
1087 ;;;
1088 ;;; Helper functions for reading MIME stuff from the minibuffer and
1089 ;;; inserting stuff to the buffer.
1090 ;;;
1091
1092 (defcustom mml-default-directory mm-default-directory
1093   "The default directory where mml will find files.
1094 If not set, `default-directory' will be used."
1095   :type '(choice directory (const :tag "Default" nil))
1096   :version "23.0" ;; No Gnus
1097   :group 'message)
1098
1099 (defun mml-minibuffer-read-file (prompt)
1100   (let* ((completion-ignored-extensions nil)
1101          (file (read-file-name prompt
1102                                (or mml-default-directory default-directory)
1103                                nil t)))
1104     ;; Prevent some common errors.  This is inspired by similar code in
1105     ;; VM.
1106     (when (file-directory-p file)
1107       (error "%s is a directory, cannot attach" file))
1108     (unless (file-exists-p file)
1109       (error "No such file: %s" file))
1110     (unless (file-readable-p file)
1111       (error "Permission denied: %s" file))
1112     file))
1113
1114 (defun mml-minibuffer-read-type (name &optional default)
1115   (mailcap-parse-mimetypes)
1116   (let* ((default (or default
1117                       (mm-default-file-encoding name)
1118                       ;; Perhaps here we should check what the file
1119                       ;; looks like, and offer text/plain if it looks
1120                       ;; like text/plain.
1121                       "application/octet-stream"))
1122          (string (completing-read
1123                   (format "Content type (default %s): " default)
1124                   (mapcar 'list (mailcap-mime-types)))))
1125     (if (not (equal string ""))
1126         string
1127       default)))
1128
1129 (defun mml-minibuffer-read-description ()
1130   (let ((description (read-string "One line description: ")))
1131     (when (string-match "\\`[ \t]*\\'" description)
1132       (setq description nil))
1133     description))
1134
1135 (defun mml-minibuffer-read-disposition (type &optional default filename)
1136   (unless default
1137     (setq default (mml-content-disposition type filename)))
1138   (let ((disposition (completing-read
1139                       (format "Disposition (default %s): " default)
1140                       '(("attachment") ("inline") (""))
1141                       nil t nil nil default)))
1142     (if (not (equal disposition ""))
1143         disposition
1144       default)))
1145
1146 (defun mml-quote-region (beg end)
1147   "Quote the MML tags in the region."
1148   (interactive "r")
1149   (save-excursion
1150     (save-restriction
1151       ;; Temporarily narrow the region to defend from changes
1152       ;; invalidating END.
1153       (narrow-to-region beg end)
1154       (goto-char (point-min))
1155       ;; Quote parts.
1156       (while (re-search-forward
1157               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
1158         ;; Insert ! after the #.
1159         (goto-char (+ (match-beginning 0) 2))
1160         (insert "!")))))
1161
1162 (defun mml-insert-tag (name &rest plist)
1163   "Insert an MML tag described by NAME and PLIST."
1164   (when (symbolp name)
1165     (setq name (symbol-name name)))
1166   (insert "<#" name)
1167   (while plist
1168     (let ((key (pop plist))
1169           (value (pop plist)))
1170       (when value
1171         ;; Quote VALUE if it contains suspicious characters.
1172         (when (string-match "[\"'\\~/*;() \t\n]" value)
1173           (setq value (with-output-to-string
1174                         (let (print-escape-nonascii)
1175                           (prin1 value)))))
1176         (insert (format " %s=%s" key value)))))
1177   (insert ">\n"))
1178
1179 (defun mml-insert-empty-tag (name &rest plist)
1180   "Insert an empty MML tag described by NAME and PLIST."
1181   (when (symbolp name)
1182     (setq name (symbol-name name)))
1183   (apply #'mml-insert-tag name plist)
1184   (insert "<#/" name ">\n"))
1185
1186 ;;; Attachment functions.
1187
1188 (defcustom mml-dnd-protocol-alist
1189   '(("^file:///" . mml-dnd-attach-file)
1190     ("^file://"  . dnd-open-file)
1191     ("^file:"    . mml-dnd-attach-file))
1192   "The functions to call when a drop in `mml-mode' is made.
1193 See `dnd-protocol-alist' for more information.  When nil, behave
1194 as in other buffers."
1195   :type '(choice (repeat (cons (regexp) (function)))
1196                  (const :tag "Behave as in other buffers" nil))
1197   :version "22.1" ;; Gnus 5.10.9
1198   :group 'message)
1199
1200 (defcustom mml-dnd-attach-options nil
1201   "Which options should be queried when attaching a file via drag and drop.
1202
1203 If it is a list, valid members are `type', `description' and
1204 `disposition'.  `disposition' implies `type'.  If it is nil,
1205 don't ask for options.  If it is t, ask the user whether or not
1206 to specify options."
1207   :type '(choice
1208           (const :tag "Non" nil)
1209           (const :tag "Query" t)
1210           (list :value (type description disposition)
1211            (set :inline t
1212                 (const type)
1213                 (const description)
1214                 (const disposition))))
1215   :version "22.1" ;; Gnus 5.10.9
1216   :group 'message)
1217
1218 (defun mml-attach-file (file &optional type description disposition)
1219   "Attach a file to the outgoing MIME message.
1220 The file is not inserted or encoded until you send the message with
1221 `\\[message-send-and-exit]' or `\\[message-send]'.
1222
1223 FILE is the name of the file to attach.  TYPE is its
1224 content-type, a string of the form \"type/subtype\".  DESCRIPTION
1225 is a one-line description of the attachment.  The DISPOSITION
1226 specifies how the attachment is intended to be displayed.  It can
1227 be either \"inline\" (displayed automatically within the message
1228 body) or \"attachment\" (separate from the body)."
1229   (interactive
1230    (let* ((file (mml-minibuffer-read-file "Attach file: "))
1231           (type (mml-minibuffer-read-type file))
1232           (description (mml-minibuffer-read-description))
1233           (disposition (mml-minibuffer-read-disposition type nil file)))
1234      (list file type description disposition)))
1235   (save-excursion
1236     (unless (message-in-body-p) (goto-char (point-max)))
1237     (mml-insert-empty-tag 'part
1238                           'type type
1239                           'filename file
1240                           'disposition (or disposition "attachment")
1241                           'description description)))
1242
1243 (defun mml-dnd-attach-file (uri action)
1244   "Attach a drag and drop file.
1245
1246 Ask for type, description or disposition according to
1247 `mml-dnd-attach-options'."
1248   (let ((file (dnd-get-local-file-name uri t)))
1249     (when (and file (file-regular-p file))
1250       (let ((mml-dnd-attach-options mml-dnd-attach-options)
1251             type description disposition)
1252         (setq mml-dnd-attach-options
1253               (when (and (eq mml-dnd-attach-options t)
1254                          (not
1255                           (y-or-n-p
1256                            "Use default type, disposition and description? ")))
1257                 '(type description disposition)))
1258         (when (or (memq 'type mml-dnd-attach-options)
1259                   (memq 'disposition mml-dnd-attach-options))
1260           (setq type (mml-minibuffer-read-type file)))
1261         (when (memq 'description mml-dnd-attach-options)
1262           (setq description (mml-minibuffer-read-description)))
1263         (when (memq 'disposition mml-dnd-attach-options)
1264           (setq disposition (mml-minibuffer-read-disposition type nil file)))
1265         (mml-attach-file file type description disposition)))))
1266
1267 (defun mml-attach-buffer (buffer &optional type description)
1268   "Attach a buffer to the outgoing MIME message.
1269 See `mml-attach-file' for details of operation."
1270   (interactive
1271    (let* ((buffer (read-buffer "Attach buffer: "))
1272           (type (mml-minibuffer-read-type buffer "text/plain"))
1273           (description (mml-minibuffer-read-description)))
1274      (list buffer type description)))
1275   (save-excursion
1276     (unless (message-in-body-p) (goto-char (point-max)))
1277     (mml-insert-empty-tag 'part 'type type 'buffer buffer
1278                           'disposition "attachment"
1279                           'description description)))
1280
1281 (defun mml-attach-external (file &optional type description)
1282   "Attach an external file into the buffer.
1283 FILE is an ange-ftp/efs specification of the part location.
1284 TYPE is the MIME type to use."
1285   (interactive
1286    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1287           (type (mml-minibuffer-read-type file))
1288           (description (mml-minibuffer-read-description)))
1289      (list file type description)))
1290   (save-excursion
1291     (unless (message-in-body-p) (goto-char (point-max)))
1292     (mml-insert-empty-tag 'external 'type type 'name file
1293                           'disposition "attachment" 'description description)))
1294
1295 (defun mml-insert-multipart (&optional type)
1296   (interactive (list (completing-read "Multipart type (default mixed): "
1297                                       '(("mixed") ("alternative") ("digest") ("parallel")
1298                                         ("signed") ("encrypted"))
1299                                       nil nil "mixed")))
1300   (or type
1301       (setq type "mixed"))
1302   (mml-insert-empty-tag "multipart" 'type type)
1303   (forward-line -1))
1304
1305 (defun mml-insert-part (&optional type)
1306   (interactive
1307    (list (mml-minibuffer-read-type "")))
1308   (mml-insert-tag 'part 'type type 'disposition "inline")
1309   (forward-line -1))
1310
1311 (defun mml-preview-insert-mail-followup-to ()
1312   "Insert a Mail-Followup-To header before previewing an article.
1313 Should be adopted if code in `message-send-mail' is changed."
1314   (when (and (message-mail-p)
1315              (message-subscribed-p)
1316              (not (mail-fetch-field "mail-followup-to"))
1317              (message-make-mail-followup-to))
1318     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1319     (insert (message-make-mail-followup-to))))
1320
1321 (defvar mml-preview-buffer nil)
1322
1323 (autoload 'gnus-make-hashtable "gnus-util")
1324 (autoload 'widget-button-press "wid-edit" nil t)
1325 (declare-function widget-event-point "wid-edit" (event))
1326 ;; If gnus-buffer-configuration is bound this is loaded.
1327 (declare-function gnus-configure-windows "gnus-win" (setting &optional force))
1328
1329 (defun mml-preview (&optional raw)
1330   "Display current buffer with Gnus, in a new buffer.
1331 If RAW, display a raw encoded MIME message.
1332
1333 The window layout for the preview buffer is controled by the variables
1334 `special-display-buffer-names', `special-display-regexps', or
1335 `gnus-buffer-configuration' (the first match made will be used),
1336 or the `pop-to-buffer' function."
1337   (interactive "P")
1338   (setq mml-preview-buffer (generate-new-buffer
1339                             (concat (if raw "*Raw MIME preview of "
1340                                       "*MIME preview of ") (buffer-name))))
1341   (save-excursion
1342     (let* ((buf (current-buffer))
1343            (message-options message-options)
1344            (message-this-is-mail (message-mail-p))
1345            (message-this-is-news (message-news-p))
1346            (message-posting-charset (or (gnus-setup-posting-charset
1347                                          (save-restriction
1348                                            (message-narrow-to-headers-or-head)
1349                                            (message-fetch-field "Newsgroups")))
1350                                         message-posting-charset)))
1351       (message-options-set-recipient)
1352       (when (boundp 'gnus-buffers)
1353         (push mml-preview-buffer gnus-buffers))
1354       (save-restriction
1355         (widen)
1356         (set-buffer mml-preview-buffer)
1357         (erase-buffer)
1358         (insert-buffer-substring buf))
1359       (mml-preview-insert-mail-followup-to)
1360       (let ((message-deletable-headers (if (message-news-p)
1361                                            nil
1362                                          message-deletable-headers)))
1363         (message-generate-headers
1364          (copy-sequence (if (message-news-p)
1365                             message-required-news-headers
1366                           message-required-mail-headers))))
1367       (if (re-search-forward
1368            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1369           (replace-match "\n"))
1370       (let ((mail-header-separator ""));; mail-header-separator is removed.
1371         (message-sort-headers)
1372         (mml-to-mime))
1373       (if raw
1374           (when (fboundp 'set-buffer-multibyte)
1375             (let ((s (buffer-string)))
1376               ;; Insert the content into unibyte buffer.
1377               (erase-buffer)
1378               (mm-disable-multibyte)
1379               (insert s)))
1380         (let ((gnus-newsgroup-charset (car message-posting-charset))
1381               gnus-article-prepare-hook gnus-original-article-buffer)
1382           (run-hooks 'gnus-article-decode-hook)
1383           (let ((gnus-newsgroup-name "dummy")
1384                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1385                                         (gnus-make-hashtable 5))))
1386             (gnus-article-prepare-display))))
1387       ;; Disable article-mode-map.
1388       (use-local-map nil)
1389       (gnus-make-local-hook 'kill-buffer-hook)
1390       (add-hook 'kill-buffer-hook
1391                 (lambda ()
1392                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1393       (setq buffer-read-only t)
1394       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1395       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1396       (local-set-key "\r"
1397                      (lambda ()
1398                        (interactive)
1399                        (widget-button-press (point))))
1400       (local-set-key gnus-mouse-2
1401                      (lambda (event)
1402                        (interactive "@e")
1403                        (widget-button-press (widget-event-point event) event)))
1404       ;; FIXME: Buffer is in article mode, but most tool bar commands won't
1405       ;; work.  Maybe only keep the following icons: search, print, quit
1406       (goto-char (point-min))))
1407   (if (and (not (mm-special-display-p (buffer-name mml-preview-buffer)))
1408            (boundp 'gnus-buffer-configuration)
1409            (assq 'mml-preview gnus-buffer-configuration))
1410       (let ((gnus-message-buffer (current-buffer)))
1411         (gnus-configure-windows 'mml-preview))
1412     (pop-to-buffer mml-preview-buffer)))
1413
1414 (defun mml-validate ()
1415   "Validate the current MML document."
1416   (interactive)
1417   (mml-parse))
1418
1419 (defun mml-tweak-part (cont)
1420   "Tweak a MML part."
1421   (let ((tweak (cdr (assq 'tweak cont)))
1422         func)
1423     (cond
1424      (tweak
1425       (setq func
1426             (or (cdr (assoc tweak mml-tweak-function-alist))
1427                 (intern tweak))))
1428      (mml-tweak-type-alist
1429       (let ((alist mml-tweak-type-alist)
1430             (type (or (cdr (assq 'type cont)) "text/plain")))
1431         (while alist
1432           (if (string-match (caar alist) type)
1433               (setq func (cdar alist)
1434                     alist nil)
1435             (setq alist (cdr alist)))))))
1436     (if func
1437         (funcall func cont)
1438       cont)
1439     (let ((alist mml-tweak-sexp-alist))
1440       (while alist
1441         (if (eval (caar alist))
1442             (funcall (cdar alist) cont))
1443         (setq alist (cdr alist)))))
1444   cont)
1445
1446 (defun mml-tweak-externalize-attachments (cont)
1447   "Tweak attached files as external parts."
1448   (let (filename-cons)
1449     (when (and (eq (car cont) 'part)
1450                (not (cdr (assq 'buffer cont)))
1451                (and (setq filename-cons (assq 'filename cont))
1452                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1453       (setcar cont 'external)
1454       (setcar filename-cons 'name))))
1455
1456 (provide 'mml)
1457
1458 ;;; arch-tag: 583c96cf-1ffe-451b-a5e5-4733ae9ddd12
1459 ;;; mml.el ends here