a2ddb2272596df5dd76e9baaedc6c3969eb6fc63
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages  -*- coding: iso-latin-1 -*-
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
8 ;;      Keiichi Suzuki   <kei-suzu@mail.wbs.ne.jp>
9 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
10 ;;      Katsumi Yamaoka  <yamaoka@jpl.org>
11 ;;      Kiyokazu SUTO    <suto@merry.xmath.ous.ac.jp>
12 ;; Keywords: mail, news, MIME
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30
31 ;;; Commentary:
32
33 ;; This mode provides mail-sending facilities from within Emacs.  It
34 ;; consists mainly of large chunks of code from the sendmail.el,
35 ;; gnus-msg.el and rnewspost.el files.
36
37 ;;; Code:
38
39 (eval-when-compile
40   (require 'cl)
41   (require 'smtp)
42   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
43 (eval-and-compile
44   (if (boundp 'MULE)
45       (require 'canlock-om)
46     (require 'canlock)))
47 (require 'mailheader)
48 (require 'nnheader)
49 ;; This is apparently necessary even though things are autoloaded:
50 (if (featurep 'xemacs)
51     (require 'mail-abbrevs))
52 (require 'mime-edit)
53 (eval-when-compile (require 'static))
54
55 ;; Avoid byte-compile warnings.
56 (eval-when-compile
57   (require 'mail-parse)
58   (require 'mml))
59
60 (require 'rfc822)
61 (eval-and-compile
62   (autoload 'sha1 "sha1-el")
63   (autoload 'customize-save-variable "cus-edit"));; for Mule 2.
64
65 (defgroup message '((user-mail-address custom-variable)
66                     (user-full-name custom-variable))
67   "Mail and news message composing."
68   :link '(custom-manual "(message)Top")
69   :group 'mail
70   :group 'news)
71
72 (put 'user-mail-address 'custom-type 'string)
73 (put 'user-full-name 'custom-type 'string)
74
75 (defgroup message-various nil
76   "Various Message Variables"
77   :link '(custom-manual "(message)Various Message Variables")
78   :group 'message)
79
80 (defgroup message-buffers nil
81   "Message Buffers"
82   :link '(custom-manual "(message)Message Buffers")
83   :group 'message)
84
85 (defgroup message-sending nil
86   "Message Sending"
87   :link '(custom-manual "(message)Sending Variables")
88   :group 'message)
89
90 (defgroup message-interface nil
91   "Message Interface"
92   :link '(custom-manual "(message)Interface")
93   :group 'message)
94
95 (defgroup message-forwarding nil
96   "Message Forwarding"
97   :link '(custom-manual "(message)Forwarding")
98   :group 'message-interface)
99
100 (defgroup message-insertion nil
101   "Message Insertion"
102   :link '(custom-manual "(message)Insertion")
103   :group 'message)
104
105 (defgroup message-headers nil
106   "Message Headers"
107   :link '(custom-manual "(message)Message Headers")
108   :group 'message)
109
110 (defgroup message-news nil
111   "Composing News Messages"
112   :group 'message)
113
114 (defgroup message-mail nil
115   "Composing Mail Messages"
116   :group 'message)
117
118 (defgroup message-faces nil
119   "Faces used for message composing."
120   :group 'message
121   :group 'faces)
122
123 (defgroup message-frames nil
124   "Message frames"
125   :group 'message)
126
127 (defcustom message-directory "~/Mail/"
128   "*Directory from which all other mail file variables are derived."
129   :group 'message-various
130   :type 'directory)
131
132 (defcustom message-max-buffers 10
133   "*How many buffers to keep before starting to kill them off."
134   :group 'message-buffers
135   :type 'integer)
136
137 (defcustom message-send-rename-function nil
138   "Function called to rename the buffer after sending it."
139   :group 'message-buffers
140   :type '(choice function (const nil)))
141
142 (defcustom message-fcc-handler-function 'message-output
143   "*A function called to save outgoing articles.
144 This function will be called with the name of the file to store the
145 article in.  The default function is `message-output' which saves in Unix
146 mailbox format."
147   :type '(radio (function-item message-output)
148                 (function :tag "Other"))
149   :group 'message-sending)
150
151 (defcustom message-encode-function 'message-maybe-encode
152   "*A function called to encode messages."
153   :group 'message-sending
154   :type 'function)
155
156 (defcustom message-8bit-encoding-list '(8bit binary)
157   "*8bit encoding type in Content-Transfer-Encoding field."
158   :group 'message-sending
159   :type '(repeat (symbol :tag "Type")))
160
161 (defcustom message-courtesy-message
162   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
163   "*This is inserted at the start of a mailed copy of a posted message.
164 If the string contains the format spec \"%s\", the Newsgroups
165 the article has been posted to will be inserted there.
166 If this variable is nil, no such courtesy message will be added."
167   :group 'message-sending
168   :type 'string)
169
170 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
171   "*Regexp that matches headers to be removed in resent bounced mail."
172   :group 'message-interface
173   :type 'regexp)
174
175 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
176   "Function to setup a re-sending bounced message."
177   :group 'message-sending
178   :type 'function)
179
180 ;;;###autoload
181 (defcustom message-from-style 'default
182   "*Specifies how \"From\" headers look.
183
184 If nil, they contain just the return address like:
185         king@grassland.com
186 If `parens', they look like:
187         king@grassland.com (Elvis Parsley)
188 If `angles', they look like:
189         Elvis Parsley <king@grassland.com>
190
191 Otherwise, most addresses look like `angles', but they look like
192 `parens' if `angles' would need quoting and `parens' would not."
193   :type '(choice (const :tag "simple" nil)
194                  (const parens)
195                  (const angles)
196                  (const default))
197   :group 'message-headers)
198
199 (defcustom message-syntax-checks nil
200   ;; Guess this one shouldn't be easy to customize...
201   "*Controls what syntax checks should not be performed on outgoing posts.
202 To disable checking of long signatures, for instance, add
203  `(signature . disabled)' to this list.
204
205 Don't touch this variable unless you really know what you're doing.
206
207 Checks include `subject-cmsg', `multiple-headers', `sendsys',
208 `message-id', `from', `long-lines', `control-chars', `size',
209 `new-text', `quoting-style', `redirected-followup', `signature',
210 `approved', `sender', `empty', `empty-headers', `message-id', `from',
211 `subject', `shorten-followup-to', `existing-newsgroups',
212 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
213   :group 'message-news
214   :type '(repeat sexp))                 ; Fixme: improve this
215
216 (defcustom message-required-news-headers
217   '(From Newsgroups Subject Date Message-ID
218          (optional . Organization) Lines
219          (optional . User-Agent))
220   "*Headers to be generated or prompted for when posting an article.
221 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
222 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
223 User-Agent are optional.  If don't you want message to insert some
224 header, remove it from this list."
225   :group 'message-news
226   :group 'message-headers
227   :type '(repeat sexp))
228
229 (defcustom message-required-mail-headers
230   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
231          (optional . User-Agent))
232   "*Headers to be generated or prompted for when mailing a message.
233 It is recommended that From, Date, To, Subject and Message-ID be
234 included.  Organization, Lines and User-Agent are optional."
235   :group 'message-mail
236   :group 'message-headers
237   :type '(repeat sexp))
238
239 (defcustom message-deletable-headers '(Message-ID Date Lines)
240   "Headers to be deleted if they already exist and were generated by message previously."
241   :group 'message-headers
242   :type 'sexp)
243
244 (defcustom message-ignored-news-headers
245   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:"
246   "*Regexp of headers to be removed unconditionally before posting."
247   :group 'message-news
248   :group 'message-headers
249   :type 'regexp)
250
251 (defcustom message-ignored-mail-headers
252   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:"
253   "*Regexp of headers to be removed unconditionally before mailing."
254   :group 'message-mail
255   :group 'message-headers
256   :type 'regexp)
257
258 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:"
259   "*Header lines matching this regexp will be deleted before posting.
260 It's best to delete old Path and Date headers before posting to avoid
261 any confusion."
262   :group 'message-interface
263   :type 'regexp)
264
265 (defcustom message-supersede-setup-function
266   'message-supersede-setup-for-mime-edit
267   "Function to setup a supersede message."
268   :group 'message-sending
269   :type 'function)
270
271 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
272   "*Regexp matching \"Re: \" in the subject line."
273   :group 'message-various
274   :type 'regexp)
275
276 ;;; Some sender agents encode the whole subject including leading "Re: ".
277 ;;; And if followup agent does not decode it for some reason (e.g. unknown
278 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
279 ;;; result will contain multiple "Re: "'s.
280 (defcustom message-subject-encoded-re-regexp
281   (concat
282    "^[ \t]*"
283    (regexp-quote "=?")
284    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
285    (regexp-quote "?")
286    "\\("
287    "[Bb]" (regexp-quote "?") ; B encoding
288    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
289    "\\("
290    "[Uc][km]U6" ; [Rr][Ee]:
291    "\\|"
292    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
293    "\\|"
294    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
295    "\\)"
296    "\\|"
297    "[Qb]" (regexp-quote "?") ; Q encoding
298    "\\(_\\|=09\\|=20\\)*"
299    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
300    "\\)"
301    )
302   "*Regexp matching \"Re: \" in the subject line.
303 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
304 an encoded-word."
305   :group 'message-various
306   :type 'regexp)
307
308 (defcustom message-use-subject-re t
309   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
310 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
311 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
312   :group 'message-various
313   :type '(choice (const :tag "off" nil)
314                  (const :tag "on" t)
315                  (const guess)))
316
317 ;;;###autoload
318 (defcustom message-signature-separator "^-- *$"
319   "Regexp matching the signature separator."
320   :type 'regexp
321   :group 'message-various)
322
323 (defcustom message-signature-separator-for-insertion "-- \n"
324   "*Signature separator. This value will be inserted as signature separator
325 when composing message. Default value is \"-- \\n\". Notice: Changing this
326 value may go against RFC-1036 and draft-ietf-usefor-article-05.txt. "
327   :type 'string
328   :group 'message-insertion)
329
330 (defcustom message-elide-ellipsis "\n[...]\n\n"
331   "*The string which is inserted for elided text."
332   :type 'string
333   :group 'message-various)
334
335 (defcustom message-interactive nil
336   "Non-nil means when sending a message wait for and display errors.
337 nil means let mailer mail back a message to report errors."
338   :group 'message-sending
339   :group 'message-mail
340   :type 'boolean)
341
342 (defcustom message-generate-new-buffers 'unique
343   "*Non-nil means create a new message buffer whenever `message-setup' is called.
344 If this is a function, call that function with three parameters:  The type,
345 the to address and the group name.  (Any of these may be nil.)  The function
346 should return the new buffer name."
347   :group 'message-buffers
348   :type '(choice (const :tag "off" nil)
349                  (const :tag "unique" unique)
350                  (const :tag "unsent" unsent)
351                  (function fun)))
352
353 (defcustom message-kill-buffer-on-exit nil
354   "*Non-nil means that the message buffer will be killed after sending a message."
355   :group 'message-buffers
356   :type 'boolean)
357
358 (defcustom message-kill-buffer-query-function 'yes-or-no-p
359   "*Function used to prompt user whether to kill the message buffer.  If
360 it is t, the buffer will be killed unconditionally."
361   :type '(radio (function-item yes-or-no-p)
362                 (function-item y-or-n-p)
363                 (function-item nnheader-Y-or-n-p)
364                 (function :tag "Other" t))
365   :group 'message-buffers)
366
367 (defcustom message-kill-buffer-and-remove-file t
368   "*Non-nil means that the associated file will be removed before
369 removing the message buffer.  However, it is treated as nil when the
370 command `message-mimic-kill-buffer' is used."
371   :group 'message-buffers
372   :type 'boolean)
373
374 (eval-when-compile
375   (defvar gnus-local-organization))
376 (defcustom message-user-organization
377   (or (and (boundp 'gnus-local-organization)
378            (stringp gnus-local-organization)
379            gnus-local-organization)
380       (getenv "ORGANIZATION")
381       t)
382   "*String to be used as an Organization header.
383 If t, use `message-user-organization-file'."
384   :group 'message-headers
385   :type '(choice string
386                  (const :tag "consult file" t)))
387
388 ;;;###autoload
389 (defcustom message-user-organization-file "/usr/lib/news/organization"
390   "*Local news organization file."
391   :type 'file
392   :group 'message-headers)
393
394 (defcustom message-forward-start-separator
395   (concat (mime-make-tag "message" "rfc822") "\n")
396   "*Delimiter inserted before forwarded messages."
397   :group 'message-forwarding
398   :type 'string)
399
400 (defcustom message-forward-end-separator
401   (concat (mime-make-tag "text" "plain") "\n")
402   "*Delimiter inserted after forwarded messages."
403   :group 'message-forwarding
404   :type 'string)
405
406 (defcustom message-included-forward-headers
407   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^\\(Mail-\\)?Followup-To:\\|^\\(Mail-\\)?Reply-To:\\|^Mail-Copies-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:\\|^Content-\\|^MIME-Version:"
408   "*Regexp matching headers to be included in forwarded messages."
409   :group 'message-forwarding
410   :type 'regexp)
411
412 (defcustom message-make-forward-subject-function
413   'message-forward-subject-author-subject
414   "*List of functions called to generate subject headers for forwarded messages.
415 The subject generated by the previous function is passed into each
416 successive function.
417
418 The provided functions are:
419
420 * `message-forward-subject-author-subject' (Source of article (author or
421       newsgroup)), in brackets followed by the subject
422 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
423       to it."
424   :group 'message-forwarding
425   :type '(radio (function-item message-forward-subject-author-subject)
426                 (function-item message-forward-subject-fwd)
427                 (repeat :tag "List of functions" function)))
428
429 (defcustom message-forward-as-mime t
430   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
431   :version "21.1"
432   :group 'message-forwarding
433   :type 'boolean)
434
435 (defcustom message-forward-show-mml t
436   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
437   :version "21.1"
438   :group 'message-forwarding
439   :type 'boolean)
440
441 (defcustom message-forward-before-signature t
442   "*If non-nil, put forwarded message before signature, else after."
443   :group 'message-forwarding
444   :type 'boolean)
445
446 (defcustom message-wash-forwarded-subjects nil
447   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
448   :group 'message-forwarding
449   :type 'boolean)
450
451 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
452   "*All headers that match this regexp will be deleted when resending a message."
453   :group 'message-interface
454   :type 'regexp)
455
456 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
457   "*All headers that match this regexp will be deleted when forwarding a message."
458   :version "21.1"
459   :group 'message-forwarding
460   :type '(choice (const :tag "None" nil)
461                  regexp))
462
463 (defcustom message-ignored-cited-headers "."
464   "*Delete these headers from the messages you yank."
465   :group 'message-insertion
466   :type 'regexp)
467
468 (defcustom message-cite-prefix-regexp
469   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
470       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>~|:}+]\\)+"
471     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
472     "\\([ \t]*\\(\\w\\|[-_.]\\)+>+\\|[ \t]*[]>~|:}+]\\)+")
473   "*Regexp matching the longest possible citation prefix on a line."
474   :group 'message-insertion
475   :type 'regexp)
476
477 (defcustom message-cancel-message "I am canceling my own article.\n"
478   "Message to be inserted in the cancel message."
479   :group 'message-interface
480   :type 'string)
481
482 ;; Useful to set in site-init.el
483 ;;;###autoload
484 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
485   "Function to call to send the current buffer as mail.
486 The headers should be delimited by a line whose contents match the
487 variable `mail-header-separator'.
488
489 Valid values include `message-send-mail-with-sendmail' (the default),
490 `message-send-mail-with-mh', `message-send-mail-with-qmail',
491 `message-send-mail-with-smtp', `smtpmail-send-it' and `feedmail-send-it'.
492
493 See also `send-mail-function'."
494   :type '(radio (function-item message-send-mail-with-sendmail)
495                 (function-item message-send-mail-with-mh)
496                 (function-item message-send-mail-with-qmail)
497                 (function-item message-send-mail-with-smtp)
498                 (function-item smtpmail-send-it)
499                 (function-item feedmail-send-it)
500                 (function :tag "Other"))
501   :group 'message-sending
502   :group 'message-mail)
503
504 ;; 1997-09-29 by MORIOKA Tomohiko
505 (defcustom message-send-news-function 'message-send-news-with-gnus
506   "Function to call to send the current buffer as news.
507 The headers should be delimited by a line whose contents match the
508 variable `mail-header-separator'."
509   :group 'message-sending
510   :group 'message-news
511   :type 'function)
512
513 (defcustom message-reply-to-function nil
514   "If non-nil, function that should return a list of headers.
515 This function should pick out addresses from the To, Cc, and From headers
516 and respond with new To and Cc headers."
517   :group 'message-interface
518   :type '(choice function (const nil)))
519
520 (defcustom message-wide-reply-to-function nil
521   "If non-nil, function that should return a list of headers.
522 This function should pick out addresses from the To, Cc, and From headers
523 and respond with new To and Cc headers."
524   :group 'message-interface
525   :type '(choice function (const nil)))
526
527 (defcustom message-followup-to-function nil
528   "If non-nil, function that should return a list of headers.
529 This function should pick out addresses from the To, Cc, and From headers
530 and respond with new To and Cc headers."
531   :group 'message-interface
532   :type '(choice function (const nil)))
533
534 (defcustom message-use-followup-to 'ask
535   "*Specifies what to do with Followup-To header.
536 If nil, always ignore the header.  If it is t, use its value, but
537 query before using the \"poster\" value.  If it is the symbol `ask',
538 always query the user whether to use the value.  If it is the symbol
539 `use', always use the value."
540   :group 'message-interface
541   :type '(choice (const :tag "ignore" nil)
542                  (const :tag "use & query" t)
543                  (const :tag "maybe" t)
544                  (const :tag "always" use)
545                  (const :tag "ask" ask)))
546
547 (defcustom message-use-mail-copies-to 'ask
548   "*Specifies what to do with Mail-Copies-To header.
549 If nil, always ignore the header.  If it is t, use its value, but
550 query before using the value other than \"always\" or \"never\".
551 If it is the symbol `ask', always query the user whether to use
552 the value.  If it is the symbol `use', always use the value."
553   :group 'message-interface
554   :type '(choice (const :tag "ignore" nil)
555                  (const :tag "maybe" t)
556                  (const :tag "always" use)
557                  (const :tag "ask" ask)))
558
559 ;;; XXX: 'ask and 'use are not implemented yet.
560 (defcustom message-use-mail-reply-to 'ask
561   "*Specifies what to do with Mail-Reply-To/Reply-To header.
562 If nil, always ignore the header.  If it is t or the symbol `use', use
563 its value.  If it is the symbol `ask', always query the user whether to
564 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
565 is never used."
566   :group 'message-interface
567   :type '(choice (const :tag "ignore" nil)
568                  (const :tag "maybe" t)
569                  (const :tag "always" use)
570                  (const :tag "ask" ask)))
571
572 (defcustom message-use-mail-followup-to 'use
573   "*Specifies what to do with Mail-Followup-To header.
574 If nil, always ignore the header.  If it is the symbol `ask', always
575 query the user whether to use the value.  If it is t or the symbol
576 `use', always use the value."
577   :group 'message-interface
578   :type '(choice (const :tag "ignore" nil)
579                  (const :tag "maybe" t)
580                  (const :tag "always" use)
581                  (const :tag "ask" ask)))
582
583 (defcustom message-subscribed-address-functions nil
584   "*Specifies functions for determining list subscription.
585 If nil, do not attempt to determine list subscribtion with functions.
586 If non-nil, this variable contains a list of functions which return
587 regular expressions to match lists.  These functions can be used in
588 conjunction with `message-subscribed-regexps' and
589 `message-subscribed-addresses'."
590   :group 'message-interface
591   :type '(repeat sexp))
592
593 (defcustom message-subscribed-address-file nil
594   "*A file containing addresses the user is subscribed to.
595 If nil, do not look at any files to determine list subscriptions.  If
596 non-nil, each line of this file should be a mailing list address."
597   :group 'message-interface
598   :type 'string)
599
600 (defcustom message-subscribed-addresses nil
601   "*Specifies a list of addresses the user is subscribed to.
602 If nil, do not use any predefined list subscriptions.  This list of
603 addresses can be used in conjuction with
604 `message-subscribed-address-functions' and `message-subscribed-regexps'."
605   :group 'message-interface
606   :type '(repeat string))
607
608 (defcustom message-subscribed-regexps nil
609   "*Specifies a list of addresses the user is subscribed to.
610 If nil, do not use any predefined list subscriptions.  This list of
611 regular expressions can be used in conjuction with
612 `message-subscribed-address-functions' and `message-subscribed-addresses'."
613   :group 'message-interface
614   :type '(repeat regexp))
615
616 (defcustom message-allow-no-recipients 'ask
617   "Specifies what to do when there are no recipients other than Gcc/Fcc.
618 If it is the symbol `always', the posting is allowed.  If it is the
619 symbol `never', the posting is not allowed.  If it is the symbol
620 `ask', you are prompted."
621   :group 'message-interface
622   :type '(choice (const always)
623                  (const never)
624                  (const ask)))
625
626 (defcustom message-sendmail-f-is-evil nil
627   "*Non-nil means don't add \"-f username\" to the sendmail command line.
628 Doing so would be even more evil than leaving it out."
629   :group 'message-sending
630   :type 'boolean)
631
632 ;; qmail-related stuff
633 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
634   "Location of the qmail-inject program."
635   :group 'message-sending
636   :type 'file)
637
638 (defcustom message-qmail-inject-args nil
639   "Arguments passed to qmail-inject programs.
640 This should be a list of strings, one string for each argument.
641
642 For e.g., if you wish to set the envelope sender address so that bounces
643 go to the right place or to deal with listserv's usage of that address, you
644 might set this variable to '(\"-f\" \"you@some.where\")."
645   :group 'message-sending
646   :type '(repeat string))
647
648 (defvar message-cater-to-broken-inn t
649   "Non-nil means Gnus should not fold the `References' header.
650 Folding `References' makes ancient versions of INN create incorrect
651 NOV lines.")
652
653 (eval-when-compile
654   (defvar gnus-post-method)
655   (defvar gnus-select-method))
656 (defcustom message-post-method
657   (cond ((and (boundp 'gnus-post-method)
658               (listp gnus-post-method)
659               gnus-post-method)
660          gnus-post-method)
661         ((boundp 'gnus-select-method)
662          gnus-select-method)
663         (t '(nnspool "")))
664   "*Method used to post news.
665 Note that when posting from inside Gnus, for instance, this
666 variable isn't used."
667   :group 'message-news
668   :group 'message-sending
669   ;; This should be the `gnus-select-method' widget, but that might
670   ;; create a dependence to `gnus.el'.
671   :type 'sexp)
672
673 (defcustom message-generate-headers-first nil
674   "*If non-nil, generate all required headers before composing.
675 The variables `message-required-news-headers' and
676 `message-required-mail-headers' specify which headers to generate.
677
678 Note that the variable `message-deletable-headers' specifies headers which
679 are to be deleted and then re-generated before sending, so this variable
680 will not have a visible effect for those headers."
681   :group 'message-headers
682   :type 'boolean)
683
684 (defcustom message-setup-hook '(turn-on-mime-edit)
685   "Normal hook, run each time a new outgoing message is initialized.
686 The function `message-setup' runs this hook."
687   :group 'message-various
688   :type 'hook)
689
690 (defcustom message-cancel-hook nil
691   "Hook run when cancelling articles."
692   :group 'message-various
693   :type 'hook)
694
695 (defcustom message-signature-setup-hook nil
696   "Normal hook, run each time a new outgoing message is initialized.
697 It is run after the headers have been inserted and before
698 the signature is inserted."
699   :group 'message-various
700   :type 'hook)
701
702 (defcustom message-bounce-setup-hook nil
703   "Normal hook, run each time a re-sending bounced message is initialized.
704 The function `message-bounce' runs this hook."
705   :group 'message-various
706   :type 'hook)
707
708 (defcustom message-supersede-setup-hook nil
709   "Normal hook, run each time a supersede message is initialized.
710 The function `message-supersede' runs this hook."
711   :group 'message-various
712   :type 'hook)
713
714 (defcustom message-mode-hook nil
715   "Hook run in message mode buffers."
716   :group 'message-various
717   :type 'hook)
718
719 (defcustom message-header-hook '((lambda () (eword-encode-header t)))
720   "Hook run in a message mode buffer narrowed to the headers."
721   :group 'message-various
722   :type 'hook)
723
724 (defcustom message-header-setup-hook nil
725   "Hook called narrowed to the headers when setting up a message buffer."
726   :group 'message-various
727   :type 'hook)
728
729 (defcustom message-minibuffer-local-map
730   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
731     (set-keymap-parent map minibuffer-local-map)
732     map)
733   "Keymap for `message-read-from-minibuffer'.")
734
735 ;;;###autoload
736 (defcustom message-citation-line-function 'message-insert-citation-line
737   "*Function called to insert the \"Whomever writes:\" line.
738
739 Note that Gnus provides a feature where the reader can click on
740 `writes:' to hide the cited text.  If you change this line too much,
741 people who read your message will have to change their Gnus
742 configuration.  See the variable `gnus-cite-attribution-suffix'."
743   :type 'function
744   :group 'message-insertion)
745
746 ;;;###autoload
747 (defcustom message-yank-prefix "> "
748   "*Prefix inserted on the lines of yanked messages.
749 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
750 See also `message-yank-cited-prefix'."
751   :type 'string
752   :group 'message-insertion)
753
754 (defcustom message-yank-add-new-references t
755   "Non-nil means new IDs will be added to \"References\" field when an
756 article is yanked by the command `message-yank-original' interactively.
757 If it is a symbol `message-id-only', only an ID from \"Message-ID\" field
758 is used, otherwise IDs extracted from \"References\", \"In-Reply-To\" and
759 \"Message-ID\" fields are used."
760   :type '(radio (const :tag "Do not add anything" nil)
761                 (const :tag "From Message-Id, References and In-Reply-To fields" t)
762                 (const :tag "From only Message-Id field." message-id-only))
763   :group 'message-insertion)
764
765 (defcustom message-list-references-add-position nil
766   "Integer value means position for adding to \"References\" field when
767 an article is yanked by the command `message-yank-original' interactively."
768   :type '(radio (const :tag "Add to last" nil)
769                 (integer :tag "Position from last ID"))
770   :group 'message-insertion)
771
772 (defcustom message-yank-cited-prefix ">"
773   "*Prefix inserted on cited or empty lines of yanked messages.
774 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
775 See also `message-yank-prefix'."
776   :type 'string
777   :group 'message-insertion)
778
779 (defcustom message-indentation-spaces 3
780   "*Number of spaces to insert at the beginning of each cited line.
781 Used by `message-yank-original' via `message-yank-cite'."
782   :group 'message-insertion
783   :type 'integer)
784
785 ;;;###autoload
786 (defcustom message-cite-function 'message-cite-original
787   "*Function for citing an original message.
788 Predefined functions include `message-cite-original' and
789 `message-cite-original-without-signature'.
790 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
791   :type '(radio (function-item message-cite-original)
792                 (function-item message-cite-original-without-signature)
793                 (function-item mu-cite-original)
794                 (function-item sc-cite-original)
795                 (function :tag "Other"))
796   :group 'message-insertion)
797
798 ;;;###autoload
799 (defcustom message-suspend-font-lock-when-citing nil
800   "Non-nil means suspend font-lock'ing while citing an original message.
801 Some lazy demand-driven fontification tools (or Emacs itself) have a
802 bug that they often miss a buffer to be fontified.  It will mostly
803 occur when Emacs prompts user for any inputs in the minibuffer.
804 Setting this option to non-nil may help you to avoid unpleasant errors
805 even if it is an add-hoc expedient."
806   :type 'boolean
807   :group 'message-insertion)
808
809 ;;;###autoload
810 (defcustom message-indent-citation-function 'message-indent-citation
811   "*Function for modifying a citation just inserted in the mail buffer.
812 This can also be a list of functions.  Each function can find the
813 citation between (point) and (mark t).  And each function should leave
814 point and mark around the citation text as modified."
815   :type 'function
816   :group 'message-insertion)
817
818 (defvar message-abbrevs-loaded nil)
819
820 ;;;###autoload
821 (defcustom message-signature t
822   "*String to be inserted at the end of the message buffer.
823 If t, the `message-signature-file' file will be inserted instead.
824 If a function, the result from the function will be used instead.
825 If a form, the result from the form will be used instead."
826   :type 'sexp
827   :group 'message-insertion)
828
829 ;;;###autoload
830 (defcustom message-signature-file "~/.signature"
831   "*Name of file containing the text inserted at end of message buffer.
832 Ignored if the named file doesn't exist.
833 If nil, don't insert a signature."
834   :type '(choice file (const :tags "None" nil))
835   :group 'message-insertion)
836
837 (defcustom message-distribution-function nil
838   "*Function called to return a Distribution header."
839   :group 'message-news
840   :group 'message-headers
841   :type '(choice function (const nil)))
842
843 (defcustom message-expires 14
844   "Number of days before your article expires."
845   :group 'message-news
846   :group 'message-headers
847   :link '(custom-manual "(message)News Headers")
848   :type 'integer)
849
850 (defcustom message-user-path nil
851   "If nil, use the NNTP server name in the Path header.
852 If stringp, use this; if non-nil, use no host name (user name only)."
853   :group 'message-news
854   :group 'message-headers
855   :link '(custom-manual "(message)News Headers")
856   :type '(choice (const :tag "nntp" nil)
857                  (string :tag "name")
858                  (sexp :tag "none" :format "%t" t)))
859
860 (defvar message-reply-buffer nil)
861 (defvar message-reply-headers nil)
862 (defvar message-sent-message-via nil)
863 (defvar message-checksum nil)
864 (defvar message-send-actions nil
865   "A list of actions to be performed upon successful sending of a message.")
866 (defvar message-exit-actions nil
867   "A list of actions to be performed upon exiting after sending a message.")
868 (defvar message-kill-actions nil
869   "A list of actions to be performed before killing a message buffer.")
870 (defvar message-postpone-actions nil
871   "A list of actions to be performed after postponing a message.")
872 (defvar message-original-frame nil)
873 (defvar message-parameter-alist nil)
874 (defvar message-startup-parameter-alist nil)
875
876 (define-widget 'message-header-lines 'text
877   "All header lines must be LFD terminated."
878   :format "%{%t%}:%n%v"
879   :valid-regexp "^\\'"
880   :error "All header lines must be newline terminated")
881
882 (defcustom message-default-headers ""
883   "*A string containing header lines to be inserted in outgoing messages.
884 It is inserted before you edit the message, so you can edit or delete
885 these lines."
886   :group 'message-headers
887   :type 'message-header-lines)
888
889 (defcustom message-default-mail-headers ""
890   "*A string of header lines to be inserted in outgoing mails."
891   :group 'message-headers
892   :group 'message-mail
893   :type 'message-header-lines)
894
895 (defcustom message-default-news-headers ""
896   "*A string of header lines to be inserted in outgoing news articles."
897   :group 'message-headers
898   :group 'message-news
899   :type 'message-header-lines)
900
901 ;; Note: could use /usr/ucb/mail instead of sendmail;
902 ;; options -t, and -v if not interactive.
903 (defcustom message-mailer-swallows-blank-line
904   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
905                          system-configuration)
906            (file-readable-p "/etc/sendmail.cf")
907            (let ((buffer (get-buffer-create " *temp*")))
908              (unwind-protect
909                  (save-excursion
910                    (set-buffer buffer)
911                    (insert-file-contents "/etc/sendmail.cf")
912                    (goto-char (point-min))
913                    (let ((case-fold-search nil))
914                      (re-search-forward "^OR\\>" nil t)))
915                (kill-buffer buffer))))
916       ;; According to RFC822, "The field-name must be composed of printable
917       ;; ASCII characters (i. e., characters that have decimal values between
918       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
919       ;; space, or colon.
920       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
921   "*Set this non-nil if the system's mailer runs the header and body together.
922 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
923 The value should be an expression to test whether the problem will
924 actually occur."
925   :group 'message-sending
926   :type 'sexp)
927
928 ;;; XXX: This symbol is overloaded!  See below.
929 (defvar message-user-agent nil
930   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
931
932 (static-when (boundp 'MULE)
933   (require 'reporter));; `define-mail-user-agent' is here.
934
935 ;;;###autoload
936 (define-mail-user-agent 'message-user-agent
937   'message-mail 'message-send-and-exit
938   'message-kill-buffer 'message-send-hook)
939
940 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
941   "If non-nil, delete the deletable headers before feeding to mh.")
942
943 (defvar message-send-method-alist
944   '((news message-news-p message-send-via-news)
945     (mail message-mail-p message-send-via-mail))
946   "Alist of ways to send outgoing messages.
947 Each element has the form
948
949   \(TYPE PREDICATE FUNCTION)
950
951 where TYPE is a symbol that names the method; PREDICATE is a function
952 called without any parameters to determine whether the message is
953 a message of type TYPE; and FUNCTION is a function to be called if
954 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
955 the prefix.")
956
957 (defcustom message-mail-alias-type 'abbrev
958   "*What alias expansion type to use in Message buffers.
959 The default is `abbrev', which uses mailabbrev.  nil switches
960 mail aliases off."
961   :group 'message
962   :link '(custom-manual "(message)Mail Aliases")
963   :type '(choice (const :tag "Use Mailabbrev" abbrev)
964                  (const :tag "No expansion" nil)))
965
966 (defcustom message-auto-save-directory
967   (file-name-as-directory (nnheader-concat message-directory "drafts"))
968   "*Directory where Message auto-saves buffers if Gnus isn't running.
969 If nil, Message won't auto-save."
970   :group 'message-buffers
971   :type '(choice directory (const :tag "Don't auto-save" nil)))
972
973 (defcustom message-buffer-naming-style 'unique
974   "*The way new message buffers are named.
975 Valid valued are `unique' and `unsent'."
976   :version "21.1"
977   :group 'message-buffers
978   :type '(choice (const :tag "unique" unique)
979                  (const :tag "unsent" unsent)))
980
981 (defcustom message-default-charset
982   (and (featurep 'xemacs) (not (featurep 'mule)) 'iso-8859-1)
983   "Default charset used in non-MULE XEmacsen."
984   :version "21.1"
985   :group 'message
986   :type 'symbol)
987
988 (defcustom message-dont-reply-to-names
989   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
990   "*A regexp specifying addresses to prune when doing wide replies.
991 A value of nil means exclude your own user name only."
992   :version "21.1"
993   :group 'message
994   :type '(choice (const :tag "Yourself" nil)
995                  regexp))
996
997 (defvar message-shoot-gnksa-feet nil
998   "*A list of GNKSA feet you are allowed to shoot.
999 Gnus gives you all the opportunity you could possibly want for
1000 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1001 feet of Good Net-Keeping Seal of Approval. The following are foot
1002 candidates:
1003 `empty-article'     Allow you to post an empty article;
1004 `quoted-text-only'  Allow you to post quoted text only;
1005 `multiple-copies'   Allow you to post multiple copies.")
1006 ;; `cancel-messages'   Allow you to cancel or supersede others' messages.
1007
1008 (defsubst message-gnksa-enable-p (feature)
1009   (or (not (listp message-shoot-gnksa-feet))
1010       (memq feature message-shoot-gnksa-feet)))
1011
1012 ;;; Internal variables.
1013 ;;; Well, not really internal.
1014
1015 (defvar message-mode-syntax-table
1016   (let ((table (copy-syntax-table text-mode-syntax-table)))
1017     (modify-syntax-entry ?% ". " table)
1018     (modify-syntax-entry ?> ". " table)
1019     (modify-syntax-entry ?< ". " table)
1020     table)
1021   "Syntax table used while in Message mode.")
1022
1023 (defface message-header-to-face
1024   '((((class color)
1025       (background dark))
1026      (:foreground "green2" :bold t))
1027     (((class color)
1028       (background light))
1029      (:foreground "MidnightBlue" :bold t))
1030     (t
1031      (:bold t :italic t)))
1032   "Face used for displaying From headers."
1033   :group 'message-faces)
1034
1035 (defface message-header-cc-face
1036   '((((class color)
1037       (background dark))
1038      (:foreground "green4" :bold t))
1039     (((class color)
1040       (background light))
1041      (:foreground "MidnightBlue"))
1042     (t
1043      (:bold t)))
1044   "Face used for displaying Cc headers."
1045   :group 'message-faces)
1046
1047 (defface message-header-subject-face
1048   '((((class color)
1049       (background dark))
1050      (:foreground "green3"))
1051     (((class color)
1052       (background light))
1053      (:foreground "navy blue" :bold t))
1054     (t
1055      (:bold t)))
1056   "Face used for displaying subject headers."
1057   :group 'message-faces)
1058
1059 (defface message-header-newsgroups-face
1060   '((((class color)
1061       (background dark))
1062      (:foreground "yellow" :bold t :italic t))
1063     (((class color)
1064       (background light))
1065      (:foreground "blue4" :bold t :italic t))
1066     (t
1067      (:bold t :italic t)))
1068   "Face used for displaying newsgroups headers."
1069   :group 'message-faces)
1070
1071 (defface message-header-other-face
1072   '((((class color)
1073       (background dark))
1074      (:foreground "#b00000"))
1075     (((class color)
1076       (background light))
1077      (:foreground "steel blue"))
1078     (t
1079      (:bold t :italic t)))
1080   "Face used for displaying newsgroups headers."
1081   :group 'message-faces)
1082
1083 (defface message-header-name-face
1084   '((((class color)
1085       (background dark))
1086      (:foreground "DarkGreen"))
1087     (((class color)
1088       (background light))
1089      (:foreground "cornflower blue"))
1090     (t
1091      (:bold t)))
1092   "Face used for displaying header names."
1093   :group 'message-faces)
1094
1095 (defface message-header-xheader-face
1096   '((((class color)
1097       (background dark))
1098      (:foreground "blue"))
1099     (((class color)
1100       (background light))
1101      (:foreground "blue"))
1102     (t
1103      (:bold t)))
1104   "Face used for displaying X-Header headers."
1105   :group 'message-faces)
1106
1107 (defface message-separator-face
1108   '((((class color)
1109       (background dark))
1110      (:foreground "blue3"))
1111     (((class color)
1112       (background light))
1113      (:foreground "brown"))
1114     (t
1115      (:bold t)))
1116   "Face used for displaying the separator."
1117   :group 'message-faces)
1118
1119 (defface message-cited-text-face
1120   '((((class color)
1121       (background dark))
1122      (:foreground "red"))
1123     (((class color)
1124       (background light))
1125      (:foreground "red"))
1126     (t
1127      (:bold t)))
1128   "Face used for displaying cited text names."
1129   :group 'message-faces)
1130
1131 (defface message-mml-face
1132   '((((class color)
1133       (background dark))
1134      (:foreground "ForestGreen"))
1135     (((class color)
1136       (background light))
1137      (:foreground "ForestGreen"))
1138     (t
1139      (:bold t)))
1140   "Face used for displaying MML."
1141   :group 'message-faces)
1142
1143 (defvar message-font-lock-keywords
1144   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1145     `((,(concat "^\\([Tt]o:\\)" content)
1146        (1 'message-header-name-face)
1147        (2 'message-header-to-face nil t))
1148       (,(concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
1149                 "[Mm]ail-[Cc]opies-[Tt]o:\\|"
1150                 "[Mm]ail-[Rr]eply-[Tt]o:\\|"
1151                 "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content)
1152        (1 'message-header-name-face)
1153        (2 'message-header-cc-face nil t))
1154       (,(concat "^\\([Ss]ubject:\\)" content)
1155        (1 'message-header-name-face)
1156        (2 'message-header-subject-face nil t))
1157       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
1158        (1 'message-header-name-face)
1159        (2 'message-header-newsgroups-face nil t))
1160       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
1161        (1 'message-header-name-face)
1162        (2 'message-header-other-face nil t))
1163       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
1164        (1 'message-header-name-face)
1165        (2 'message-header-name-face))
1166       ,@(if (and mail-header-separator
1167                  (not (equal mail-header-separator "")))
1168             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1169                1 'message-separator-face))
1170           nil)
1171       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
1172        (0 'message-cited-text-face))
1173       (,mime-edit-tag-regexp
1174        (0 'message-mml-face))))
1175   "Additional expressions to highlight in Message mode.")
1176
1177 ;; XEmacs does it like this.  For Emacs, we have to set the
1178 ;; `font-lock-defaults' buffer-local variable.
1179 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1180
1181 (defvar message-face-alist
1182   '((bold . bold-region)
1183     (underline . underline-region)
1184     (default . (lambda (b e)
1185                  (unbold-region b e)
1186                  (ununderline-region b e))))
1187   "Alist of mail and news faces for facemenu.
1188 The cdr of ech entry is a function for applying the face to a region.")
1189
1190 (defcustom message-send-hook nil
1191   "Hook run before sending messages."
1192   :group 'message-various
1193   :options '(ispell-message)
1194   :type 'hook)
1195
1196 (defcustom message-send-mail-hook nil
1197   "Hook run before sending mail messages."
1198   :group 'message-various
1199   :type 'hook)
1200
1201 (defcustom message-send-news-hook nil
1202   "Hook run before sending news messages."
1203   :group 'message-various
1204   :type 'hook)
1205
1206 (defcustom message-sent-hook nil
1207   "Hook run after sending messages."
1208   :group 'message-various
1209   :type 'hook)
1210
1211 (defcustom message-use-multi-frames nil
1212   "Make new frame when sending messages."
1213   :group 'message-frames
1214   :type 'boolean)
1215
1216 (defcustom message-delete-frame-on-exit nil
1217   "Delete frame after sending messages."
1218   :group 'message-frames
1219   :type '(choice (const :tag "off" nil)
1220                  (const :tag "always" t)
1221                  (const :tag "ask" ask)))
1222
1223 (defvar message-draft-coding-system
1224   (cond
1225    ((boundp 'MULE) '*junet*)
1226    ((not (fboundp 'find-coding-system)) nil)
1227    ((find-coding-system 'emacs-mule)
1228     (if (memq system-type '(windows-nt ms-dos ms-windows))
1229         'emacs-mule-dos 'emacs-mule))
1230    ((find-coding-system 'escape-quoted) 'escape-quoted)
1231    ((find-coding-system 'no-conversion) 'no-conversion)
1232    (t nil))
1233   "Coding system to compose mail.")
1234
1235 (defcustom message-send-mail-partially-limit 1000000
1236   "The limitation of messages sent as message/partial.
1237 The lower bound of message size in characters, beyond which the message
1238 should be sent in several parts.  If it is nil, the size is unlimited."
1239   :version "21.1"
1240   :group 'message-buffers
1241   :type '(choice (const :tag "unlimited" nil)
1242                  (integer 1000000)))
1243
1244 (defcustom message-alternative-emails nil
1245   "A regexp to match the alternative email addresses.
1246 The first matched address (not primary one) is used in the From field."
1247   :group 'message-headers
1248   :type '(choice (const :tag "Always use primary" nil)
1249                  regexp))
1250
1251 (defcustom message-mail-user-agent nil
1252   "Like `mail-user-agent'.
1253 Except if it is nil, use Gnus native MUA; if it is t, use
1254 `mail-user-agent'."
1255   :type '(radio (const :tag "Gnus native"
1256                        :format "%t\n"
1257                        nil)
1258                 (const :tag "`mail-user-agent'"
1259                        :format "%t\n"
1260                        t)
1261                 (function-item :tag "Default Emacs mail"
1262                                :format "%t\n"
1263                                sendmail-user-agent)
1264                 (function-item :tag "Emacs interface to MH"
1265                                :format "%t\n"
1266                                mh-e-user-agent)
1267                 (function :tag "Other"))
1268   :version "21.1"
1269   :group 'message)
1270
1271 (defcustom message-wide-reply-confirm-recipients nil
1272   "Whether to confirm a wide reply to multiple email recipients.
1273 If this variable is nil, don't ask whether to reply to all recipients.
1274 If this variable is non-nil, pose the question \"Reply to all
1275 recipients?\" before a wide reply to multiple recipients.  If the user
1276 answers yes, reply to all recipients as usual.  If the user answers
1277 no, only reply back to the author."
1278   :group 'message-headers
1279   :type 'boolean)
1280
1281 (defcustom message-insert-canlock t
1282   "Whether to insert a Cancel-Lock header in news postings."
1283   :group 'message-headers
1284   :type 'boolean)
1285
1286 ;;; Internal variables.
1287
1288 (defvar message-sending-message "Sending...")
1289 (defvar message-buffer-list nil)
1290 (defvar message-this-is-news nil)
1291 (defvar message-this-is-mail nil)
1292 (defvar message-draft-article nil)
1293 (defvar message-mime-part nil)
1294 (defvar message-posting-charset nil)
1295
1296 ;; Byte-compiler warning
1297 (eval-when-compile
1298   (defvar gnus-active-hashtb)
1299   (defvar gnus-read-active-file))
1300
1301 ;;; Regexp matching the delimiter of messages in UNIX mail format
1302 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1303 ;;; of rmail.el's rmail-unix-mail-delimiter.
1304 (defvar message-unix-mail-delimiter
1305   (let ((time-zone-regexp
1306          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1307                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1308                  "\\|"
1309                  "\\) *")))
1310     (concat
1311      "From "
1312
1313      ;; Many things can happen to an RFC 822 mailbox before it is put into
1314      ;; a `From' line.  The leading phrase can be stripped, e.g.
1315      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1316      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1317      ;; can be removed, e.g.
1318      ;;         From: joe@y.z (Joe      K
1319      ;;                 User)
1320      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1321      ;;         From: Joe User
1322      ;;                 <joe@y.z>
1323      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1324      ;; The mailbox can be removed or be replaced by white space, e.g.
1325      ;;         From: "Joe User"{space}{tab}
1326      ;;                 <joe@y.z>
1327      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1328      ;; where {space} and {tab} represent the Ascii space and tab characters.
1329      ;; We want to match the results of any of these manglings.
1330      ;; The following regexp rejects names whose first characters are
1331      ;; obviously bogus, but after that anything goes.
1332      "\\([^\0-\b\n-\r\^?].*\\)? "
1333
1334      ;; The time the message was sent.
1335      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1336      "\\([^\0-\r \^?]+\\) +"            ; month
1337      "\\([0-3]?[0-9]\\) +"              ; day of month
1338      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1339
1340      ;; Perhaps a time zone, specified by an abbreviation, or by a
1341      ;; numeric offset.
1342      time-zone-regexp
1343
1344      ;; The year.
1345      " \\([0-9][0-9]+\\) *"
1346
1347      ;; On some systems the time zone can appear after the year, too.
1348      time-zone-regexp
1349
1350      ;; Old uucp cruft.
1351      "\\(remote from .*\\)?"
1352
1353      "\n"))
1354   "Regexp matching the delimiter of messages in UNIX mail format.")
1355
1356 (defvar message-unsent-separator
1357   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1358           "^ *---+ +Returned message +---+ *$\\|"
1359           "^Start of returned message$\\|"
1360           "^ *---+ +Original message +---+ *$\\|"
1361           "^ *--+ +begin message +--+ *$\\|"
1362           "^ *---+ +Original message follows +---+ *$\\|"
1363           "^ *---+ +Undelivered message follows +---+ *$\\|"
1364           "^|? *---+ +Message text follows: +---+ *|?$")
1365   "A regexp that matches the separator before the text of a failed message.")
1366
1367 (defvar message-header-format-alist
1368   `((Newsgroups)
1369     (To . message-fill-address)
1370     (Cc . message-fill-address)
1371     (Subject)
1372     (In-Reply-To)
1373     (Fcc)
1374     (Bcc)
1375     (Date)
1376     (Organization)
1377     (Distribution)
1378     (Lines)
1379     (Expires)
1380     (Message-ID)
1381     (References . message-shorten-references)
1382     (User-Agent))
1383   "Alist used for formatting headers.")
1384
1385 (defvar message-options nil
1386   "Some saved answers when sending message.")
1387
1388 (defvar message-send-mail-real-function nil
1389   "Internal send mail function.")
1390
1391 (defvar message-bogus-system-names "^localhost\\."
1392   "The regexp of bogus system names.")
1393
1394 (eval-and-compile
1395   (autoload 'message-setup-toolbar "messagexmas")
1396   (autoload 'mh-new-draft-name "mh-comp")
1397   (autoload 'mh-send-letter "mh-comp")
1398   (autoload 'gnus-point-at-eol "gnus-util")
1399   (autoload 'gnus-point-at-bol "gnus-util")
1400   (autoload 'gnus-output-to-rmail "gnus-util")
1401   (autoload 'gnus-output-to-mail "gnus-util")
1402   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1403   (autoload 'nndraft-request-associate-buffer "nndraft")
1404   (autoload 'nndraft-request-expire-articles "nndraft")
1405   (autoload 'gnus-open-server "gnus-int")
1406   (autoload 'gnus-request-post "gnus-int")
1407   (autoload 'gnus-copy-article-buffer "gnus-msg")
1408   (autoload 'gnus-alive-p "gnus-util")
1409   (autoload 'gnus-server-string "gnus")
1410   (autoload 'gnus-group-name-charset "gnus-group")
1411   (autoload 'gnus-group-name-decode "gnus-group")
1412   (autoload 'gnus-groups-from-server "gnus")
1413   (autoload 'rmail-output "rmailout")
1414   (autoload 'mu-cite-original "mu-cite"))
1415
1416 \f
1417
1418 ;;;
1419 ;;; Utility functions.
1420 ;;;
1421 (defun message-eval-parameter (parameter)
1422   (condition-case ()
1423       (if (symbolp parameter)
1424           (if (functionp parameter)
1425               (funcall parameter)
1426             (eval parameter))
1427         parameter)
1428     (error nil)))
1429
1430 (defsubst message-get-parameter (key &optional alist)
1431   (unless alist
1432     (setq alist message-parameter-alist))
1433   (cdr (assq key alist)))
1434
1435 (defmacro message-get-parameter-with-eval (key &optional alist)
1436   `(message-eval-parameter (message-get-parameter ,key ,alist)))
1437
1438 (defmacro message-y-or-n-p (question show &rest text)
1439   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1440   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1441
1442 (defmacro message-delete-line (&optional n)
1443   "Delete the current line (and the next N lines)."
1444   `(delete-region (progn (beginning-of-line) (point))
1445                   (progn (forward-line ,(or n 1)) (point))))
1446
1447 (defun message-unquote-tokens (elems)
1448   "Remove double quotes (\") from strings in list ELEMS."
1449   (mapcar (lambda (item)
1450             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1451               (setq item (concat (match-string 1 item)
1452                                  (match-string 2 item))))
1453             item)
1454           elems))
1455
1456 (defun message-tokenize-header (header &optional separator)
1457   "Split HEADER into a list of header elements.
1458 SEPARATOR is a string of characters to be used as separators.  \",\"
1459 is used by default."
1460   (if (not header)
1461       nil
1462     (let ((regexp (format "[%s]+" (or separator ",")))
1463           (beg 1)
1464           (first t)
1465           quoted elems paren)
1466       (save-excursion
1467         (message-set-work-buffer)
1468         (insert header)
1469         (goto-char (point-min))
1470         (while (not (eobp))
1471           (if first
1472               (setq first nil)
1473             (forward-char 1))
1474           (cond ((and (> (point) beg)
1475                       (or (eobp)
1476                           (and (looking-at regexp)
1477                                (not quoted)
1478                                (not paren))))
1479                  (push (buffer-substring beg (point)) elems)
1480                  (setq beg (match-end 0)))
1481                 ((eq (char-after) ?\")
1482                  (setq quoted (not quoted)))
1483                 ((and (eq (char-after) ?\()
1484                       (not quoted))
1485                  (setq paren t))
1486                 ((and (eq (char-after) ?\))
1487                       (not quoted))
1488                  (setq paren nil))))
1489         (nreverse elems)))))
1490
1491 (defun message-mail-file-mbox-p (file)
1492   "Say whether FILE looks like a Unix mbox file."
1493   (when (and (file-exists-p file)
1494              (file-readable-p file)
1495              (file-regular-p file))
1496     (with-temp-buffer
1497       (nnheader-insert-file-contents file)
1498       (goto-char (point-min))
1499       (looking-at message-unix-mail-delimiter))))
1500
1501 (defun message-fetch-field (header &optional not-all)
1502   "The same as `mail-fetch-field', only remove all newlines."
1503   (let* ((inhibit-point-motion-hooks t)
1504          (case-fold-search t)
1505          (value (mail-fetch-field header nil (not not-all))))
1506     (when value
1507       (while (string-match "\n[\t ]+" value)
1508         (setq value (replace-match " " t t value)))
1509       (set-text-properties 0 (length value) nil value)
1510       value)))
1511
1512 (defun message-narrow-to-field ()
1513   "Narrow the buffer to the header on the current line."
1514   (beginning-of-line)
1515   (narrow-to-region
1516    (point)
1517    (progn
1518      (forward-line 1)
1519      (if (re-search-forward "^[^ \n\t]" nil t)
1520          (progn
1521            (beginning-of-line)
1522            (point))
1523        (point-max))))
1524   (goto-char (point-min)))
1525
1526 (defun message-add-header (&rest headers)
1527   "Add the HEADERS to the message header, skipping those already present."
1528   (while headers
1529     (let (hclean)
1530       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1531         (error "Invalid header `%s'" (car headers)))
1532       (setq hclean (match-string 1 (car headers)))
1533       (save-restriction
1534         (message-narrow-to-headers)
1535         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1536           (goto-char (point-max))
1537           (if (string-match "\n$" (car headers))
1538               (insert (car headers))
1539             (insert (car headers) ?\n)))))
1540     (setq headers (cdr headers))))
1541
1542
1543 (defun message-fetch-reply-field (header)
1544   "Fetch field HEADER from the message we're replying to."
1545   (let ((buffer (message-eval-parameter message-reply-buffer)))
1546     (when (and buffer
1547                (buffer-name buffer))
1548       (save-excursion
1549         (set-buffer buffer)
1550         (message-fetch-field header)))))
1551
1552 (defun message-set-work-buffer ()
1553   (if (get-buffer " *message work*")
1554       (progn
1555         (set-buffer " *message work*")
1556         (erase-buffer))
1557     (set-buffer (get-buffer-create " *message work*"))
1558     (kill-all-local-variables)))
1559
1560 (defun message-functionp (form)
1561   "Return non-nil if FORM is funcallable."
1562   (or (and (symbolp form) (fboundp form))
1563       (and (listp form) (eq (car form) 'lambda))
1564       (byte-code-function-p form)))
1565
1566 (defun message-strip-list-identifiers (subject)
1567   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1568   (require 'gnus-sum)                   ; for gnus-list-identifiers
1569   (let ((regexp (if (stringp gnus-list-identifiers)
1570                     gnus-list-identifiers
1571                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1572     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1573                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1574         (concat (substring subject 0 (match-beginning 1))
1575                 (or (match-string 3 subject)
1576                     (match-string 5 subject))
1577                 (substring subject
1578                            (match-end 1)))
1579       subject)))
1580
1581 (defun message-strip-subject-re (subject)
1582   "Remove \"Re:\" from subject lines in string SUBJECT."
1583   (if (string-match message-subject-re-regexp subject)
1584       (substring subject (match-end 0))
1585     subject))
1586
1587 (defun message-remove-header (header &optional is-regexp first reverse)
1588   "Remove HEADER in the narrowed buffer.
1589 If IS-REGEXP, HEADER is a regular expression.
1590 If FIRST, only remove the first instance of the header.
1591 Return the number of headers removed."
1592   (goto-char (point-min))
1593   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1594         (number 0)
1595         (case-fold-search t)
1596         last)
1597     (while (and (not (eobp))
1598                 (not last))
1599       (if (if reverse
1600               (not (looking-at regexp))
1601             (looking-at regexp))
1602           (progn
1603             (incf number)
1604             (when first
1605               (setq last t))
1606             (delete-region
1607              (point)
1608              ;; There might be a continuation header, so we have to search
1609              ;; until we find a new non-continuation line.
1610              (progn
1611                (forward-line 1)
1612                (if (re-search-forward "^[^ \t]" nil t)
1613                    (goto-char (match-beginning 0))
1614                  (point-max)))))
1615         (forward-line 1)
1616         (if (re-search-forward "^[^ \t]" nil t)
1617             (goto-char (match-beginning 0))
1618           (goto-char (point-max)))))
1619     number))
1620
1621 (defun message-remove-first-header (header)
1622   "Remove the first instance of HEADER if there is more than one."
1623   (let ((count 0)
1624         (regexp (concat "^" (regexp-quote header) ":")))
1625     (save-excursion
1626       (goto-char (point-min))
1627       (while (re-search-forward regexp nil t)
1628         (incf count)))
1629     (while (> count 1)
1630       (message-remove-header header nil t)
1631       (decf count))))
1632
1633 (defun message-narrow-to-headers ()
1634   "Narrow the buffer to the head of the message."
1635   (widen)
1636   (narrow-to-region
1637    (goto-char (point-min))
1638    (if (re-search-forward
1639         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1640        (match-beginning 0)
1641      (point-max)))
1642   (goto-char (point-min)))
1643
1644 (defun message-narrow-to-head-1 ()
1645   "Like `message-narrow-to-head'.  Don't widen."
1646   (narrow-to-region
1647    (goto-char (point-min))
1648    (if (search-forward "\n\n" nil 1)
1649        (1- (point))
1650      (point-max)))
1651   (goto-char (point-min)))
1652
1653 (defun message-narrow-to-head ()
1654   "Narrow the buffer to the head of the message.
1655 Point is left at the beginning of the narrowed-to region."
1656   (widen)
1657   (message-narrow-to-head-1))
1658
1659 (defun message-narrow-to-headers-or-head ()
1660   "Narrow the buffer to the head of the message."
1661   (widen)
1662   (narrow-to-region
1663    (goto-char (point-min))
1664    (cond
1665     ((re-search-forward
1666       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1667      (match-beginning 0))
1668     ((search-forward "\n\n" nil t)
1669      (1- (point)))
1670     (t
1671      (point-max))))
1672   (goto-char (point-min)))
1673
1674 (defun message-news-p ()
1675   "Say whether the current buffer contains a news message."
1676   (and (not message-this-is-mail)
1677        (or message-this-is-news
1678            (save-excursion
1679              (save-restriction
1680                (message-narrow-to-headers)
1681                (and (message-fetch-field "newsgroups")
1682                     (not (message-fetch-field "posted-to"))))))))
1683
1684 (defun message-mail-p ()
1685   "Say whether the current buffer contains a mail message."
1686   (and (not message-this-is-news)
1687        (or message-this-is-mail
1688            (save-excursion
1689              (save-restriction
1690                (message-narrow-to-headers)
1691                (or (message-fetch-field "to")
1692                    (message-fetch-field "cc")
1693                    (message-fetch-field "bcc")))))))
1694
1695 (defun message-next-header ()
1696   "Go to the beginning of the next header."
1697   (beginning-of-line)
1698   (or (eobp) (forward-char 1))
1699   (not (if (re-search-forward "^[^ \t]" nil t)
1700            (beginning-of-line)
1701          (goto-char (point-max)))))
1702
1703 (defun message-sort-headers-1 ()
1704   "Sort the buffer as headers using `message-rank' text props."
1705   (goto-char (point-min))
1706   (require 'sort)
1707   (sort-subr
1708    nil 'message-next-header
1709    (lambda ()
1710      (message-next-header)
1711      (unless (bobp)
1712        (forward-char -1)))
1713    (lambda ()
1714      (or (get-text-property (point) 'message-rank)
1715          10000))))
1716
1717 (defun message-sort-headers ()
1718   "Sort the headers of the current message according to `message-header-format-alist'."
1719   (interactive)
1720   (save-excursion
1721     (save-restriction
1722       (let ((max (1+ (length message-header-format-alist)))
1723             rank)
1724         (message-narrow-to-headers)
1725         (while (re-search-forward "^[^ \n]+:" nil t)
1726           (put-text-property
1727            (match-beginning 0) (1+ (match-beginning 0))
1728            'message-rank
1729            (if (setq rank (length (memq (assq (intern (buffer-substring
1730                                                        (match-beginning 0)
1731                                                        (1- (match-end 0))))
1732                                               message-header-format-alist)
1733                                         message-header-format-alist)))
1734                (- max rank)
1735              (1+ max)))))
1736       (message-sort-headers-1))))
1737
1738 \f
1739
1740 ;;;
1741 ;;; Message mode
1742 ;;;
1743
1744 ;;; Set up keymap.
1745
1746 (defvar message-mode-map nil)
1747
1748 (unless message-mode-map
1749   (setq message-mode-map (make-keymap))
1750   (set-keymap-parent message-mode-map text-mode-map)
1751   (define-key message-mode-map "\C-c?" 'describe-mode)
1752
1753   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1754   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1755   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1756   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1757   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1758   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1759   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
1760   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1761   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1762   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1763   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1764   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
1765   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1766   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1767   (define-key message-mode-map "\C-c\C-f\C-i" 'message-insert-or-toggle-importance)
1768   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1769   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1770   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
1771
1772   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1773   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1774
1775   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1776   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1777   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1778   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1779   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1780   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1781   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1782   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1783
1784   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1785   (define-key message-mode-map "\C-c\C-s" 'message-send)
1786   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1787   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1788   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
1789
1790   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1791   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1792   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1793   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1794   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1795
1796   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
1797   (define-key message-mode-map "\t" 'message-tab)
1798   (define-key message-mode-map "\M-;" 'comment-region)
1799
1800   (define-key message-mode-map "\C-x\C-s" 'message-save-drafts)
1801   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
1802
1803 (easy-menu-define
1804  message-mode-menu message-mode-map "Message Menu."
1805  `("Message"
1806    ["Sort Headers" message-sort-headers t]
1807    ["Yank Original" message-yank-original t]
1808    ["Fill Yanked Message" message-fill-yanked-message t]
1809    ["Insert Signature" message-insert-signature t]
1810    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1811    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1812    ["Elide Region" message-elide-region (mark t)]
1813    ["Delete Outside Region" message-delete-not-region (mark t)]
1814    ["Kill To Signature" message-kill-to-signature t]
1815    ["Newline and Reformat" message-newline-and-reformat t]
1816    ["Rename buffer" message-rename-buffer t]
1817    ["Flag as important" message-insert-importance-high
1818     ,@(if (featurep 'xemacs) '(t)
1819         '(:help "Mark this message as important"))]
1820    ["Flag as unimportant" message-insert-importance-low
1821     ,@(if (featurep 'xemacs) '(t)
1822         '(:help "Mark this message as unimportant"))]
1823    ["Spellcheck" ispell-message
1824     ,@(if (featurep 'xemacs) '(t)
1825         '(:help "Spellcheck this message"))]
1826    ["Attach file as MIME" mime-edit-insert-file
1827     ,@(if (featurep 'xemacs) '(t)
1828         '(:help "Attach a file at point"))]
1829    "----"
1830    ["Send Message" message-send-and-exit
1831     ,@(if (featurep 'xemacs) '(t)
1832         '(:help "Send this message"))]
1833    ["Postpone Message" message-dont-send
1834     ,@(if (featurep 'xemacs) '(t)
1835         '(:help "File this draft message and exit"))]
1836    ["Send at Specific Time" gnus-delay-article
1837     ,@(if (featurep 'xemacs) '(t)
1838         '(:help "Ask, then arrange to send message at that time"))]
1839    ["Kill Message" message-kill-buffer
1840     ,@(if (featurep 'xemacs) '(t)
1841         '(:help "Delete this message without sending"))]))
1842
1843 (easy-menu-define
1844  message-mode-field-menu message-mode-map ""
1845  '("Field"
1846    ["Fetch To" message-insert-to t]
1847    ["Fetch Newsgroups" message-insert-newsgroups t]
1848    "----"
1849    ["To" message-goto-to t]
1850    ["Subject" message-goto-subject t]
1851    ["Cc" message-goto-cc t]
1852    ["Reply-To" message-goto-reply-to t]
1853    ["Mail-Reply-To" message-goto-mail-reply-to t]
1854    ["Mail-Followup-To" message-goto-mail-followup-to t]
1855    ["Mail-Copies-To" message-goto-mail-copies-to t]
1856    ["Summary" message-goto-summary t]
1857    ["Keywords" message-goto-keywords t]
1858    ["Newsgroups" message-goto-newsgroups t]
1859    ["Followup-To" message-goto-followup-to t]
1860    ["Mail-Followup-To" message-goto-mail-followup-to t]
1861    ["Distribution" message-goto-distribution t]
1862    ["Body" message-goto-body t]
1863    ["Signature" message-goto-signature t]))
1864
1865 (defvar message-tool-bar-map nil)
1866
1867 (eval-when-compile
1868   (defvar facemenu-add-face-function)
1869   (defvar facemenu-remove-face-function))
1870
1871 ;;; Forbidden properties
1872 ;;
1873 ;; We use `after-change-functions' to keep special text properties
1874 ;; that interfer with the normal function of message mode out of the
1875 ;; buffer.
1876
1877 (defcustom message-strip-special-text-properties t
1878   "Strip special properties from the message buffer.
1879
1880 Emacs has a number of special text properties which can break message
1881 composing in various ways.  If this option is set, message will strip
1882 these properties from the message composition buffer.  However, some
1883 packages requires these properties to be present in order to work.
1884 If you use one of these packages, turn this option off, and hope the
1885 message composition doesn't break too bad."
1886   :group 'message-various
1887   :type 'boolean)
1888
1889 (defconst message-forbidden-properties
1890   ;; No reason this should be clutter up customize.  We make it a
1891   ;; property list (rather than a list of property symbols), to be
1892   ;; directly useful for `remove-text-properties'.
1893   '(field nil read-only nil intangible nil invisible nil
1894           mouse-face nil modification-hooks nil insert-in-front-hooks nil
1895           insert-behind-hooks nil point-entered nil point-left nil)
1896   ;; Other special properties:
1897   ;; category, face, display: probably doesn't do any harm.
1898   ;; fontified: is used by font-lock.
1899   ;; syntax-table, local-map: I dunno.
1900   ;; We need to add XEmacs names to the list.
1901   "Property list of with properties.forbidden in message buffers.
1902 The values of the properties are ignored, only the property names are used.")
1903
1904 (defun message-tamago-not-in-use-p (pos)
1905   "Return t when tamago version 4 is not in use at the cursor position.
1906 Tamago version 4 is a popular input method for writing Japanese text.
1907 It uses the properties `intangible', `invisible', `modification-hooks'
1908 and `read-only' when translating ascii or kana text to kanji text.
1909 These properties are essential to work, so we should never strip them."
1910   (not (and (boundp 'egg-modefull-mode)
1911             (symbol-value 'egg-modefull-mode)
1912             (or (memq (get-text-property pos 'intangible)
1913                       '(its-part-1 its-part-2))
1914                 (get-text-property pos 'egg-end)
1915                 (get-text-property pos 'egg-lang)
1916                 (get-text-property pos 'egg-start)))))
1917
1918 (defun message-strip-forbidden-properties (begin end &optional old-length)
1919   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
1920 This function is intended to be called from `after-change-functions'.
1921 See also `message-forbidden-properties'."
1922   (when (and message-strip-special-text-properties
1923              (message-tamago-not-in-use-p begin))
1924     (remove-text-properties begin end message-forbidden-properties)))
1925
1926 ;;;###autoload
1927 (define-derived-mode message-mode text-mode "Message"
1928   "Major mode for editing mail and news to be sent.
1929 Like Text Mode but with these additional commands:\\<message-mode-map>
1930 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1931 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1932 C-c C-f  move to a header field (and create it if there isn't):
1933          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1934          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1935          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1936          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1937          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1938          C-c C-f C-f  move to Followup-To
1939          C-c C-f C-m  move to Mail-Followup-To
1940          C-c C-f c    move to Mail-Copies-To
1941 C-c C-t  `message-insert-to' (add a To header to a news followup)
1942 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1943 C-c C-b  `message-goto-body' (move to beginning of message text).
1944 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1945 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1946 C-c C-y  `message-yank-original' (insert current message, if any).
1947 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1948 C-c C-e  `message-elide-region' (elide the text between point and mark).
1949 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1950 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1951 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1952 C-c C-p  `message-insert-or-toggle-importance'  (insert or cycle importance)
1953 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1954   (set (make-local-variable 'message-reply-buffer) nil)
1955   (make-local-variable 'message-send-actions)
1956   (make-local-variable 'message-exit-actions)
1957   (make-local-variable 'message-kill-actions)
1958   (make-local-variable 'message-postpone-actions)
1959   (make-local-variable 'message-draft-article)
1960   (setq buffer-offer-save t)
1961   (set (make-local-variable 'facemenu-add-face-function)
1962        (lambda (face end)
1963          (let ((face-fun (cdr (assq face message-face-alist))))
1964            (if face-fun
1965                (funcall face-fun (point) end)
1966              (error "Face %s not configured for %s mode" face mode-name)))
1967          ""))
1968   (set (make-local-variable 'facemenu-remove-face-function) t)
1969   (set (make-local-variable 'message-reply-headers) nil)
1970   (make-local-variable 'message-user-agent)
1971   (make-local-variable 'message-post-method)
1972   (set (make-local-variable 'message-sent-message-via) nil)
1973   (set (make-local-variable 'message-checksum) nil)
1974   (make-local-variable 'message-parameter-alist)
1975   (setq message-parameter-alist
1976         (copy-sequence message-startup-parameter-alist))
1977   (message-setup-fill-variables)
1978   ;; Allow using comment commands to add/remove quoting.
1979   (set (make-local-variable 'comment-start) message-yank-prefix)
1980   (if (featurep 'xemacs)
1981       (message-setup-toolbar)
1982     (set (make-local-variable 'font-lock-defaults)
1983          '(message-font-lock-keywords t))
1984     (if (boundp 'tool-bar-map)
1985         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1986   (easy-menu-add message-mode-menu message-mode-map)
1987   (easy-menu-add message-mode-field-menu message-mode-map)
1988   ;; make-local-hook is harmless though obsolete in Emacs 21.
1989   ;; Emacs 20 and XEmacs need make-local-hook.
1990   (make-local-hook 'after-change-functions)
1991   ;; Mmmm... Forbidden properties...
1992   (add-hook 'after-change-functions 'message-strip-forbidden-properties
1993             nil 'local)
1994   ;; Allow mail alias things.
1995   (when (eq message-mail-alias-type 'abbrev)
1996     (if (fboundp 'mail-abbrevs-setup)
1997         (mail-abbrevs-setup)
1998       (mail-aliases-setup)))
1999   (message-set-auto-save-file-name)
2000   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2001
2002 (defun message-setup-fill-variables ()
2003   "Setup message fill variables."
2004   (set (make-local-variable 'fill-paragraph-function)
2005        'message-fill-paragraph)
2006   (make-local-variable 'paragraph-separate)
2007   (make-local-variable 'paragraph-start)
2008   (make-local-variable 'adaptive-fill-regexp)
2009   (unless (boundp 'adaptive-fill-first-line-regexp)
2010     (setq adaptive-fill-first-line-regexp nil))
2011   (make-local-variable 'adaptive-fill-first-line-regexp)
2012   (let ((quote-prefix-regexp
2013          ;; User should change message-cite-prefix-regexp if
2014          ;; message-yank-prefix is set to an abnormal value.
2015          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2016     (setq paragraph-start
2017           (concat
2018            (regexp-quote mail-header-separator) "$\\|"
2019            "[ \t]*$\\|"                 ; blank lines
2020            "-- $\\|"                    ; signature delimiter
2021            "---+$\\|"                   ; delimiters for forwarded messages
2022            page-delimiter "$\\|"        ; spoiler warnings
2023            ".*wrote:$\\|"               ; attribution lines
2024            quote-prefix-regexp "$"))    ; empty lines in quoted text
2025     (setq paragraph-separate paragraph-start)
2026     (setq adaptive-fill-regexp
2027           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2028     (setq adaptive-fill-first-line-regexp
2029           (concat quote-prefix-regexp "\\|"
2030                   adaptive-fill-first-line-regexp)))
2031   (make-local-variable 'auto-fill-inhibit-regexp)
2032   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2033   (setq auto-fill-inhibit-regexp nil)
2034   (make-local-variable 'normal-auto-fill-function)
2035   (setq normal-auto-fill-function 'message-do-auto-fill)
2036   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2037   ;; In that case, ensure that it uses the right function.  The real
2038   ;; solution would be not to use `define-derived-mode', and run
2039   ;; `text-mode-hook' ourself at the end of the mode.
2040   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2041   (when auto-fill-function
2042     (setq auto-fill-function normal-auto-fill-function)))
2043
2044 \f
2045
2046 ;;;
2047 ;;; Message mode commands
2048 ;;;
2049
2050 ;;; Movement commands
2051
2052 (defun message-goto-to ()
2053   "Move point to the To header."
2054   (interactive)
2055   (message-position-on-field "To"))
2056
2057 (defun message-goto-subject ()
2058   "Move point to the Subject header."
2059   (interactive)
2060   (message-position-on-field "Subject"))
2061
2062 (defun message-goto-cc ()
2063   "Move point to the Cc header."
2064   (interactive)
2065   (message-position-on-field "Cc" "To"))
2066
2067 (defun message-goto-bcc ()
2068   "Move point to the Bcc  header."
2069   (interactive)
2070   (message-position-on-field "Bcc" "Cc" "To"))
2071
2072 (defun message-goto-fcc ()
2073   "Move point to the Fcc header."
2074   (interactive)
2075   (message-position-on-field "Fcc" "To" "Newsgroups"))
2076
2077 (defun message-goto-reply-to ()
2078   "Move point to the Reply-To header."
2079   (interactive)
2080   (message-position-on-field "Reply-To" "Subject"))
2081
2082 (defun message-goto-mail-reply-to ()
2083   "Move point to the Mail-Reply-To header."
2084   (interactive)
2085   (message-position-on-field "Mail-Reply-To" "Subject"))
2086
2087 (defun message-goto-mail-copies-to ()
2088   "Move point to the Mail-Copies-To header.  If the header is newly created,
2089 a string \"never\" is inserted in default."
2090   (interactive)
2091   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2092     (insert "never")
2093     (backward-char 5)))
2094
2095 (defun message-goto-newsgroups ()
2096   "Move point to the Newsgroups header."
2097   (interactive)
2098   (message-position-on-field "Newsgroups"))
2099
2100 (defun message-goto-distribution ()
2101   "Move point to the Distribution header."
2102   (interactive)
2103   (message-position-on-field "Distribution"))
2104
2105 (defun message-goto-followup-to ()
2106   "Move point to the Followup-To header."
2107   (interactive)
2108   (message-position-on-field "Followup-To" "Newsgroups"))
2109
2110 (defun message-goto-mail-followup-to ()
2111   "Move point to the Mail-Followup-To header.  If the header is newly created
2112 and To field contains only one address, the address is inserted in default."
2113   (interactive)
2114   (unless (message-position-on-field "Mail-Followup-To" "Subject")
2115     (let ((start (point))
2116           addresses)
2117       (save-restriction
2118         (message-narrow-to-headers)
2119         (setq addresses (split-string (mail-strip-quoted-names
2120                                        (or (std11-fetch-field "to") ""))
2121                                       "[ \f\t\n\r\v,]+"))
2122         (when (eq 1 (length addresses))
2123           (goto-char start)
2124           (insert (car addresses))
2125           (goto-char start))))))
2126
2127 (defun message-goto-keywords ()
2128   "Move point to the Keywords header."
2129   (interactive)
2130   (message-position-on-field "Keywords" "Subject"))
2131
2132 (defun message-goto-summary ()
2133   "Move point to the Summary header."
2134   (interactive)
2135   (message-position-on-field "Summary" "Subject"))
2136
2137 (defun message-goto-body (&optional interactivep)
2138   "Move point to the beginning of the message body."
2139   (interactive (list t))
2140   (when (and interactivep
2141              (looking-at "[ \t]*\n"))
2142     (expand-abbrev))
2143   (goto-char (point-min))
2144   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2145       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2146
2147 (defun message-goto-eoh ()
2148   "Move point to the end of the headers."
2149   (interactive)
2150   (message-goto-body)
2151   (forward-line -1))
2152
2153 (defun message-goto-signature ()
2154   "Move point to the beginning of the message signature.
2155 If there is no signature in the article, go to the end and
2156 return nil."
2157   (interactive)
2158   (goto-char (point-min))
2159   (if (re-search-forward message-signature-separator nil t)
2160       (forward-line 1)
2161     (goto-char (point-max))
2162     nil))
2163
2164 \f
2165
2166 (defun message-insert-to (&optional force)
2167   "Insert a To header that points to the author of the article being replied to.
2168 If the original author requested not to be sent mail, the function signals
2169 an error.
2170 With the prefix argument FORCE, insert the header anyway."
2171   (interactive "P")
2172   (let ((co (message-fetch-reply-field "mail-copies-to")))
2173     (when (and (null force)
2174                co
2175                (or (equal (downcase co) "never")
2176                    (equal (downcase co) "nobody")))
2177       (error "The user has requested not to have copies sent via mail")))
2178   (when (and (message-position-on-field "To")
2179              (mail-fetch-field "to")
2180              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
2181     (insert ", "))
2182   (insert (or (message-fetch-reply-field "mail-reply-to")
2183               (message-fetch-reply-field "reply-to")
2184               (message-fetch-reply-field "from") "")))
2185
2186 (defun message-widen-reply ()
2187   "Widen the reply to include maximum recipients."
2188   (interactive)
2189   (let ((follow-to
2190          (and message-reply-buffer
2191               (buffer-name message-reply-buffer)
2192               (save-excursion
2193                 (set-buffer message-reply-buffer)
2194                 (message-get-reply-headers t)))))
2195     (save-excursion
2196       (save-restriction
2197         (message-narrow-to-headers)
2198         (dolist (elem follow-to)
2199           (message-remove-header (symbol-name (car elem)))
2200           (goto-char (point-min))
2201           (insert (symbol-name (car elem)) ": "
2202                   (cdr elem) "\n"))))))
2203
2204 (defun message-insert-newsgroups ()
2205   "Insert the Newsgroups header from the article being replied to."
2206   (interactive)
2207   (when (and (message-position-on-field "Newsgroups")
2208              (mail-fetch-field "newsgroups")
2209              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2210     (insert ","))
2211   (insert (or (message-fetch-reply-field "newsgroups") "")))
2212
2213 \f
2214
2215 ;;; Various commands
2216
2217 (defun message-delete-not-region (beg end)
2218   "Delete everything in the body of the current message outside of the region."
2219   (interactive "r")
2220   (let (citeprefix)
2221     (save-excursion
2222       (goto-char beg)
2223       ;; snarf citation prefix, if appropriate
2224       (unless (eq (point) (progn (beginning-of-line) (point)))
2225         (when (looking-at message-cite-prefix-regexp)
2226           (setq citeprefix (match-string 0))))
2227       (goto-char end)
2228       (delete-region (point) (if (not (message-goto-signature))
2229                                  (point)
2230                                (forward-line -2)
2231                                (point)))
2232       (insert "\n")
2233       (goto-char beg)
2234       (delete-region beg (progn (message-goto-body)
2235                                 (forward-line 2)
2236                                 (point)))
2237       (when citeprefix
2238         (insert citeprefix))))
2239   (when (message-goto-signature)
2240     (forward-line -2)))
2241
2242 (defun message-kill-to-signature ()
2243   "Deletes all text up to the signature."
2244   (interactive)
2245   (let ((point (point)))
2246     (message-goto-signature)
2247     (unless (eobp)
2248       (forward-line -2))
2249     (kill-region point (point))
2250     (unless (bolp)
2251       (insert "\n"))))
2252
2253 (defun message-newline-and-reformat (&optional arg not-break)
2254   "Insert four newlines, and then reformat if inside quoted text.
2255 Prefix arg means justify as well."
2256   (interactive (list (if current-prefix-arg 'full)))
2257   (let (quoted point beg end leading-space bolp)
2258     (setq point (point))
2259     (beginning-of-line)
2260     (setq beg (point))
2261     (setq bolp (= beg point))
2262     ;; Find first line of the paragraph.
2263     (if not-break
2264         (while (and (not (eobp))
2265                     (not (looking-at message-cite-prefix-regexp))
2266                     (looking-at paragraph-start))
2267           (forward-line 1)))
2268     ;; Find the prefix
2269     (when (looking-at message-cite-prefix-regexp)
2270       (setq quoted (match-string 0))
2271       (goto-char (match-end 0))
2272       (looking-at "[ \t]*")
2273       (setq leading-space (match-string 0)))
2274     (if (and quoted
2275              (not not-break)
2276              (not bolp)
2277              (< (- point beg) (length quoted)))
2278         ;; break inside the cite prefix.
2279         (setq quoted nil
2280               end nil))
2281     (if quoted
2282         (progn
2283           (forward-line 1)
2284           (while (and (not (eobp))
2285                       (not (looking-at paragraph-separate))
2286                       (looking-at message-cite-prefix-regexp)
2287                       (equal quoted (match-string 0)))
2288             (goto-char (match-end 0))
2289             (looking-at "[ \t]*")
2290             (if (> (length leading-space) (length (match-string 0)))
2291                 (setq leading-space (match-string 0)))
2292             (forward-line 1))
2293           (setq end (point))
2294           (goto-char beg)
2295           (while (and (if (bobp) nil (forward-line -1) t)
2296                       (not (looking-at paragraph-start))
2297                       (looking-at message-cite-prefix-regexp)
2298                       (equal quoted (match-string 0)))
2299             (setq beg (point))
2300             (goto-char (match-end 0))
2301             (looking-at "[ \t]*")
2302             (if (> (length leading-space) (length (match-string 0)))
2303                 (setq leading-space (match-string 0)))))
2304       (while (and (not (eobp))
2305                   (not (looking-at paragraph-separate))
2306                   (not (looking-at message-cite-prefix-regexp)))
2307         (forward-line 1))
2308       (setq end (point))
2309       (goto-char beg)
2310       (while (and (if (bobp) nil (forward-line -1) t)
2311                   (not (looking-at paragraph-start))
2312                   (not (looking-at message-cite-prefix-regexp)))
2313         (setq beg (point))))
2314     (goto-char point)
2315     (save-restriction
2316       (narrow-to-region beg end)
2317       (if not-break
2318           (setq point nil)
2319         (if bolp
2320             (insert "\n")
2321           (insert "\n\n"))
2322         (setq point (point))
2323         (insert "\n\n")
2324         (delete-region (point) (re-search-forward "[ \t]*"))
2325         (when (and quoted (not bolp))
2326           (insert quoted leading-space)))
2327       (if quoted
2328           (let* ((adaptive-fill-regexp
2329                   (regexp-quote (concat quoted leading-space)))
2330                  (adaptive-fill-first-line-regexp
2331                   adaptive-fill-regexp ))
2332             (fill-paragraph arg))
2333         (fill-paragraph arg))
2334       (if point (goto-char point)))))
2335
2336 (defun message-fill-paragraph (&optional arg)
2337   "Like `fill-paragraph'."
2338   (interactive (list (if current-prefix-arg 'full)))
2339   (if (and (boundp 'filladapt-mode) filladapt-mode)
2340       nil
2341     (message-newline-and-reformat arg t)
2342     t))
2343
2344 ;; Is it better to use `mail-header-end'?
2345 (defun message-point-in-header-p ()
2346   "Return t if point is in the header."
2347   (save-excursion
2348     (let ((p (point)))
2349       (goto-char (point-min))
2350       (not (re-search-forward
2351             (concat "^" (regexp-quote mail-header-separator) "\n")
2352             p t)))))
2353
2354 (defun message-do-auto-fill ()
2355   "Like `do-auto-fill', but don't fill in message header."
2356   (unless (message-point-in-header-p)
2357     (do-auto-fill)))
2358
2359 (defun message-insert-signature (&optional force)
2360   "Insert a signature.  See documentation for variable `message-signature'."
2361   (interactive (list 0))
2362   (let* ((signature
2363           (cond
2364            ((and (null message-signature)
2365                  (eq force 0))
2366             (save-excursion
2367               (goto-char (point-max))
2368               (not (re-search-backward message-signature-separator nil t))))
2369            ((and (null message-signature)
2370                  force)
2371             t)
2372            ((message-functionp message-signature)
2373             (funcall message-signature))
2374            ((listp message-signature)
2375             (eval message-signature))
2376            (t message-signature)))
2377          (signature
2378           (cond ((stringp signature)
2379                  signature)
2380                 ((and (eq t signature)
2381                       message-signature-file
2382                       (file-exists-p message-signature-file))
2383                  signature))))
2384     (when signature
2385       (goto-char (point-max))
2386       ;; Insert the signature.
2387       (unless (bolp)
2388         (insert "\n"))
2389       (insert "\n" message-signature-separator-for-insertion)
2390       (unless (bolp)
2391         (insert "\n"))
2392       (if (eq signature t)
2393           (insert-file-contents message-signature-file)
2394         (insert signature))
2395       (goto-char (point-max))
2396       (or (bolp) (insert "\n")))))
2397
2398 (defun message-insert-importance-high ()
2399   "Insert header to mark message as important."
2400   (interactive)
2401   (save-excursion
2402     (message-remove-header "Importance")
2403     (message-goto-eoh)
2404     (insert "Importance: high\n")))
2405
2406 (defun message-insert-importance-low ()
2407   "Insert header to mark message as unimportant."
2408   (interactive)
2409   (save-excursion
2410     (message-remove-header "Importance")
2411     (message-goto-eoh)
2412     (insert "Importance: low\n")))
2413
2414 (defun message-insert-or-toggle-importance ()
2415   "Insert a \"Importance: high\" header, or cycle through the header values.
2416 The three allowed values according to RFC 1327 are `high', `normal'
2417 and `low'."
2418   (interactive)
2419   (save-excursion
2420     (let ((valid '("high" "normal" "low"))
2421           (new "high")
2422           cur)
2423       (when (setq cur (message-fetch-field "Importance"))
2424         (message-remove-header "Importance")
2425         (setq new (cond ((string= cur "high")
2426                          "low")
2427                         ((string= cur "low")
2428                          "normal")
2429                         (t
2430                          "high"))))
2431       (message-goto-eoh)
2432       (insert (format "Importance: %s\n" new)))))
2433
2434 (defun message-elide-region (b e)
2435   "Elide the text in the region.
2436 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2437 text was killed."
2438   (interactive "r")
2439   (kill-region b e)
2440   (insert message-elide-ellipsis))
2441
2442 (defvar message-caesar-translation-table nil)
2443
2444 (defun message-caesar-region (b e &optional n)
2445   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2446   (interactive
2447    (list
2448     (min (point) (or (mark t) (point)))
2449     (max (point) (or (mark t) (point)))
2450     (when current-prefix-arg
2451       (prefix-numeric-value current-prefix-arg))))
2452
2453   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2454   (unless (or (zerop n)                 ; no action needed for a rot of 0
2455               (= b e))                  ; no region to rotate
2456     ;; We build the table, if necessary.
2457     (when (or (not message-caesar-translation-table)
2458               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2459       (setq message-caesar-translation-table
2460             (message-make-caesar-translation-table n)))
2461     (translate-region b e message-caesar-translation-table)))
2462
2463 (defun message-make-caesar-translation-table (n)
2464   "Create a rot table with offset N."
2465   (let ((i -1)
2466         (table (make-string 256 0)))
2467     (while (< (incf i) 256)
2468       (aset table i i))
2469     (concat
2470      (substring table 0 ?A)
2471      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2472      (substring table ?A (+ ?A n))
2473      (substring table (+ ?A 26) ?a)
2474      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2475      (substring table ?a (+ ?a n))
2476      (substring table (+ ?a 26) 255))))
2477
2478 (defun message-caesar-buffer-body (&optional rotnum)
2479   "Caesar rotate all letters in the current buffer by 13 places.
2480 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2481 With prefix arg, specifies the number of places to rotate each letter forward.
2482 Mail and USENET news headers are not rotated."
2483   (interactive (if current-prefix-arg
2484                    (list (prefix-numeric-value current-prefix-arg))
2485                  (list nil)))
2486   (save-excursion
2487     (save-restriction
2488       (when (message-goto-body)
2489         (narrow-to-region (point) (point-max)))
2490       (message-caesar-region (point-min) (point-max) rotnum))))
2491
2492 (defun message-pipe-buffer-body (program)
2493   "Pipe the message body in the current buffer through PROGRAM."
2494   (save-excursion
2495     (save-restriction
2496       (when (message-goto-body)
2497         (narrow-to-region (point) (point-max)))
2498       (shell-command-on-region
2499        (point-min) (point-max) program nil t))))
2500
2501 (defun message-rename-buffer (&optional enter-string)
2502   "Rename the *message* buffer to \"*message* RECIPIENT\".
2503 If the function is run with a prefix, it will ask for a new buffer
2504 name, rather than giving an automatic name."
2505   (interactive "Pbuffer name: ")
2506   (save-excursion
2507     (save-restriction
2508       (goto-char (point-min))
2509       (narrow-to-region (point)
2510                         (search-forward mail-header-separator nil 'end))
2511       (let* ((mail-to (or
2512                        (if (message-news-p) (message-fetch-field "Newsgroups")
2513                          (message-fetch-field "To"))
2514                        ""))
2515              (mail-trimmed-to
2516               (if (string-match "," mail-to)
2517                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2518                 mail-to))
2519              (name-default (concat "*message* " mail-trimmed-to))
2520              (name (if enter-string
2521                        (read-string "New buffer name: " name-default)
2522                      name-default)))
2523         (rename-buffer name t)))))
2524
2525 (defun message-fill-yanked-message (&optional justifyp)
2526   "Fill the paragraphs of a message yanked into this one.
2527 Numeric argument means justify as well."
2528   (interactive "P")
2529   (save-excursion
2530     (goto-char (point-min))
2531     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2532     (let ((fill-prefix message-yank-prefix))
2533       (fill-individual-paragraphs (point) (point-max) justifyp))))
2534
2535 (defun message-indent-citation ()
2536   "Modify text just inserted from a message to be cited.
2537 The inserted text should be the region.
2538 When this function returns, the region is again around the modified text.
2539
2540 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2541 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2542   (let ((start (point)))
2543     ;; Remove unwanted headers.
2544     (when message-ignored-cited-headers
2545       (let (all-removed)
2546         (save-restriction
2547           (narrow-to-region
2548            (goto-char start)
2549            (if (search-forward "\n\n" nil t)
2550                (1- (point))
2551              (point)))
2552           (message-remove-header message-ignored-cited-headers t)
2553           (when (= (point-min) (point-max))
2554             (setq all-removed t))
2555           (goto-char (point-max)))
2556         (if all-removed
2557             (goto-char start)
2558           (forward-line 1))))
2559     ;; Delete blank lines at the start of the buffer.
2560     (while (and (point-min)
2561                 (eolp)
2562                 (not (eobp)))
2563       (message-delete-line))
2564     ;; Delete blank lines at the end of the buffer.
2565     (goto-char (point-max))
2566     (unless (bolp)
2567       (insert "\n"))
2568     (while (and (zerop (forward-line -1))
2569                 (looking-at "$"))
2570       (message-delete-line))
2571     ;; Do the indentation.
2572     (if (null message-yank-prefix)
2573         (indent-rigidly start (mark t) message-indentation-spaces)
2574       (save-excursion
2575         (goto-char start)
2576         (while (< (point) (mark t))
2577           (if (or (looking-at ">") (looking-at "^$"))
2578               (insert message-yank-cited-prefix)
2579             (insert message-yank-prefix))
2580           (forward-line 1))))
2581     (goto-char start)))
2582
2583 (defun message-list-references (refs-list &rest refs-strs)
2584   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
2585 to REFS-LIST."
2586   (let (refs ref id saved-id)
2587     (when (and refs-list
2588                (integerp message-list-references-add-position))
2589       (let ((pos message-list-references-add-position))
2590         (while (and refs-list
2591                     (> pos 0))
2592           (push (pop refs-list) saved-id)
2593           (setq pos (1- pos)))))
2594     (while refs-strs
2595       (when (setq refs (pop refs-strs))
2596         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
2597         (while refs
2598           (when (eq (car (setq ref (pop refs))) 'msg-id)
2599             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
2600             (or (member id refs-list)
2601                 (member id saved-id)
2602                 (push id refs-list))))))
2603     (while saved-id
2604       (push (pop saved-id) refs-list))
2605     refs-list))
2606
2607 (defvar gnus-article-copy)
2608 (defun message-yank-original (&optional arg)
2609   "Insert the message being replied to, if any.
2610 Puts point before the text and mark after.
2611 Normally indents each nonblank line ARG spaces (default 3).  However,
2612 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2613
2614 This function uses `message-cite-function' to do the actual citing.
2615
2616 Just \\[universal-argument] as argument means don't indent, insert no
2617 prefix, and don't delete any headers.
2618
2619 In addition, if `message-yank-add-new-references' is non-nil and this
2620 command is called interactively, new IDs from the yanked article will
2621 be added to \"References\" field.
2622 \(See also `message-yank-add-new-references'.)"
2623   (interactive "P")
2624   (let ((modified (buffer-modified-p))
2625         (buffer (message-eval-parameter message-reply-buffer))
2626         start end refs)
2627     (when (and buffer
2628                message-cite-function)
2629       (delete-windows-on buffer t)
2630       (insert-buffer buffer) ; mark will be set at the end of article.
2631       (setq start (point)
2632             end (mark t))
2633
2634       ;; Add new IDs to References field.
2635       (when (and message-yank-add-new-references (interactive-p))
2636         (save-excursion
2637           (save-restriction
2638             (message-narrow-to-headers)
2639             (setq refs (message-list-references
2640                         nil
2641                         (message-fetch-field "References")))
2642             (widen)
2643             (narrow-to-region start end)
2644             (std11-narrow-to-header)
2645             (when (setq refs (message-list-references
2646                               refs
2647                               (unless (eq message-yank-add-new-references
2648                                           'message-id-only)
2649                                 (or (message-fetch-field "References")
2650                                     (message-fetch-field "In-Reply-To")))
2651                               (message-fetch-field "Message-ID")))
2652               (widen)
2653               (message-narrow-to-headers)
2654               (goto-char (point-min))
2655               (let ((case-fold-search t))
2656                 (if (re-search-forward "^References:\\([\t ]+.+\n\\)+" nil t)
2657                     (replace-match "")
2658                   (goto-char (point-max))))
2659               (mail-header-format
2660                (list (or (assq 'References message-header-format-alist)
2661                          '(References . message-fill-references)))
2662                (list (cons 'References
2663                            (mapconcat 'identity (nreverse refs) " "))))
2664               (backward-delete-char 1)))))
2665
2666       (unless arg
2667         (if (and message-suspend-font-lock-when-citing
2668                  (boundp 'font-lock-mode)
2669                  (symbol-value 'font-lock-mode))
2670             (unwind-protect
2671                 (progn
2672                   (sit-for 0)
2673                   (font-lock-mode 0)
2674                   (funcall message-cite-function))
2675               (font-lock-mode 1))
2676           (funcall message-cite-function)))
2677       (message-exchange-point-and-mark)
2678       (unless (bolp)
2679         (insert ?\n))
2680       (unless modified
2681         (setq message-checksum (message-checksum))))))
2682
2683 (defun message-yank-buffer (buffer)
2684   "Insert BUFFER into the current buffer and quote it."
2685   (interactive "bYank buffer: ")
2686   (let ((message-reply-buffer buffer))
2687     (save-window-excursion
2688       (message-yank-original))))
2689
2690 (defun message-buffers ()
2691   "Return a list of active message buffers."
2692   (let (buffers)
2693     (save-excursion
2694       (dolist (buffer (buffer-list t))
2695         (set-buffer buffer)
2696         (when (and (eq major-mode 'message-mode)
2697                    (null message-sent-message-via))
2698           (push (buffer-name buffer) buffers))))
2699     (nreverse buffers)))
2700
2701 (defun message-cite-original-without-signature ()
2702   "Cite function in the standard Message manner."
2703   (let ((start (point))
2704         (end (mark t))
2705         (functions
2706          (when message-indent-citation-function
2707            (if (listp message-indent-citation-function)
2708                message-indent-citation-function
2709              (list message-indent-citation-function))))
2710         (message-reply-headers (or message-reply-headers
2711                                    (make-mail-header))))
2712     (mail-header-set-from message-reply-headers
2713                           (save-restriction
2714                             (narrow-to-region
2715                              (point)
2716                              (if (search-forward "\n\n" nil t)
2717                                  (1- (point))
2718                                (point-max)))
2719                             (or (message-fetch-field "from")
2720                                 "unknown sender")))
2721     ;; Allow undoing.
2722     (undo-boundary)
2723     (goto-char end)
2724     (when (re-search-backward message-signature-separator start t)
2725       ;; Also peel off any blank lines before the signature.
2726       (forward-line -1)
2727       (while (looking-at "^[ \t]*$")
2728         (forward-line -1))
2729       (forward-line 1)
2730       (delete-region (point) end)
2731       (unless (search-backward "\n\n" start t)
2732         ;; Insert a blank line if it is peeled off.
2733         (insert "\n")))
2734     (goto-char start)
2735     (while functions
2736       (funcall (pop functions)))
2737     (when message-citation-line-function
2738       (unless (bolp)
2739         (insert "\n"))
2740       (funcall message-citation-line-function))))
2741
2742 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2743 (defun message-cite-original ()
2744   "Cite function in the standard Message manner."
2745   (if (and (boundp 'mail-citation-hook)
2746            mail-citation-hook)
2747       (run-hooks 'mail-citation-hook)
2748     (let ((start (point))
2749           (end (mark t))
2750           (functions
2751            (when message-indent-citation-function
2752              (if (listp message-indent-citation-function)
2753                  message-indent-citation-function
2754                (list message-indent-citation-function))))
2755           (message-reply-headers (or message-reply-headers
2756                                      (make-mail-header))))
2757       (mail-header-set-from message-reply-headers
2758                             (save-restriction
2759                               (narrow-to-region
2760                                (point)
2761                                (if (search-forward "\n\n" nil t)
2762                                    (1- (point))
2763                                  (point-max)))
2764                               (or (message-fetch-field "from")
2765                                   "unknown sender")))
2766       (goto-char start)
2767       (while functions
2768         (funcall (pop functions)))
2769       (when message-citation-line-function
2770         (unless (bolp)
2771           (insert "\n"))
2772         (funcall message-citation-line-function)))))
2773
2774 (defun message-insert-citation-line ()
2775   "Insert a simple citation line."
2776   (when message-reply-headers
2777     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2778
2779 (defun message-position-on-field (header &rest afters)
2780   (let ((case-fold-search t))
2781     (save-restriction
2782       (narrow-to-region
2783        (goto-char (point-min))
2784        (progn
2785          (re-search-forward
2786           (concat "^" (regexp-quote mail-header-separator) "$"))
2787          (match-beginning 0)))
2788       (goto-char (point-min))
2789       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2790           (progn
2791             (re-search-forward "^[^ \t]" nil 'move)
2792             (beginning-of-line)
2793             (skip-chars-backward "\n")
2794             t)
2795         (while (and afters
2796                     (not (re-search-forward
2797                           (concat "^" (regexp-quote (car afters)) ":")
2798                           nil t)))
2799           (pop afters))
2800         (when afters
2801           (re-search-forward "^[^ \t]" nil 'move)
2802           (beginning-of-line))
2803         (insert header ": \n")
2804         (forward-char -1)
2805         nil))))
2806
2807 (defun message-remove-signature ()
2808   "Remove the signature from the text between point and mark.
2809 The text will also be indented the normal way."
2810   (save-excursion
2811     (let ((start (point))
2812           mark)
2813       (if (not (re-search-forward message-signature-separator (mark t) t))
2814           ;; No signature here, so we just indent the cited text.
2815           (message-indent-citation)
2816         ;; Find the last non-empty line.
2817         (forward-line -1)
2818         (while (looking-at "[ \t]*$")
2819           (forward-line -1))
2820         (forward-line 1)
2821         (setq mark (set-marker (make-marker) (point)))
2822         (goto-char start)
2823         (message-indent-citation)
2824         ;; Enable undoing the deletion.
2825         (undo-boundary)
2826         (delete-region mark (mark t))
2827         (set-marker mark nil)))))
2828
2829 \f
2830
2831 ;;;
2832 ;;; Sending messages
2833 ;;;
2834
2835 ;; Avoid byte-compile warning.
2836 (defvar message-encoding-buffer nil)
2837 (defvar message-edit-buffer nil)
2838 (defvar message-mime-mode nil)
2839
2840 (defun message-send-and-exit (&optional arg)
2841   "Send message like `message-send', then, if no errors, exit from mail buffer."
2842   (interactive "P")
2843   (let ((buf (current-buffer))
2844         (actions message-exit-actions)
2845         (frame (selected-frame))
2846         (org-frame message-original-frame))
2847     (when (and (message-send arg)
2848                (buffer-name buf))
2849       (if message-kill-buffer-on-exit
2850           (kill-buffer buf)
2851         (bury-buffer buf)
2852         (when (eq buf (current-buffer))
2853           (message-bury buf)))
2854       (message-do-actions actions)
2855       (message-delete-frame frame org-frame)
2856       t)))
2857
2858 (defun message-dont-send ()
2859   "Don't send the message you have been editing."
2860   (interactive)
2861   (message-save-drafts)
2862   (let ((actions message-postpone-actions)
2863         (frame (selected-frame))
2864         (org-frame message-original-frame))
2865     (message-bury (current-buffer))
2866     (message-do-actions actions)
2867     (message-delete-frame frame org-frame)))
2868
2869 (defun message-kill-buffer ()
2870   "Kill the current buffer."
2871   (interactive)
2872   (when (or (not (buffer-modified-p))
2873             (eq t message-kill-buffer-query-function)
2874             (funcall message-kill-buffer-query-function
2875                      "The buffer modified; kill anyway? "))
2876     (let ((actions message-kill-actions)
2877           (draft-article message-draft-article)
2878           (auto-save-file-name buffer-auto-save-file-name)
2879           (file-name buffer-file-name)
2880           (modified (buffer-modified-p))
2881           (frame (selected-frame))
2882           (org-frame message-original-frame))
2883       (setq buffer-file-name nil)
2884       (kill-buffer (current-buffer))
2885       (when (and message-kill-buffer-and-remove-file
2886                  (or (and auto-save-file-name
2887                           (file-exists-p auto-save-file-name))
2888                      (and file-name
2889                           (file-exists-p file-name)))
2890                  (yes-or-no-p (format "Remove the backup file%s? "
2891                                       (if modified " too" ""))))
2892         (ignore-errors
2893           (delete-file auto-save-file-name))
2894         (let ((message-draft-article draft-article))
2895           (message-disassociate-draft)))
2896       (message-do-actions actions)
2897       (message-delete-frame frame org-frame)))
2898   (message ""))
2899
2900 (defun message-mimic-kill-buffer ()
2901   "Kill the current buffer with query.  This is an imitation for
2902 `kill-buffer', but it will delete a message frame."
2903   (interactive)
2904   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
2905                                       (buffer-name))))
2906         message-kill-buffer-and-remove-file)
2907     (when (or (not bufname)
2908               (string-equal bufname "")
2909               (string-equal bufname (buffer-name)))
2910       (message-kill-buffer))))
2911
2912 (defun message-delete-frame (frame org-frame)
2913   "Delete frame for editing message."
2914   (when (and (or (static-if (featurep 'xemacs)
2915                      (device-on-window-system-p)
2916                    window-system)
2917                  (>= emacs-major-version 20))
2918              (or (and (eq message-delete-frame-on-exit t)
2919                       (select-frame frame)
2920                       (or (eq frame org-frame)
2921                           (prog1
2922                               (y-or-n-p "Delete this frame?")
2923                             (message ""))))
2924                  (and (eq message-delete-frame-on-exit 'ask)
2925                       (select-frame frame)
2926                       (prog1
2927                           (y-or-n-p "Delete this frame?")
2928                         (message "")))))
2929     (delete-frame frame)))
2930
2931 (defun message-bury (buffer)
2932   "Bury this mail BUFFER."
2933   (let ((newbuf (other-buffer buffer)))
2934     (bury-buffer buffer)
2935     (if (and (fboundp 'frame-parameters)
2936              (cdr (assq 'dedicated (frame-parameters)))
2937              (not (null (delq (selected-frame) (visible-frame-list)))))
2938         (delete-frame (selected-frame))
2939       (switch-to-buffer newbuf))))
2940
2941 (defun message-send (&optional arg)
2942   "Send the message in the current buffer.
2943 If `message-interactive' is non-nil, wait for success indication or
2944 error messages, and inform user.
2945 Otherwise any failure is reported in a message back to the user from
2946 the mailer.
2947 The usage of ARG is defined by the instance that called Message.
2948 It should typically alter the sending method in some way or other."
2949   (interactive "P")
2950   ;; Disabled test.
2951   (when (or (buffer-modified-p)
2952             (message-check-element 'unchanged)
2953             (y-or-n-p "No changes in the buffer; really send? "))
2954     ;; Make it possible to undo the coming changes.
2955     (undo-boundary)
2956     (let ((inhibit-read-only t))
2957       (put-text-property (point-min) (point-max) 'read-only nil))
2958     (run-hooks 'message-send-hook)
2959     (message-fix-before-sending)
2960     (message message-sending-message)
2961     (let ((message-encoding-buffer
2962            (message-generate-new-buffer-clone-locals " message encoding"))
2963           (message-edit-buffer (current-buffer))
2964           (message-mime-mode mime-edit-mode-flag)
2965           (alist message-send-method-alist)
2966           (success t)
2967           elem sent dont-barf-on-no-method
2968           (message-options message-options))
2969       (message-options-set-recipient)
2970       (save-excursion
2971         (set-buffer message-encoding-buffer)
2972         (erase-buffer)
2973         ;; ;; Avoid copying text props.
2974         ;; T-gnus change: copy all text props from the editing buffer
2975         ;; into the encoding buffer.
2976         (insert-buffer message-edit-buffer)
2977         (funcall message-encode-function)
2978         (while (and success
2979                     (setq elem (pop alist)))
2980           (when (funcall (cadr elem))
2981             (when (and (or (not (memq (car elem)
2982                                       message-sent-message-via))
2983                            (if (or (message-gnksa-enable-p 'multiple-copies)
2984                                    (not (eq (car elem) 'news)))
2985                                (y-or-n-p
2986                                 (format
2987                                  "Already sent message via %s; resend? "
2988                                  (car elem)))
2989                              (error "Denied posting -- multiple copies")))
2990                        (setq success (funcall (caddr elem) arg)))
2991               (setq sent t)))))
2992       (unless
2993           (or sent (not success)
2994               (let ((fcc (message-fetch-field "Fcc"))
2995                     (gcc (message-fetch-field "Gcc")))
2996                 (when (or fcc gcc)
2997                   (or (eq message-allow-no-recipients 'always)
2998                       (and (not (eq message-allow-no-recipients 'never))
2999                            (setq dont-barf-on-no-method
3000                                  (gnus-y-or-n-p
3001                                   (format "No receiver, perform %s anyway? "
3002                                           (cond ((and fcc gcc) "Fcc and Gcc")
3003                                                 (fcc "Fcc")
3004                                                 (t "Gcc"))))))))))
3005         (error "No methods specified to send by"))
3006       (prog1
3007           (when (or dont-barf-on-no-method
3008                     (and success sent))
3009             (message-do-fcc)
3010             (save-excursion
3011               (run-hooks 'message-sent-hook))
3012             (message "Sending...done")
3013             ;; Mark the buffer as unmodified and delete auto-save.
3014             (set-buffer-modified-p nil)
3015             (delete-auto-save-file-if-necessary t)
3016             (message-disassociate-draft)
3017             ;; Delete other mail buffers and stuff.
3018             (message-do-send-housekeeping)
3019             (message-do-actions message-send-actions)
3020             ;; Return success.
3021             t)
3022         (kill-buffer message-encoding-buffer)))))
3023
3024 (defun message-send-via-mail (arg)
3025   "Send the current message via mail."
3026   (message-send-mail arg))
3027
3028 (defun message-send-via-news (arg)
3029   "Send the current message via news."
3030   (message-send-news arg))
3031
3032 (defmacro message-check (type &rest forms)
3033   "Eval FORMS if TYPE is to be checked."
3034   `(or (message-check-element ,type)
3035        (save-excursion
3036          ,@forms)))
3037
3038 (put 'message-check 'lisp-indent-function 1)
3039 (put 'message-check 'edebug-form-spec '(form body))
3040
3041 ;; Advise the function `invisible-region'.
3042 (let (current-load-list)
3043   (eval
3044    `(defadvice invisible-region (around add-mime-edit-invisible (start end)
3045                                         activate)
3046       "Advised by T-gnus Message.
3047 Add the text property `mime-edit-invisible' to an invisible text when
3048 the buffer's major mode is `message-mode'.  The added property will be
3049 used to distinguish whether the invisible text is a MIME part or not."
3050       ,(if (featurep 'xemacs)
3051            '(if (eq ?\n (char-after start))
3052                 (setq start (1+ start)))
3053          '(if (eq ?\n (char-after (1- end)))
3054               (setq end (1- end))))
3055       (setq ad-return-value
3056             (if (eq 'message-mode major-mode)
3057                 (add-text-properties start end
3058                                      '(invisible t mime-edit-invisible t))
3059               (put-text-property start end 'invisible t))))))
3060
3061 (defun message-fix-before-sending ()
3062   "Do various things to make the message nice before sending it."
3063   ;; Make sure there's a newline at the end of the message.
3064   (widen)
3065   (goto-char (point-max))
3066   (unless (bolp)
3067     (insert "\n"))
3068   ;; Delete all invisible text except for the mime parts which might
3069   ;; be inserted by the MIME-Edit.
3070   (message-check 'invisible-text
3071     (let (from
3072           (to (point-min))
3073           mime-from mime-to hidden-start)
3074       (while (setq from (text-property-any to (point-max) 'invisible t))
3075         (setq to (or (text-property-not-all from (point-max) 'invisible t)
3076                      (point-max))
3077               mime-to from)
3078         (while (setq mime-from (text-property-any mime-to to
3079                                                   'mime-edit-invisible t))
3080           (when (> mime-from mime-to)
3081             (setq hidden-start (or hidden-start mime-to))
3082             (put-text-property mime-to mime-from 'invisible nil))
3083           (setq mime-to (or (text-property-not-all mime-from to
3084                                                    'mime-edit-invisible t)
3085                             to)))
3086         (when (< mime-to to)
3087           (setq hidden-start (or hidden-start mime-to))
3088           (put-text-property mime-to to 'invisible nil)))
3089       (when hidden-start
3090         (goto-char hidden-start)
3091         (set-window-start (selected-window) (gnus-point-at-bol))
3092         (unless (yes-or-no-p
3093                  "Invisible text found and made visible; continue posting? ")
3094           (error "Invisible text found and made visible"))))))
3095
3096 (defun message-add-action (action &rest types)
3097   "Add ACTION to be performed when doing an exit of type TYPES."
3098   (let (var)
3099     (while types
3100       (set (setq var (intern (format "message-%s-actions" (pop types))))
3101            (nconc (symbol-value var) (list action))))))
3102
3103 (defun message-do-actions (actions)
3104   "Perform all actions in ACTIONS."
3105   ;; Now perform actions on successful sending.
3106   (while actions
3107     (ignore-errors
3108       (cond
3109        ;; A simple function.
3110        ((message-functionp (car actions))
3111         (funcall (car actions)))
3112        ;; Something to be evaled.
3113        (t
3114         (eval (car actions)))))
3115     (pop actions)))
3116
3117 (defsubst message-maybe-split-and-send-mail ()
3118   "Split a message if necessary, and send it via mail.
3119 Returns nil if sending succeeded, returns any string if sending failed.
3120 This sub function is for exclusive use of `message-send-mail'."
3121   (let ((mime-edit-split-ignored-field-regexp
3122          mime-edit-split-ignored-field-regexp)
3123         (case-fold-search t)
3124         failure)
3125     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3126       (setq mime-edit-split-ignored-field-regexp
3127             (concat (substring mime-edit-split-ignored-field-regexp
3128                                0 (match-beginning 0))
3129                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3130                     "_so_don't_rape_it!"
3131                     (substring mime-edit-split-ignored-field-regexp
3132                                (match-end 0)))))
3133     (setq failure
3134           (or
3135            (catch 'message-sending-mail-failure
3136              (mime-edit-maybe-split-and-send
3137               (function
3138                (lambda ()
3139                  (interactive)
3140                  (save-restriction
3141                    (std11-narrow-to-header mail-header-separator)
3142                    (goto-char (point-min))
3143                    (when (re-search-forward "^Message-ID:" nil t)
3144                      (delete-region (match-end 0) (std11-field-end))
3145                      (insert " " (message-make-message-id))))
3146                  (condition-case err
3147                      (funcall (or message-send-mail-real-function
3148                                   message-send-mail-function))
3149                    (error
3150                     (throw 'message-sending-mail-failure err))))))
3151              nil)
3152            (condition-case err
3153                (progn
3154                  (funcall (or message-send-mail-real-function
3155                               message-send-mail-function))
3156                  nil)
3157              (error err))))
3158     (when failure
3159       (if (eq 'error (car failure))
3160           (cadr failure)
3161         (prin1-to-string failure)))))
3162
3163 (defun message-send-mail-partially ()
3164   "Send mail as message/partial."
3165   ;; replace the header delimiter with a blank line
3166   (goto-char (point-min))
3167   (re-search-forward
3168    (concat "^" (regexp-quote mail-header-separator) "\n"))
3169   (replace-match "\n")
3170   (run-hooks 'message-send-mail-hook)
3171   (let ((p (goto-char (point-min)))
3172         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3173         (curbuf (current-buffer))
3174         (id (message-make-message-id)) (n 1)
3175         plist total  header required-mail-headers)
3176     (while (not (eobp))
3177       (if (< (point-max) (+ p message-send-mail-partially-limit))
3178           (goto-char (point-max))
3179         (goto-char (+ p message-send-mail-partially-limit))
3180         (beginning-of-line)
3181         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3182       (push p plist)
3183       (setq p (point)))
3184     (setq total (length plist))
3185     (push (point-max) plist)
3186     (setq plist (nreverse plist))
3187     (unwind-protect
3188         (save-excursion
3189           (setq p (pop plist))
3190           (while plist
3191             (set-buffer curbuf)
3192             (copy-to-buffer tembuf p (car plist))
3193             (set-buffer tembuf)
3194             (goto-char (point-min))
3195             (if header
3196                 (progn
3197                   (goto-char (point-min))
3198                   (narrow-to-region (point) (point))
3199                   (insert header))
3200               (message-goto-eoh)
3201               (setq header (buffer-substring (point-min) (point)))
3202               (goto-char (point-min))
3203               (narrow-to-region (point) (point))
3204               (insert header)
3205               (message-remove-header "Mime-Version")
3206               (message-remove-header "Content-Type")
3207               (message-remove-header "Content-Transfer-Encoding")
3208               (message-remove-header "Message-ID")
3209               (message-remove-header "Lines")
3210               (goto-char (point-max))
3211               (insert "Mime-Version: 1.0\n")
3212               (setq header (buffer-substring (point-min) (point-max))))
3213             (goto-char (point-max))
3214             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3215                             id n total))
3216             (forward-char -1)
3217             (let ((mail-header-separator ""))
3218               (when (memq 'Message-ID message-required-mail-headers)
3219                 (insert "Message-ID: " (message-make-message-id) "\n"))
3220               (when (memq 'Lines message-required-mail-headers)
3221                 (insert "Lines: " (message-make-lines) "\n"))
3222               (message-goto-subject)
3223               (end-of-line)
3224               (insert (format " (%d/%d)" n total))
3225               (widen)
3226               (mm-with-unibyte-current-buffer
3227                 (funcall (or message-send-mail-real-function
3228                              message-send-mail-function))))
3229             (setq n (+ n 1))
3230             (setq p (pop plist))
3231             (erase-buffer)))
3232       (kill-buffer tembuf))))
3233
3234 (defun message-send-mail (&optional arg)
3235   (require 'mail-utils)
3236   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3237          (case-fold-search nil)
3238          (news (message-news-p))
3239          (message-this-is-mail t)
3240          (headers message-required-mail-headers)
3241          failure)
3242     (save-restriction
3243       (message-narrow-to-headers)
3244       ;; Generate the Mail-Followup-To header if the header is not there...
3245       (if (and (or message-subscribed-regexps
3246                    message-subscribed-addresses
3247                    message-subscribed-address-file
3248                    message-subscribed-address-functions)
3249                (not (mail-fetch-field "mail-followup-to")))
3250           (setq headers
3251                 (cons
3252                  (cons "Mail-Followup-To" (message-make-mft))
3253                  message-required-mail-headers))
3254         ;; otherwise, delete the MFT header if the field is empty
3255         (when (equal "" (mail-fetch-field "mail-followup-to"))
3256           (message-remove-header "^Mail-Followup-To:")))
3257       ;; Insert some headers.
3258       (let ((message-deletable-headers
3259              (if news nil message-deletable-headers)))
3260         (message-generate-headers headers))
3261       ;; Let the user do all of the above.
3262       (run-hooks 'message-header-hook))
3263     (if (not (message-check-mail-syntax))
3264         (progn
3265           (message "")
3266           nil)
3267       (unwind-protect
3268           (save-excursion
3269             (set-buffer tembuf)
3270             (erase-buffer)
3271             (insert-buffer message-encoding-buffer)
3272             ;; Remove some headers.
3273             (save-restriction
3274               (message-narrow-to-headers)
3275 ;; We Semi-gnus people have no use for it.
3276 ;;            ;; We (re)generate the Lines header.
3277 ;;            (when (memq 'Lines message-required-mail-headers)
3278 ;;              (message-generate-headers '(Lines)))
3279               ;; Remove some headers.
3280               (message-remove-header message-ignored-mail-headers t))
3281             (goto-char (point-max))
3282             ;; require one newline at the end.
3283             (or (= (preceding-char) ?\n)
3284                 (insert ?\n))
3285             (when
3286                 (save-restriction
3287                   (message-narrow-to-headers)
3288                   (and news
3289                        (or (message-fetch-field "cc")
3290                            (message-fetch-field "to"))
3291                        (let ((ct (mime-read-Content-Type)))
3292                          (or (not ct)
3293                              (and (eq 'text (cdr (assq 'type ct)))
3294                                   (eq 'plain (cdr (assq 'subtype ct))))))))
3295               (message-insert-courtesy-copy))
3296             (setq failure (message-maybe-split-and-send-mail)))
3297         (kill-buffer tembuf))
3298       (set-buffer message-edit-buffer)
3299       (if failure
3300           (progn
3301             (message "Couldn't send message via mail: %s" failure)
3302             nil)
3303         (push 'mail message-sent-message-via)))))
3304
3305 (defun message-send-mail-with-sendmail ()
3306   "Send off the prepared buffer with sendmail."
3307   (let ((errbuf (if message-interactive
3308                     (message-generate-new-buffer-clone-locals
3309                      " sendmail errors")
3310                   0))
3311         resend-to-addresses delimline)
3312     (let ((case-fold-search t))
3313       (save-restriction
3314         (message-narrow-to-headers)
3315         (setq resend-to-addresses (message-fetch-field "resent-to")))
3316       ;; Change header-delimiter to be what sendmail expects.
3317       (goto-char (point-min))
3318       (re-search-forward
3319        (concat "^" (regexp-quote mail-header-separator) "\n"))
3320       (replace-match "\n")
3321       (backward-char 1)
3322       (setq delimline (point-marker))
3323       (run-hooks 'message-send-mail-hook)
3324       ;; Insert an extra newline if we need it to work around
3325       ;; Sun's bug that swallows newlines.
3326       (goto-char (1+ delimline))
3327       (when (eval message-mailer-swallows-blank-line)
3328         (newline))
3329       (when message-interactive
3330         (save-excursion
3331           (set-buffer errbuf)
3332           (erase-buffer))))
3333     (let ((default-directory "/"))
3334       (as-binary-process
3335        (apply 'call-process-region
3336               (append (list (point-min) (point-max)
3337                             (if (boundp 'sendmail-program)
3338                                 sendmail-program
3339                               "/usr/lib/sendmail")
3340                             nil errbuf nil "-oi")
3341                       ;; Always specify who from,
3342                       ;; since some systems have broken sendmails.
3343                       ;; But some systems are more broken with -f, so
3344                       ;; we'll let users override this.
3345                       (if (null message-sendmail-f-is-evil)
3346                           (list "-f" (message-make-address)))
3347                       ;; These mean "report errors by mail"
3348                       ;; and "deliver in background".
3349                       (if (null message-interactive) '("-oem" "-odb"))
3350                       ;; Get the addresses from the message
3351                       ;; unless this is a resend.
3352                       ;; We must not do that for a resend
3353                       ;; because we would find the original addresses.
3354                       ;; For a resend, include the specific addresses.
3355                       (if resend-to-addresses
3356                           (list resend-to-addresses)
3357                         '("-t"))))))
3358     (when message-interactive
3359       (save-excursion
3360         (set-buffer errbuf)
3361         (goto-char (point-min))
3362         (while (re-search-forward "\n\n* *" nil t)
3363           (replace-match "; "))
3364         (if (not (zerop (buffer-size)))
3365             (error "Sending...failed to %s"
3366                    (buffer-substring (point-min) (point-max)))))
3367       (when (bufferp errbuf)
3368         (kill-buffer errbuf)))))
3369
3370 (defun message-send-mail-with-qmail ()
3371   "Pass the prepared message buffer to qmail-inject.
3372 Refer to the documentation for the variable `message-send-mail-function'
3373 to find out how to use this."
3374   ;; replace the header delimiter with a blank line
3375   (goto-char (point-min))
3376   (re-search-forward
3377    (concat "^" (regexp-quote mail-header-separator) "\n"))
3378   (replace-match "\n")
3379   (backward-char 1)
3380   (run-hooks 'message-send-mail-hook)
3381   ;; send the message
3382   (case
3383       (as-binary-process
3384        (apply
3385         'call-process-region 1 (point-max) message-qmail-inject-program
3386         nil nil nil
3387         ;; qmail-inject's default behaviour is to look for addresses on the
3388         ;; command line; if there're none, it scans the headers.
3389         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3390         ;;
3391         ;; in general, ALL of qmail-inject's defaults are perfect for simply
3392         ;; reading a formatted (i. e., at least a To: or Resent-To header)
3393         ;; message from stdin.
3394         ;;
3395         ;; qmail also has the advantage of not having been raped by
3396         ;; various vendors, so we don't have to allow for that, either --
3397         ;; compare this with message-send-mail-with-sendmail and weep
3398         ;; for sendmail's lost innocence.
3399         ;;
3400         ;; all this is way cool coz it lets us keep the arguments entirely
3401         ;; free for -inject-arguments -- a big win for the user and for us
3402         ;; since we don't have to play that double-guessing game and the user
3403         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3404         message-qmail-inject-args))
3405     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3406     ;; we have to look at the retval instead
3407     (0 nil)
3408     (100 (error "qmail-inject reported permanent failure"))
3409     (111 (error "qmail-inject reported transient failure"))
3410     ;; should never happen
3411     (t   (error "qmail-inject reported unknown failure"))))
3412
3413 (defun message-send-mail-with-mh ()
3414   "Send the prepared message buffer with mh."
3415   (let ((mh-previous-window-config nil)
3416         (name (mh-new-draft-name)))
3417     (setq buffer-file-name name)
3418     ;; MH wants to generate these headers itself.
3419     (when message-mh-deletable-headers
3420       (let ((headers message-mh-deletable-headers))
3421         (while headers
3422           (goto-char (point-min))
3423           (and (re-search-forward
3424                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3425                (message-delete-line))
3426           (pop headers))))
3427     (run-hooks 'message-send-mail-hook)
3428     ;; Pass it on to mh.
3429     (mh-send-letter)))
3430
3431 (defun message-send-mail-with-smtp ()
3432   "Send off the prepared buffer with SMTP."
3433   (require 'smtp) ; XXX
3434   (let ((case-fold-search t)
3435         recipients)
3436     (save-restriction
3437       (message-narrow-to-headers)
3438       (setq recipients
3439             ;; XXX: Should be replaced by better one.
3440             (smtp-deduce-address-list (current-buffer)
3441                                       (point-min) (point-max)))
3442       ;; Remove BCC lines.
3443       (message-remove-header "bcc"))
3444     ;; replace the header delimiter with a blank line.
3445     (goto-char (point-min))
3446     (re-search-forward
3447      (concat "^" (regexp-quote mail-header-separator) "\n"))
3448     (replace-match "\n")
3449     (backward-char 1)
3450     (run-hooks 'message-send-mail-hook)
3451     (if recipients
3452         (static-if (fboundp 'smtp-send-buffer)
3453             (smtp-send-buffer user-mail-address recipients
3454                               (current-buffer))
3455           (let ((result (smtp-via-smtp user-mail-address recipients
3456                                        (current-buffer))))
3457             (unless (eq result t)
3458               (error "Sending failed; %s" result))))
3459       (error "Sending failed; no recipients"))))
3460
3461 (defsubst message-maybe-split-and-send-news (method)
3462   "Split a message if necessary, and send it via news.
3463 Returns nil if sending succeeded, returns t if sending failed.
3464 This sub function is for exclusive use of `message-send-news'."
3465   (let ((mime-edit-split-ignored-field-regexp
3466          mime-edit-split-ignored-field-regexp)
3467         (case-fold-search t))
3468     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
3469       (setq mime-edit-split-ignored-field-regexp
3470             (concat (substring mime-edit-split-ignored-field-regexp
3471                                0 (match-beginning 0))
3472                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
3473                     "_so_don't_rape_it!"
3474                     (substring mime-edit-split-ignored-field-regexp
3475                                (match-end 0)))))
3476     (or
3477      (catch 'message-sending-news-failure
3478        (mime-edit-maybe-split-and-send
3479         (function
3480          (lambda ()
3481            (interactive)
3482            (save-restriction
3483              (std11-narrow-to-header mail-header-separator)
3484              (goto-char (point-min))
3485              (when (re-search-forward "^Message-ID:" nil t)
3486                (delete-region (match-end 0) (std11-field-end))
3487                (insert " " (message-make-message-id))))
3488            (unless (funcall message-send-news-function method)
3489              (throw 'message-sending-news-failure t)))))
3490        nil)
3491      (not (funcall message-send-news-function method)))))
3492
3493 (defun message-canlock-generate ()
3494   "Return a string that is non-trival to guess.
3495 Do not use this for anything important, it is cryptographically weak."
3496   (sha1 (concat (message-unique-id)
3497                 (format "%x%x%x" (random) (random t) (random))
3498                 (prin1-to-string (recent-keys))
3499                 (prin1-to-string (garbage-collect)))))
3500
3501 (defun message-canlock-password ()
3502   "The password used by message for cancel locks.
3503 This is the value of `canlock-password', if that option is non-nil.
3504 Otherwise, generate and save a value for `canlock-password' first."
3505   (unless canlock-password
3506     (customize-save-variable 'canlock-password (message-canlock-generate)))
3507   canlock-password)
3508
3509 (defun message-insert-canlock ()
3510   (when message-insert-canlock
3511     (message-canlock-password)
3512     (canlock-insert-header)))
3513
3514 (defun message-send-news (&optional arg)
3515   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3516          (case-fold-search nil)
3517          (method (if (message-functionp message-post-method)
3518                      (funcall message-post-method arg)
3519                    message-post-method))
3520          (newsgroups-field (save-restriction
3521                              (message-narrow-to-headers-or-head)
3522                              (message-fetch-field "Newsgroups")))
3523          (followup-field (save-restriction
3524                            (message-narrow-to-headers-or-head)
3525                            (message-fetch-field "Followup-To")))
3526          ;; BUG: We really need to get the charset for each name in the
3527          ;; Newsgroups and Followup-To lines to allow crossposting
3528          ;; between group namess with incompatible character sets.
3529          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3530          (group-field-charset
3531           (gnus-group-name-charset method newsgroups-field))
3532          (followup-field-charset
3533           (gnus-group-name-charset method (or followup-field "")))
3534          (mime-field-encoding-method-alist
3535           (append (when group-field-charset
3536                     (list (cons "Newsgroups" group-field-charset)))
3537                   (when followup-field-charset
3538                     (list (cons "Followup-To" followup-field-charset)))
3539                   mime-field-encoding-method-alist))
3540          (message-syntax-checks
3541           (if (and arg
3542                    (listp message-syntax-checks))
3543               (cons '(existing-newsgroups . disabled)
3544                     message-syntax-checks)
3545             message-syntax-checks))
3546          (message-this-is-news t)
3547          result)
3548     (save-restriction
3549       (message-narrow-to-headers)
3550       ;; Insert some headers.
3551       (message-generate-headers message-required-news-headers)
3552       (message-insert-canlock)
3553       ;; Let the user do all of the above.
3554       (run-hooks 'message-header-hook))
3555     ;; Note: This check will be disabled by the ".*" default value for
3556     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3557     (when (and group-field-charset
3558                (listp message-syntax-checks))
3559       (setq message-syntax-checks
3560             (cons '(valid-newsgroups . disabled)
3561                   message-syntax-checks)))
3562     (message-cleanup-headers)
3563     (if (not (let ((message-post-method method))
3564                (message-check-news-syntax)))
3565         nil
3566       (unwind-protect
3567           (save-excursion
3568             (set-buffer tembuf)
3569             (buffer-disable-undo)
3570             (erase-buffer)
3571             (insert-buffer message-encoding-buffer)
3572             ;; Remove some headers.
3573             (save-restriction
3574               (message-narrow-to-headers)
3575 ;; We Semi-gnus people have no use for it.
3576 ;;            ;; We (re)generate the Lines header.
3577 ;;            (when (memq 'Lines message-required-mail-headers)
3578 ;;              (message-generate-headers '(Lines)))
3579               ;; Remove some headers.
3580               (message-remove-header message-ignored-news-headers t))
3581             (goto-char (point-max))
3582             ;; require one newline at the end.
3583             (or (= (preceding-char) ?\n)
3584                 (insert ?\n))
3585             (setq result (message-maybe-split-and-send-news method)))
3586         (kill-buffer tembuf))
3587       (set-buffer message-edit-buffer)
3588       (if result
3589           (progn
3590             (message "Couldn't send message via news: %s"
3591                      (nnheader-get-report (car method)))
3592             nil)
3593         (push 'news message-sent-message-via)))))
3594
3595 ;; 1997-09-29 by MORIOKA Tomohiko
3596 (defun message-send-news-with-gnus (method)
3597   (let ((case-fold-search t))
3598     ;; Remove the delimiter.
3599     (goto-char (point-min))
3600     (re-search-forward
3601      (concat "^" (regexp-quote mail-header-separator) "\n"))
3602     (replace-match "\n")
3603     (backward-char 1)
3604     (run-hooks 'message-send-news-hook)
3605     (gnus-open-server method)
3606     (message "Sending news with %s..." (gnus-server-string method))
3607     (gnus-request-post method)
3608     ))
3609
3610 ;;;
3611 ;;; Header generation & syntax checking.
3612 ;;;
3613
3614 (defun message-check-element (type)
3615   "Return non-nil if this TYPE is not to be checked."
3616   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3617       t
3618     (let ((able (assq type message-syntax-checks)))
3619       (and (consp able)
3620            (eq (cdr able) 'disabled)))))
3621
3622 (defun message-check-news-syntax ()
3623   "Check the syntax of the message."
3624   (save-excursion
3625     (save-restriction
3626       (widen)
3627       (and
3628        ;; We narrow to the headers and check them first.
3629        (save-excursion
3630          (save-restriction
3631            (message-narrow-to-headers)
3632            (message-check-news-header-syntax)))
3633        ;; Check the body.
3634        (save-excursion
3635          (set-buffer message-edit-buffer)
3636          (message-check-news-body-syntax))))))
3637
3638 (defun message-check-news-header-syntax ()
3639   (and
3640    ;; Check Newsgroups header.
3641    (message-check 'newsgroups
3642      (let ((group (message-fetch-field "newsgroups")))
3643        (or
3644         (and group
3645              (not (string-match "\\`[ \t]*\\'" group)))
3646         (ignore
3647          (message
3648           "The newsgroups field is empty or missing.  Posting is denied.")))))
3649    ;; Check the Subject header.
3650    (message-check 'subject
3651      (let* ((case-fold-search t)
3652             (subject (message-fetch-field "subject")))
3653        (or
3654         (and subject
3655              (not (string-match "\\`[ \t]*\\'" subject)))
3656         (ignore
3657          (message
3658           "The subject field is empty or missing.  Posting is denied.")))))
3659    ;; Check for commands in Subject.
3660    (message-check 'subject-cmsg
3661      (if (string-match "^cmsg " (message-fetch-field "subject"))
3662          (y-or-n-p
3663           "The control code \"cmsg\" is in the subject.  Really post? ")
3664        t))
3665    ;; Check for multiple identical headers.
3666    (message-check 'multiple-headers
3667      (let (found)
3668        (while (and (not found)
3669                    (re-search-forward "^[^ \t:]+: " nil t))
3670          (save-excursion
3671            (or (re-search-forward
3672                 (concat "^"
3673                         (regexp-quote
3674                          (setq found
3675                                (buffer-substring
3676                                 (match-beginning 0) (- (match-end 0) 2))))
3677                         ":")
3678                 nil t)
3679                (setq found nil))))
3680        (if found
3681            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3682          t)))
3683    ;; Check for Version and Sendsys.
3684    (message-check 'sendsys
3685      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3686          (y-or-n-p
3687           (format "The article contains a %s command.  Really post? "
3688                   (buffer-substring (match-beginning 0)
3689                                     (1- (match-end 0)))))
3690        t))
3691    ;; See whether we can shorten Followup-To.
3692    (message-check 'shorten-followup-to
3693      (let ((newsgroups (message-fetch-field "newsgroups"))
3694            (followup-to (message-fetch-field "followup-to"))
3695            to)
3696        (when (and newsgroups
3697                   (string-match "," newsgroups)
3698                   (not followup-to)
3699                   (not
3700                    (zerop
3701                     (length
3702                      (setq to (completing-read
3703                                "Followups to: (default all groups) "
3704                                (mapcar (lambda (g) (list g))
3705                                        (cons "poster"
3706                                              (message-tokenize-header
3707                                               newsgroups)))))))))
3708          (goto-char (point-min))
3709          (insert "Followup-To: " to "\n"))
3710        t))
3711    ;; Check "Shoot me".
3712    (message-check 'shoot
3713      (if (re-search-forward
3714           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
3715          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3716        t))
3717    ;; Check for Approved.
3718    (message-check 'approved
3719      (if (re-search-forward "^Approved:" nil t)
3720          (y-or-n-p "The article contains an Approved header.  Really post? ")
3721        t))
3722    ;; Check the Message-ID header.
3723    (message-check 'message-id
3724      (let* ((case-fold-search t)
3725             (message-id (message-fetch-field "message-id" t)))
3726        (or (not message-id)
3727            ;; Is there an @ in the ID?
3728            (and (string-match "@" message-id)
3729                 ;; Is there a dot in the ID?
3730                 (string-match "@[^.]*\\." message-id)
3731                 ;; Does the ID end with a dot?
3732                 (not (string-match "\\.>" message-id)))
3733            (y-or-n-p
3734             (format "The Message-ID looks strange: \"%s\".  Really post? "
3735                     message-id)))))
3736    ;; Check the Newsgroups & Followup-To headers.
3737    (message-check 'existing-newsgroups
3738      (let* ((case-fold-search t)
3739             (newsgroups (message-fetch-field "newsgroups"))
3740             (followup-to (message-fetch-field "followup-to"))
3741             (groups (message-tokenize-header
3742                      (if followup-to
3743                          (concat newsgroups "," followup-to)
3744                        newsgroups)))
3745             (post-method (if (message-functionp message-post-method)
3746                              (funcall message-post-method)
3747                            message-post-method))
3748             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3749             ;; would probably involve a new nnoo function.
3750             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3751             (method (if (and (consp post-method)
3752                              (eq (car post-method) 'nnvirtual)
3753                              gnus-message-group-art)
3754                         (let ((group (car (nnvirtual-find-group-art
3755                                            (car gnus-message-group-art)
3756                                            (cdr gnus-message-group-art)))))
3757                           (gnus-find-method-for-group group))
3758                       post-method))
3759             (known-groups
3760              (mapcar (lambda (n)
3761                        (gnus-group-name-decode
3762                         (gnus-group-real-name n)
3763                         (gnus-group-name-charset method n)))
3764                      (gnus-groups-from-server method)))
3765             errors)
3766        (while groups
3767          (unless (or (equal (car groups) "poster")
3768                      (member (car groups) known-groups))
3769            (push (car groups) errors))
3770          (pop groups))
3771        (cond
3772         ;; Gnus is not running.
3773         ((or (not (and (boundp 'gnus-active-hashtb)
3774                        gnus-active-hashtb))
3775              (not (boundp 'gnus-read-active-file)))
3776          t)
3777         ;; We don't have all the group names.
3778         ((and (or (not gnus-read-active-file)
3779                   (eq gnus-read-active-file 'some))
3780               errors)
3781          (y-or-n-p
3782           (format
3783            "Really post to %s possibly unknown group%s: %s? "
3784            (if (= (length errors) 1) "this" "these")
3785            (if (= (length errors) 1) "" "s")
3786            (mapconcat 'identity errors ", "))))
3787         ;; There were no errors.
3788         ((not errors)
3789          t)
3790         ;; There are unknown groups.
3791         (t
3792          (y-or-n-p
3793           (format
3794            "Really post to %s unknown group%s: %s? "
3795            (if (= (length errors) 1) "this" "these")
3796            (if (= (length errors) 1) "" "s")
3797            (mapconcat 'identity errors ", ")))))))
3798    ;; Check the Newsgroups & Followup-To headers for syntax errors.
3799    (message-check 'valid-newsgroups
3800      (let ((case-fold-search t)
3801            (headers '("Newsgroups" "Followup-To"))
3802            header error)
3803        (while (and headers (not error))
3804          (when (setq header (mail-fetch-field (car headers)))
3805            (if (or
3806                 (not
3807                  (string-match
3808                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
3809                   header))
3810                 (memq
3811                  nil (mapcar
3812                       (lambda (g)
3813                         (not (string-match "\\.\\'\\|\\.\\." g)))
3814                       (message-tokenize-header header ","))))
3815                (setq error t)))
3816          (unless error
3817            (pop headers)))
3818        (if (not error)
3819            t
3820          (y-or-n-p
3821           (format "The %s header looks odd: \"%s\".  Really post? "
3822                   (car headers) header)))))
3823    (message-check 'repeated-newsgroups
3824      (let ((case-fold-search t)
3825            (headers '("Newsgroups" "Followup-To"))
3826            header error groups group)
3827        (while (and headers
3828                    (not error))
3829          (when (setq header (mail-fetch-field (pop headers)))
3830            (setq groups (message-tokenize-header header ","))
3831            (while (setq group (pop groups))
3832              (when (member group groups)
3833                (setq error group
3834                      groups nil)))))
3835        (if (not error)
3836            t
3837          (y-or-n-p
3838           (format "Group %s is repeated in headers.  Really post? " error)))))
3839    ;; Check the From header.
3840    (message-check 'from
3841      (let* ((case-fold-search t)
3842             (from (message-fetch-field "from"))
3843             ad)
3844        (cond
3845         ((not from)
3846          (message "There is no From line.  Posting is denied.")
3847          nil)
3848         ((or (not (string-match
3849                    "@[^\\.]*\\."
3850                    (setq ad (nth 1 (mail-extract-address-components
3851                                     from))))) ;larsi@ifi
3852              (string-match "\\.\\." ad) ;larsi@ifi..uio
3853              (string-match "@\\." ad)   ;larsi@.ifi.uio
3854              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3855              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3856              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
3857          (message
3858           "Denied posting -- the From looks strange: \"%s\"." from)
3859          nil)
3860         ((let ((addresses (rfc822-addresses from)))
3861            (while (and addresses
3862                        (not (eq (string-to-char (car addresses)) ?\()))
3863              (setq addresses (cdr addresses)))
3864            addresses)
3865          (message
3866           "Denied posting -- bad From address: \"%s\"." from)
3867          nil)
3868         (t t))))
3869    ;; Check the Reply-To header.
3870    (message-check 'reply-to
3871      (let* ((case-fold-search t)
3872             (reply-to (message-fetch-field "reply-to"))
3873             ad)
3874        (cond
3875         ((not reply-to)
3876          t)
3877         ((string-match "," reply-to)
3878          (y-or-n-p
3879           (format "Multiple Reply-To addresses: \"%s\". Really post? "
3880                   reply-to)))
3881         ((or (not (string-match
3882                    "@[^\\.]*\\."
3883                    (setq ad (nth 1 (mail-extract-address-components
3884                                     reply-to))))) ;larsi@ifi
3885              (string-match "\\.\\." ad) ;larsi@ifi..uio
3886              (string-match "@\\." ad)   ;larsi@.ifi.uio
3887              (string-match "\\.$" ad)   ;larsi@ifi.uio.
3888              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3889              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3890          (y-or-n-p
3891           (format
3892            "The Reply-To looks strange: \"%s\". Really post? "
3893            reply-to)))
3894         (t t))))))
3895
3896 (defun message-check-news-body-syntax ()
3897   (and
3898    ;; Check for long lines.
3899    (message-check 'long-lines
3900      (goto-char (point-min))
3901      (re-search-forward
3902       (concat "^" (regexp-quote mail-header-separator) "$"))
3903      (forward-line 1)
3904      (while (and
3905              (or (looking-at
3906                   mime-edit-tag-regexp)
3907                  (let ((p (point)))
3908                    (end-of-line)
3909                    (< (- (point) p) 80)))
3910              (zerop (forward-line 1))))
3911      (or (bolp)
3912          (eobp)
3913          (y-or-n-p
3914           "You have lines longer than 79 characters.  Really post? ")))
3915    ;; Check whether the article is empty.
3916    (message-check 'empty
3917      (goto-char (point-min))
3918      (re-search-forward
3919       (concat "^" (regexp-quote mail-header-separator) "$"))
3920      (forward-line 1)
3921      (let ((b (point)))
3922        (goto-char (point-max))
3923        (re-search-backward message-signature-separator nil t)
3924        (beginning-of-line)
3925        (or (re-search-backward "[^ \n\t]" b t)
3926            (if (message-gnksa-enable-p 'empty-article)
3927                (y-or-n-p "Empty article.  Really post? ")
3928              (message "Denied posting -- Empty article.")
3929              nil))))
3930    ;; Check for control characters.
3931    (message-check 'control-chars
3932      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3933          (y-or-n-p
3934           "The article contains control characters.  Really post? ")
3935        t))
3936    ;; Check 8bit characters.
3937    (message-check '8bit
3938      (message-check-8bit))
3939    ;; Check excessive size.
3940    (message-check 'size
3941      (if (> (buffer-size) 60000)
3942          (y-or-n-p
3943           (format "The article is %d octets long.  Really post? "
3944                   (buffer-size)))
3945        t))
3946    ;; Check whether any new text has been added.
3947    (message-check 'new-text
3948      (or
3949       (not message-checksum)
3950       (not (eq (message-checksum) message-checksum))
3951       (if (message-gnksa-enable-p 'quoted-text-only)
3952           (y-or-n-p
3953            "It looks like no new text has been added.  Really post? ")
3954         (message "Denied posting -- no new text has been added.")
3955         nil)))
3956    ;; Check the length of the signature.
3957    (message-check 'signature
3958      (goto-char (point-max))
3959      (if (> (count-lines (point) (point-max)) 5)
3960          (y-or-n-p
3961           (format
3962            "Your .sig is %d lines; it should be max 4.  Really post? "
3963            (1- (count-lines (point) (point-max)))))
3964        t))
3965    ;; Ensure that text follows last quoted portion.
3966    (message-check 'quoting-style
3967      (goto-char (point-max))
3968      (let ((no-problem t))
3969        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3970          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3971        (if no-problem
3972            t
3973          (if (message-gnksa-enable-p 'quoted-text-only)
3974              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3975            ;; Ensure that
3976            (goto-char (point-min))
3977            (re-search-forward
3978             (concat "^" (regexp-quote mail-header-separator) "$"))
3979            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3980                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3981              (message "Denied posting -- only quoted text.")
3982              nil)))))))
3983
3984 (defun message-check-mail-syntax ()
3985   "Check the syntax of the message."
3986   (save-excursion
3987     (save-restriction
3988       (widen)
3989       (and
3990        ;; We narrow to the headers and check them first.
3991        (save-excursion
3992          (save-restriction
3993            (message-narrow-to-headers)
3994            (message-check-mail-header-syntax)))
3995        ;; Check the body.
3996        (save-excursion
3997          (set-buffer message-edit-buffer)
3998          (message-check-mail-body-syntax))))))
3999
4000 (defun message-check-mail-header-syntax ()
4001   t)
4002
4003 (defun message-check-mail-body-syntax ()
4004   (and
4005    ;; Check 8bit characters.
4006    (message-check '8bit
4007      (message-check-8bit)
4008      )))
4009
4010 (defun message-check-8bit ()
4011   "Check the article contains 8bit characters."
4012   (save-excursion
4013     (set-buffer message-encoding-buffer)
4014     (message-narrow-to-headers)
4015     (let* ((case-fold-search t)
4016            (field-value (message-fetch-field "content-transfer-encoding")))
4017       (if (and field-value
4018                (member (downcase field-value) message-8bit-encoding-list))
4019           t
4020         (widen)
4021         (set-buffer (get-buffer-create " message syntax"))
4022         (erase-buffer)
4023         (goto-char (point-min))
4024         (set-buffer-multibyte nil)
4025         (insert-buffer message-encoding-buffer)
4026         (goto-char (point-min))
4027         (if (re-search-forward "[^\x00-\x7f]" nil t)
4028             (y-or-n-p
4029              "The article contains 8bit characters.  Really post? ")
4030           t)))))
4031
4032 (defun message-checksum ()
4033   "Return a \"checksum\" for the current buffer."
4034   (let ((sum 0))
4035     (save-excursion
4036       (goto-char (point-min))
4037       (re-search-forward
4038        (concat "^" (regexp-quote mail-header-separator) "$"))
4039       (while (not (eobp))
4040         (when (not (looking-at "[ \t\n]"))
4041           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4042                             (char-after))))
4043         (forward-char 1)))
4044     sum))
4045
4046 (defun message-do-fcc ()
4047   "Process Fcc headers in the current buffer."
4048   (let ((case-fold-search t)
4049         (coding-system-for-write 'raw-text)
4050         (output-coding-system 'raw-text)
4051         list file)
4052     (save-excursion
4053       (save-restriction
4054         (message-narrow-to-headers)
4055         (setq file (message-fetch-field "fcc" t)))
4056       (when file
4057         (set-buffer (get-buffer-create " *message temp*"))
4058         (erase-buffer)
4059         (insert-buffer-substring message-encoding-buffer)
4060         (save-restriction
4061           (message-narrow-to-headers)
4062           (while (setq file (message-fetch-field "fcc"))
4063             (push file list)
4064             (message-remove-header "fcc" nil t)))
4065         (goto-char (point-min))
4066         (when (re-search-forward
4067                (concat "^" (regexp-quote mail-header-separator) "$")
4068                nil t)
4069           (replace-match "" t t))
4070         ;; Process FCC operations.
4071         (while list
4072           (setq file (pop list))
4073           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4074               ;; Pipe the article to the program in question.
4075               (call-process-region (point-min) (point-max) shell-file-name
4076                                    nil nil nil shell-command-switch
4077                                    (match-string 1 file))
4078             ;; Save the article.
4079             (setq file (expand-file-name file))
4080             (unless (file-exists-p (file-name-directory file))
4081               (make-directory (file-name-directory file) t))
4082             (if (and message-fcc-handler-function
4083                      (not (eq message-fcc-handler-function 'rmail-output)))
4084                 (funcall message-fcc-handler-function file)
4085               (if (and (file-readable-p file) (mail-file-babyl-p file))
4086                   (rmail-output file 1 nil t)
4087                 (let ((mail-use-rfc822 t))
4088                   (rmail-output file 1 t t))))))
4089         (kill-buffer (current-buffer))))))
4090
4091 (defun message-output (filename)
4092   "Append this article to Unix/babyl mail file FILENAME."
4093   (if (and (file-readable-p filename)
4094            (mail-file-babyl-p filename))
4095       (gnus-output-to-rmail filename t)
4096     (gnus-output-to-mail filename t)))
4097
4098 (defun message-cleanup-headers ()
4099   "Do various automatic cleanups of the headers."
4100   ;; Remove empty lines in the header.
4101   (save-restriction
4102     (message-narrow-to-headers)
4103     ;; Remove blank lines.
4104     (while (re-search-forward "^[ \t]*\n" nil t)
4105       (replace-match "" t t))
4106
4107     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4108     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4109     ;; embedded line breaks.
4110     (goto-char (point-min))
4111     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4112       (save-restriction
4113         (narrow-to-region
4114          (point)
4115          (if (re-search-forward "^[^ \t]" nil t)
4116              (match-beginning 0)
4117            (forward-line 1)
4118            (point)))
4119         (goto-char (point-min))
4120         (while (re-search-forward "\n[ \t]+" nil t)
4121           (replace-match " " t t))      ;No line breaks (too confusing)
4122         (goto-char (point-min))
4123         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4124           (replace-match "," t t))
4125         (goto-char (point-min))
4126         ;; Remove trailing commas.
4127         (when (re-search-forward ",+$" nil t)
4128           (replace-match "" t t))))))
4129
4130 (defun message-make-date (&optional now)
4131   "Make a valid data header.
4132 If NOW, use that time instead."
4133   (let* ((now (or now (current-time)))
4134          (zone (nth 8 (decode-time now)))
4135          (sign "+"))
4136     (when (< zone 0)
4137       (setq sign "-")
4138       (setq zone (- zone)))
4139     (concat
4140      ;; The day name of the %a spec is locale-specific.  Pfff.
4141      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4142                                              parse-time-weekdays))))
4143      (format-time-string "%d" now)
4144      ;; The month name of the %b spec is locale-specific.  Pfff.
4145      (format " %s "
4146              (capitalize (car (rassoc (nth 4 (decode-time now))
4147                                       parse-time-months))))
4148      (format-time-string "%Y %H:%M:%S " now)
4149      ;; We do all of this because XEmacs doesn't have the %z spec.
4150      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4151
4152 (defun message-make-followup-subject (subject)
4153   "Make a followup Subject."
4154   (cond
4155    ((and (eq message-use-subject-re 'guess)
4156          (string-match message-subject-encoded-re-regexp subject))
4157     subject)
4158    (message-use-subject-re
4159     (concat "Re: " (message-strip-subject-re subject)))
4160    (t subject)))
4161
4162 (defun message-make-message-id ()
4163   "Make a unique Message-ID."
4164   (concat "<" (message-unique-id)
4165           (let ((psubject (save-excursion (message-fetch-field "subject")))
4166                 (psupersedes
4167                  (save-excursion (message-fetch-field "supersedes"))))
4168             (if (or
4169                  (and message-reply-headers
4170                       (mail-header-references message-reply-headers)
4171                       (mail-header-subject message-reply-headers)
4172                       psubject
4173                       (not (string=
4174                             (message-strip-subject-re
4175                              (mail-header-subject message-reply-headers))
4176                             (message-strip-subject-re psubject))))
4177                  (and psupersedes
4178                       (string-match "_-_@" psupersedes)))
4179                 "_-_" ""))
4180           "@" (message-make-fqdn) ">"))
4181
4182 (defvar message-unique-id-char nil)
4183
4184 ;; If you ever change this function, make sure the new version
4185 ;; cannot generate IDs that the old version could.
4186 ;; You might for example insert a "." somewhere (not next to another dot
4187 ;; or string boundary), or modify the "fsf" string.
4188 (defun message-unique-id ()
4189   ;; Don't use microseconds from (current-time), they may be unsupported.
4190   ;; Instead we use this randomly inited counter.
4191   (setq message-unique-id-char
4192         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4193            ;; (current-time) returns 16-bit ints,
4194            ;; and 2^16*25 just fits into 4 digits i base 36.
4195            (* 25 25)))
4196   (let ((tm (current-time)))
4197     (concat
4198      (if (memq system-type '(ms-dos emx vax-vms))
4199          (let ((user (downcase (user-login-name))))
4200            (while (string-match "[^a-z0-9_]" user)
4201              (aset user (match-beginning 0) ?_))
4202            user)
4203        (message-number-base36 (user-uid) -1))
4204      (message-number-base36 (+ (car   tm)
4205                                (lsh (% message-unique-id-char 25) 16)) 4)
4206      (message-number-base36 (+ (nth 1 tm)
4207                                (lsh (/ message-unique-id-char 25) 16)) 4)
4208      ;; Append the newsreader name, because while the generated
4209      ;; ID is unique to this newsreader, other newsreaders might
4210      ;; otherwise generate the same ID via another algorithm.
4211      ".fsf")))
4212
4213 (defun message-number-base36 (num len)
4214   (if (if (< len 0)
4215           (<= num 0)
4216         (= len 0))
4217       ""
4218     (concat (message-number-base36 (/ num 36) (1- len))
4219             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4220                                   (% num 36))))))
4221
4222 (defun message-make-organization ()
4223   "Make an Organization header."
4224   (let* ((organization
4225           (when message-user-organization
4226             (if (message-functionp message-user-organization)
4227                 (funcall message-user-organization)
4228               message-user-organization))))
4229     (save-excursion
4230       (message-set-work-buffer)
4231       (cond ((stringp organization)
4232              (insert organization))
4233             ((and (eq t organization)
4234                   message-user-organization-file
4235                   (file-exists-p message-user-organization-file))
4236              (insert-file-contents message-user-organization-file)))
4237       (goto-char (point-min))
4238       (while (re-search-forward "[\t\n]+" nil t)
4239         (replace-match "" t t))
4240       (unless (zerop (buffer-size))
4241         (buffer-string)))))
4242
4243 (defun message-make-lines ()
4244   "Count the number of lines and return numeric string."
4245   (save-excursion
4246     (save-restriction
4247       (widen)
4248       (message-goto-body)
4249       (int-to-string (count-lines (point) (point-max))))))
4250
4251 (defun message-make-in-reply-to ()
4252   "Return the In-Reply-To header for this message."
4253   (when message-reply-headers
4254     (let ((from (mail-header-from message-reply-headers))
4255           (date (mail-header-date message-reply-headers))
4256           (msg-id (mail-header-message-id message-reply-headers)))
4257       (when msg-id
4258         (concat msg-id
4259                 (when from
4260                   (let ((pair (std11-extract-address-components from)))
4261                     (concat "\n ("
4262                             (or (car pair) (cadr pair))
4263                             "'s message of \""
4264                             (if (or (not date) (string= date ""))
4265                                 "(unknown date)" date)
4266                             "\")"))))))))
4267
4268 (defun message-make-distribution ()
4269   "Make a Distribution header."
4270   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4271     (cond ((message-functionp message-distribution-function)
4272            (funcall message-distribution-function))
4273           (t orig-distribution))))
4274
4275 (defun message-make-expires ()
4276   "Return an Expires header based on `message-expires'."
4277   (let ((current (current-time))
4278         (future (* 1.0 message-expires 60 60 24)))
4279     ;; Add the future to current.
4280     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4281     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4282     (message-make-date current)))
4283
4284 (defun message-make-path ()
4285   "Return uucp path."
4286   (let ((login-name (user-login-name)))
4287     (cond ((null message-user-path)
4288            (concat (system-name) "!" login-name))
4289           ((stringp message-user-path)
4290            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4291            (concat message-user-path "!" login-name))
4292           (t login-name))))
4293
4294 (defun message-make-from ()
4295   "Make a From header."
4296   (let* ((style message-from-style)
4297          (login (message-make-address))
4298          (fullname
4299           (or (and (boundp 'user-full-name)
4300                    user-full-name)
4301               (user-full-name))))
4302     (when (string= fullname "&")
4303       (setq fullname (user-login-name)))
4304     (save-excursion
4305       (message-set-work-buffer)
4306       (cond
4307        ((or (null style)
4308             (equal fullname ""))
4309         (insert login))
4310        ((or (eq style 'angles)
4311             (and (not (eq style 'parens))
4312                  ;; Use angles if no quoting is needed, or if parens would
4313                  ;; need quoting too.
4314                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4315                      (let ((tmp (concat fullname nil)))
4316                        (while (string-match "([^()]*)" tmp)
4317                          (aset tmp (match-beginning 0) ?-)
4318                          (aset tmp (1- (match-end 0)) ?-))
4319                        (string-match "[\\()]" tmp)))))
4320         (insert fullname)
4321         (goto-char (point-min))
4322         ;; Look for a character that cannot appear unquoted
4323         ;; according to RFC 822.
4324         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
4325           ;; Quote fullname, escaping specials.
4326           (goto-char (point-min))
4327           (insert "\"")
4328           (while (re-search-forward "[\"\\]" nil 1)
4329             (replace-match "\\\\\\&" t))
4330           (insert "\""))
4331         (insert " <" login ">"))
4332        (t                               ; 'parens or default
4333         (insert login " (")
4334         (let ((fullname-start (point)))
4335           (insert fullname)
4336           (goto-char fullname-start)
4337           ;; RFC 822 says \ and nonmatching parentheses
4338           ;; must be escaped in comments.
4339           ;; Escape every instance of ()\ ...
4340           (while (re-search-forward "[()\\]" nil 1)
4341             (replace-match "\\\\\\&" t))
4342           ;; ... then undo escaping of matching parentheses,
4343           ;; including matching nested parentheses.
4344           (goto-char fullname-start)
4345           (while (re-search-forward
4346                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4347                   nil 1)
4348             (replace-match "\\1(\\3)" t)
4349             (goto-char fullname-start)))
4350         (insert ")")))
4351       (buffer-string))))
4352
4353 (defun message-make-sender ()
4354   "Return the \"real\" user address.
4355 This function tries to ignore all user modifications, and
4356 give as trustworthy answer as possible."
4357   (concat (user-login-name) "@" (system-name)))
4358
4359 (defun message-make-address ()
4360   "Make the address of the user."
4361   (or (message-user-mail-address)
4362       (concat (user-login-name) "@" (message-make-domain))))
4363
4364 (defun message-user-mail-address ()
4365   "Return the pertinent part of `user-mail-address'."
4366   (when user-mail-address
4367     (if (string-match " " user-mail-address)
4368         (nth 1 (std11-extract-address-components user-mail-address))
4369       user-mail-address)))
4370
4371 (defun message-make-fqdn ()
4372   "Return user's fully qualified domain name."
4373   (let ((system-name (system-name))
4374         (user-mail (message-user-mail-address)))
4375     (cond
4376      ((and (string-match "[^.]\\.[^.]" system-name)
4377            (not (string-match message-bogus-system-names system-name)))
4378       ;; `system-name' returned the right result.
4379       system-name)
4380      ;; Try `mail-host-address'.
4381      ((and (boundp 'mail-host-address)
4382            (stringp mail-host-address)
4383            (string-match "\\." mail-host-address))
4384       mail-host-address)
4385      ;; We try `user-mail-address' as a backup.
4386      ((and user-mail
4387            (string-match "\\." user-mail)
4388            (string-match "@\\(.*\\)\\'" user-mail))
4389       (match-string 1 user-mail))
4390      ;; Default to this bogus thing.
4391      (t
4392       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
4393
4394 (defun message-make-host-name ()
4395   "Return the name of the host."
4396   (let ((fqdn (message-make-fqdn)))
4397     (string-match "^[^.]+\\." fqdn)
4398     (substring fqdn 0 (1- (match-end 0)))))
4399
4400 (defun message-make-domain ()
4401   "Return the domain name."
4402   (or mail-host-address
4403       (message-make-fqdn)))
4404
4405 (defun message-make-mft ()
4406   "Return the Mail-Followup-To header."
4407   (let* ((msg-recipients (message-options-get 'message-recipients))
4408          (recipients
4409           (mapcar 'mail-strip-quoted-names
4410                   (message-tokenize-header msg-recipients)))
4411          (file-regexps
4412           (if message-subscribed-address-file
4413               (let (begin end item re)
4414                 (save-excursion
4415                   (with-temp-buffer
4416                     (insert-file-contents message-subscribed-address-file)
4417                     (while (not (eobp))
4418                       (setq begin (point))
4419                       (forward-line 1)
4420                       (setq end (point))
4421                       (if (bolp) (setq end (1- end)))
4422                       (setq item (regexp-quote (buffer-substring begin end)))
4423                       (if re (setq re (concat re "\\|" item))
4424                         (setq re (concat "\\`\\(" item))))
4425                     (and re (list (concat re "\\)\\'"))))))))
4426          (mft-regexps (apply 'append message-subscribed-regexps
4427                              (mapcar 'regexp-quote
4428                                      message-subscribed-addresses)
4429                              file-regexps
4430                              (mapcar 'funcall
4431                                      message-subscribed-address-functions))))
4432     (save-match-data
4433       (when (eval (apply 'append '(or)
4434                          (mapcar
4435                           (function (lambda (regexp)
4436                                       (mapcar
4437                                        (function (lambda (recipient)
4438                                                    `(string-match ,regexp
4439                                                                   ,recipient)))
4440                                        recipients)))
4441                           mft-regexps)))
4442         msg-recipients))))
4443
4444 ;; Dummy to avoid byte-compile warning.
4445 (defvar mule-version)
4446 (defvar emacs-beta-version)
4447 (defvar xemacs-codename)
4448 (defvar gnus-inviolable-extended-version)
4449
4450 (defun message-make-user-agent ()
4451   "Return user-agent info if the value `message-user-agent' is non-nil. If the
4452 \"User-Agent\" field has already exist, it's value will be added in the return
4453 string."
4454   (when message-user-agent
4455     (save-excursion
4456       (goto-char (point-min))
4457       (let ((case-fold-search t)
4458             user-agent start p end)
4459         (if (re-search-forward "^User-Agent:[\t ]*" nil t)
4460             (progn
4461               (setq start (match-beginning 0)
4462                     p (match-end 0)
4463                     end (std11-field-end)
4464                     user-agent (buffer-substring-no-properties p end))
4465               (delete-region start (1+ end))
4466               (concat message-user-agent " " user-agent))
4467           message-user-agent)))))
4468
4469 (defun message-generate-headers (headers)
4470   "Prepare article HEADERS.
4471 Headers already prepared in the buffer are not modified."
4472   (save-restriction
4473     (message-narrow-to-headers)
4474     (let* ((Date (message-make-date))
4475            (Message-ID (message-make-message-id))
4476            (Organization (message-make-organization))
4477            (From (message-make-from))
4478            (Path (message-make-path))
4479            (Subject nil)
4480            (Newsgroups nil)
4481            (In-Reply-To (message-make-in-reply-to))
4482            (To nil)
4483            (Distribution (message-make-distribution))
4484            (Lines (message-make-lines))
4485            (User-Agent (message-make-user-agent))
4486            (Expires (message-make-expires))
4487            (case-fold-search t)
4488            header value elem)
4489       ;; First we remove any old generated headers.
4490       (let ((headers message-deletable-headers))
4491         (unless (buffer-modified-p)
4492           (setq headers (delq 'Message-ID (copy-sequence headers))))
4493         (while headers
4494           (goto-char (point-min))
4495           (and (re-search-forward
4496                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4497                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4498                (message-delete-line))
4499           (pop headers)))
4500       ;; Go through all the required headers and see if they are in the
4501       ;; articles already.  If they are not, or are empty, they are
4502       ;; inserted automatically - except for Subject, Newsgroups and
4503       ;; Distribution.
4504       (while headers
4505         (goto-char (point-min))
4506         (setq elem (pop headers))
4507         (if (consp elem)
4508             (if (eq (car elem) 'optional)
4509                 (setq header (cdr elem))
4510               (setq header (car elem)))
4511           (setq header elem))
4512         (when (or (not (re-search-forward
4513                         (concat "^"
4514                                 (regexp-quote
4515                                  (downcase
4516                                   (if (stringp header)
4517                                       header
4518                                     (symbol-name header))))
4519                                 ":")
4520                         nil t))
4521                   (progn
4522                     ;; The header was found.  We insert a space after the
4523                     ;; colon, if there is none.
4524                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4525                     ;; Find out whether the header is empty...
4526                     (looking-at "[ \t]*\n[^ \t]")))
4527           ;; So we find out what value we should insert.
4528           (setq value
4529                 (cond
4530                  ((and (consp elem) (eq (car elem) 'optional))
4531                   ;; This is an optional header.  If the cdr of this
4532                   ;; is something that is nil, then we do not insert
4533                   ;; this header.
4534                   (setq header (cdr elem))
4535                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
4536                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
4537                  ((consp elem)
4538                   ;; The element is a cons.  Either the cdr is a
4539                   ;; string to be inserted verbatim, or it is a
4540                   ;; function, and we insert the value returned from
4541                   ;; this function.
4542                   (or (and (stringp (cdr elem)) (cdr elem))
4543                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
4544                  ((and (boundp header) (symbol-value header))
4545                   ;; The element is a symbol.  We insert the value
4546                   ;; of this symbol, if any.
4547                   (symbol-value header))
4548                  ((not (message-check-element header))
4549                   ;; We couldn't generate a value for this header,
4550                   ;; so we just ask the user.
4551                   (read-from-minibuffer
4552                    (format "Empty header for %s; enter value: " header)))))
4553           ;; Finally insert the header.
4554           (when (and value
4555                      (not (equal value "")))
4556             (save-excursion
4557               (if (bolp)
4558                   (progn
4559                     ;; This header didn't exist, so we insert it.
4560                     (goto-char (point-max))
4561                     (insert (if (stringp header) header (symbol-name header))
4562                             ": " value)
4563                     (unless (bolp)
4564                       (insert "\n"))
4565                     (forward-line -1))
4566                 ;; The value of this header was empty, so we clear
4567                 ;; totally and insert the new value.
4568                 (delete-region (point) (gnus-point-at-eol))
4569                 (insert value)
4570                 (when (bolp)
4571                   (delete-char -1)))
4572               ;; Add the deletable property to the headers that require it.
4573               (and (memq header message-deletable-headers)
4574                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4575                    (add-text-properties
4576                     (point) (match-end 0)
4577                     '(message-deletable t face italic) (current-buffer)))))))
4578       ;; Insert new Sender if the From is strange.
4579       (let ((from (message-fetch-field "from"))
4580             (sender (message-fetch-field "sender"))
4581             (secure-sender (message-make-sender)))
4582         (when (and from
4583                    (not (message-check-element 'sender))
4584                    (not (string=
4585                          (downcase
4586                           (cadr (std11-extract-address-components from)))
4587                          (downcase secure-sender)))
4588                    (or (null sender)
4589                        (not
4590                         (string=
4591                          (downcase
4592                           (cadr (std11-extract-address-components sender)))
4593                          (downcase secure-sender)))))
4594           (goto-char (point-min))
4595           ;; Rename any old Sender headers to Original-Sender.
4596           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4597             (beginning-of-line)
4598             (insert "Original-")
4599             (beginning-of-line))
4600           (when (or (message-news-p)
4601                     (string-match "@.+\\.." secure-sender))
4602             (insert "Sender: " secure-sender "\n")))))))
4603
4604 (defun message-insert-courtesy-copy ()
4605   "Insert a courtesy message in mail copies of combined messages."
4606   (let (newsgroups)
4607     (save-excursion
4608       (save-restriction
4609         (message-narrow-to-headers)
4610         (when (setq newsgroups (message-fetch-field "newsgroups"))
4611           (goto-char (point-max))
4612           (insert "Posted-To: " newsgroups "\n")))
4613       (forward-line 1)
4614       (when message-courtesy-message
4615         (cond
4616          ((string-match "%s" message-courtesy-message)
4617           (insert (format message-courtesy-message newsgroups)))
4618          (t
4619           (insert message-courtesy-message)))))))
4620
4621 ;;;
4622 ;;; Setting up a message buffer
4623 ;;;
4624
4625 (defun message-fill-address (header value)
4626   (save-restriction
4627     (narrow-to-region (point) (point))
4628     (insert (capitalize (symbol-name header))
4629             ": "
4630             (if (consp value) (car value) value)
4631             "\n")
4632     (narrow-to-region (point-min) (1- (point-max)))
4633     (let (quoted last)
4634       (goto-char (point-min))
4635       (while (not (eobp))
4636         (skip-chars-forward "^,\"" (point-max))
4637         (if (or (eq (char-after) ?,)
4638                 (eobp))
4639             (when (not quoted)
4640               (if (and (> (current-column) 78)
4641                        last)
4642                   (save-excursion
4643                     (goto-char last)
4644                     (looking-at "[ \t]*")
4645                     (replace-match "\n " t t)))
4646               (setq last (1+ (point))))
4647           (setq quoted (not quoted)))
4648         (unless (eobp)
4649           (forward-char 1))))
4650     (goto-char (point-max))
4651     (widen)
4652     (forward-line 1)))
4653
4654 (defun message-fill-references (header value)
4655   (insert (capitalize (symbol-name header))
4656           ": "
4657           (std11-fill-msg-id-list-string
4658            (if (consp value) (car value) value))
4659           "\n"))
4660
4661 (defun message-fill-header (header value)
4662   (let ((begin (point))
4663         (fill-column 78)
4664         (fill-prefix " "))
4665     (insert (capitalize (symbol-name header))
4666             ": "
4667             (if (consp value) (car value) value)
4668             "\n")
4669     (save-restriction
4670       (narrow-to-region begin (point))
4671       (fill-region-as-paragraph begin (point))
4672       ;; Tapdance around looong Message-IDs.
4673       (forward-line -1)
4674       (when (looking-at "[ \t]*$")
4675         (message-delete-line))
4676       (goto-char begin)
4677       (re-search-forward ":" nil t)
4678       (when (looking-at "\n[ \t]+")
4679         (replace-match " " t t))
4680       (goto-char (point-max)))))
4681
4682 (defun message-shorten-1 (list cut surplus)
4683   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4684   (setcdr (nthcdr (- cut 2) list)
4685           (nthcdr (+ (- cut 2) surplus 1) list)))
4686
4687 (defun message-shorten-references (header references)
4688   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4689 If folding is disallowed, also check that the REFERENCES are less
4690 than 988 characters long, and if they are not, trim them until they are."
4691   (let ((maxcount 21)
4692         (count 0)
4693         (cut 2)
4694         refs)
4695     (with-temp-buffer
4696       (insert references)
4697       (goto-char (point-min))
4698       ;; Cons a list of valid references.
4699       (while (re-search-forward "<[^>]+>" nil t)
4700         (push (match-string 0) refs))
4701       (setq refs (nreverse refs)
4702             count (length refs)))
4703
4704     ;; If the list has more than MAXCOUNT elements, trim it by
4705     ;; removing the CUTth element and the required number of
4706     ;; elements that follow.
4707     (when (> count maxcount)
4708       (let ((surplus (- count maxcount)))
4709         (message-shorten-1 refs cut surplus)
4710         (decf count surplus)))
4711
4712     ;; If folding is disallowed, make sure the total length (including
4713     ;; the spaces between) will be less than MAXSIZE characters.
4714     ;;
4715     ;; Only disallow folding for News messages. At this point the headers
4716     ;; have not been generated, thus we use message-this-is-news directly.
4717     (when (and message-this-is-news message-cater-to-broken-inn)
4718       (let ((maxsize 988)
4719             (totalsize (+ (apply #'+ (mapcar #'length refs))
4720                           (1- count)))
4721             (surplus 0)
4722             (ptr (nthcdr (1- cut) refs)))
4723         ;; Decide how many elements to cut off...
4724         (while (> totalsize maxsize)
4725           (decf totalsize (1+ (length (car ptr))))
4726           (incf surplus)
4727           (setq ptr (cdr ptr)))
4728         ;; ...and do it.
4729         (when (> surplus 0)
4730           (message-shorten-1 refs cut surplus))))
4731
4732     ;; Finally, collect the references back into a string and insert
4733     ;; it into the buffer.
4734     (let ((refstring (mapconcat #'identity refs " ")))
4735       (if (and message-this-is-news message-cater-to-broken-inn)
4736           (insert (capitalize (symbol-name header)) ": "
4737                   refstring "\n")
4738         (message-fill-header header refstring)))))
4739
4740 (defun message-position-point ()
4741   "Move point to where the user probably wants to find it."
4742   (message-narrow-to-headers)
4743   (cond
4744    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
4745     (search-backward ":" )
4746     (widen)
4747     (forward-char 1)
4748     (if (eq (char-after) ? )
4749         (forward-char 1)
4750       (insert " ")))
4751    (t
4752     (goto-char (point-max))
4753     (widen)
4754     (forward-line 1)
4755     (unless (looking-at "$")
4756       (forward-line 2)))
4757    (sit-for 0)))
4758
4759 (defun message-beginning-of-line (&optional n)
4760   "Move point to beginning of header value or to beginning of line."
4761   (interactive "p")
4762   (if (message-point-in-header-p)
4763       (let* ((here (point))
4764              (bol (progn (beginning-of-line n) (point)))
4765              (eol (gnus-point-at-eol))
4766              (eoh (re-search-forward ": *" eol t)))
4767         (if (or (not eoh) (equal here eoh))
4768             (goto-char bol)
4769           (goto-char eoh)))
4770     (beginning-of-line n)))
4771
4772 (defun message-buffer-name (type &optional to group)
4773   "Return a new (unique) buffer name based on TYPE and TO."
4774   (cond
4775    ;; Generate a new buffer name The Message Way.
4776    ((eq message-generate-new-buffers 'unique)
4777     (generate-new-buffer-name
4778      (concat "*" type
4779              (if to
4780                  (concat " to "
4781                          (or (car (std11-extract-address-components to))
4782                              to) "")
4783                "")
4784              (if (and group (not (string= group ""))) (concat " on " group) "")
4785              "*")))
4786    ;; Check whether `message-generate-new-buffers' is a function,
4787    ;; and if so, call it.
4788    ((message-functionp message-generate-new-buffers)
4789     (funcall message-generate-new-buffers type to group))
4790    ((eq message-generate-new-buffers 'unsent)
4791     (generate-new-buffer-name
4792      (concat "*unsent " type
4793              (if to
4794                  (concat " to "
4795                          (or (car (mail-extract-address-components to))
4796                              to) "")
4797                "")
4798              (if (and group (not (string= group ""))) (concat " on " group) "")
4799              "*")))
4800    ;; Use standard name.
4801    (t
4802     (format "*%s message*" type))))
4803
4804 (defmacro message-pop-to-buffer-1 (buffer)
4805   `(if pop-up-frames
4806        (let (special-display-buffer-names
4807              special-display-regexps
4808              same-window-buffer-names
4809              same-window-regexps)
4810          (pop-to-buffer ,buffer))
4811      (pop-to-buffer ,buffer)))
4812
4813 (defun message-pop-to-buffer (name)
4814   "Pop to buffer NAME, and warn if it already exists and is modified."
4815   (let ((buffer (get-buffer name))
4816         (pop-up-frames (and (or (static-if (featurep 'xemacs)
4817                                     (device-on-window-system-p)
4818                                   window-system)
4819                                 (>= emacs-major-version 20))
4820                             message-use-multi-frames)))
4821     (if (and buffer
4822              (buffer-name buffer))
4823         (progn
4824           (message-pop-to-buffer-1 buffer)
4825           (when (and (buffer-modified-p)
4826                      (not (y-or-n-p
4827                            "Message already being composed; erase? ")))
4828             (error "Message being composed")))
4829       (message-pop-to-buffer-1 name))
4830     (erase-buffer)
4831     (message-mode)
4832     (when pop-up-frames
4833       (set (make-local-variable 'message-original-frame) (selected-frame)))))
4834
4835 (defun message-do-send-housekeeping ()
4836   "Kill old message buffers."
4837   ;; We might have sent this buffer already.  Delete it from the
4838   ;; list of buffers.
4839   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
4840   (while (and message-max-buffers
4841               message-buffer-list
4842               (>= (length message-buffer-list) message-max-buffers))
4843     ;; Kill the oldest buffer -- unless it has been changed.
4844     (let ((buffer (pop message-buffer-list)))
4845       (when (and (buffer-name buffer)
4846                  (not (buffer-modified-p buffer)))
4847         (kill-buffer buffer))))
4848   ;; Rename the buffer.
4849   (if message-send-rename-function
4850       (funcall message-send-rename-function)
4851     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
4852     (when (string-match
4853            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
4854            (buffer-name))
4855       (let ((name (match-string 2 (buffer-name)))
4856             to group)
4857         (if (not (or (null name)
4858                      (string-equal name "mail")
4859                      (string-equal name "news")))
4860             (setq name (concat "*sent " name "*"))
4861           (message-narrow-to-headers)
4862           (setq to (message-fetch-field "to"))
4863           (setq group (message-fetch-field "newsgroups"))
4864           (widen)
4865           (setq name
4866                 (cond
4867                  (to (concat "*sent mail to "
4868                              (or (car (mail-extract-address-components to))
4869                                  to) "*"))
4870                  ((and group (not (string= group "")))
4871                   (concat "*sent news on " group "*"))
4872                  (t "*sent mail*"))))
4873         (unless (string-equal name (buffer-name))
4874           (rename-buffer name t)))))
4875   ;; Push the current buffer onto the list.
4876   (when message-max-buffers
4877     (setq message-buffer-list
4878           (nconc message-buffer-list (list (current-buffer))))))
4879
4880 (defun message-mail-user-agent ()
4881   (let ((mua (cond
4882               ((not message-mail-user-agent) nil)
4883               ((eq message-mail-user-agent t) mail-user-agent)
4884               (t message-mail-user-agent))))
4885     (if (memq mua '(message-user-agent gnus-user-agent))
4886         nil
4887       mua)))
4888
4889 (defun message-setup (headers &optional replybuffer actions switch-function)
4890   (let ((mua (message-mail-user-agent))
4891         subject to field yank-action)
4892     (if (not (and message-this-is-mail mua))
4893         (message-setup-1 headers replybuffer actions)
4894       (if replybuffer
4895           (setq yank-action (list 'insert-buffer replybuffer)))
4896       (setq headers (copy-sequence headers))
4897       (setq field (assq 'Subject headers))
4898       (when field
4899         (setq subject (cdr field))
4900         (setq headers (delq field headers)))
4901       (setq field (assq 'To headers))
4902       (when field
4903         (setq to (cdr field))
4904         (setq headers (delq field headers)))
4905       (let ((mail-user-agent mua))
4906         (compose-mail to subject
4907                       (mapcar (lambda (item)
4908                                 (cons
4909                                  (format "%s" (car item))
4910                                  (cdr item)))
4911                               headers)
4912                       nil switch-function yank-action actions)))))
4913
4914 (defun message-setup-1 (headers &optional replybuffer actions)
4915   (dolist (action actions)
4916     (condition-case nil
4917         (add-to-list 'message-send-actions
4918                      `(apply ',(car action) ',(cdr action)))))
4919   (setq message-reply-buffer
4920         (or (message-get-parameter 'reply-buffer)
4921             replybuffer))
4922   (goto-char (point-min))
4923   ;; Insert all the headers.
4924   (mail-header-format
4925    (let ((h headers)
4926          (alist message-header-format-alist))
4927      (while h
4928        (unless (assq (caar h) message-header-format-alist)
4929          (push (list (caar h)) alist))
4930        (pop h))
4931      alist)
4932    headers)
4933   (delete-region (point) (progn (forward-line -1) (point)))
4934   (when message-default-headers
4935     (insert message-default-headers)
4936     (or (bolp) (insert ?\n)))
4937   (put-text-property
4938    (point)
4939    (progn
4940      (insert mail-header-separator "\n")
4941      (1- (point)))
4942    'read-only nil)
4943   (forward-line -1)
4944   (when (message-news-p)
4945     (when message-default-news-headers
4946       (insert message-default-news-headers)
4947       (or (bolp) (insert ?\n)))
4948     (when message-generate-headers-first
4949       (message-generate-headers
4950        (delq 'Lines
4951              (delq 'Subject
4952                    (copy-sequence message-required-news-headers))))))
4953   (when (message-mail-p)
4954     (when message-default-mail-headers
4955       (insert message-default-mail-headers)
4956       (or (bolp) (insert ?\n)))
4957     (when message-generate-headers-first
4958       (message-generate-headers
4959        (delq 'Lines
4960              (delq 'Subject
4961                    (copy-sequence message-required-mail-headers))))))
4962   (run-hooks 'message-signature-setup-hook)
4963   (message-insert-signature)
4964   (save-restriction
4965     (message-narrow-to-headers)
4966     (if message-alternative-emails
4967         (message-use-alternative-email-as-from))
4968     (run-hooks 'message-header-setup-hook))
4969   (set-buffer-modified-p nil)
4970   (setq buffer-undo-list nil)
4971   (run-hooks 'message-setup-hook)
4972   (message-position-point)
4973   (undo-boundary))
4974
4975 (defun message-set-auto-save-file-name ()
4976   "Associate the message buffer with a file in the drafts directory."
4977   (when message-auto-save-directory
4978     (unless (file-directory-p
4979              (directory-file-name message-auto-save-directory))
4980       (gnus-make-directory message-auto-save-directory))
4981     (if (gnus-alive-p)
4982         (setq message-draft-article
4983               (nndraft-request-associate-buffer "drafts"))
4984       (setq buffer-file-name (expand-file-name
4985                               (if (memq system-type
4986                                         '(ms-dos ms-windows windows-nt
4987                                                  cygwin32 win32 w32
4988                                                  mswindows))
4989                                   "message"
4990                                 "*message*")
4991                               message-auto-save-directory))
4992       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
4993     (clear-visited-file-modtime)
4994     (static-if (boundp 'MULE)
4995         (set-file-coding-system message-draft-coding-system)
4996       (setq buffer-file-coding-system message-draft-coding-system))))
4997
4998 (defun message-disassociate-draft ()
4999   "Disassociate the message buffer from the drafts directory."
5000   (when message-draft-article
5001     (nndraft-request-expire-articles
5002      (list message-draft-article) "drafts" nil t)))
5003
5004 (defun message-insert-headers ()
5005   "Generate the headers for the article."
5006   (interactive)
5007   (save-excursion
5008     (save-restriction
5009       (message-narrow-to-headers)
5010       (when (message-news-p)
5011         (message-generate-headers
5012          (delq 'Lines
5013                (delq 'Subject
5014                      (copy-sequence message-required-news-headers)))))
5015       (when (message-mail-p)
5016         (message-generate-headers
5017          (delq 'Lines
5018                (delq 'Subject
5019                      (copy-sequence message-required-mail-headers))))))))
5020
5021 \f
5022
5023 ;;;
5024 ;;; Commands for interfacing with message
5025 ;;;
5026
5027 ;;;###autoload
5028 (defun message-mail (&optional to subject
5029                                other-headers continue switch-function
5030                                yank-action send-actions)
5031   "Start editing a mail message to be sent.
5032 OTHER-HEADERS is an alist of header/value pairs."
5033   (interactive)
5034   (let ((message-this-is-mail t) replybuffer)
5035     (unless (message-mail-user-agent)
5036       (message-pop-to-buffer (message-buffer-name "mail" to)))
5037     ;; FIXME: message-mail should do something if YANK-ACTION is not
5038     ;; insert-buffer.
5039     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5040          (setq replybuffer (nth 1 yank-action)))
5041     (message-setup
5042      (nconc
5043       `((To . ,(or to "")) (Subject . ,(or subject "")))
5044       (when other-headers other-headers))
5045      replybuffer send-actions)
5046     ;; FIXME: Should return nil if failure.
5047     t))
5048
5049 ;;;###autoload
5050 (defun message-news (&optional newsgroups subject)
5051   "Start editing a news article to be sent."
5052   (interactive)
5053   (let ((message-this-is-news t))
5054     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
5055     (message-setup `((Newsgroups . ,(or newsgroups ""))
5056                      (Subject . ,(or subject ""))))))
5057
5058 (defun message-get-reply-headers (wide &optional to-address)
5059   (let (follow-to mct never-mct to cc author mft recipients)
5060     ;; Find all relevant headers we need.
5061     (let ((mrt (when message-use-mail-reply-to
5062                  (message-fetch-field "mail-reply-to")))
5063           (reply-to (message-fetch-field "reply-to")))
5064       (setq to (message-fetch-field "to")
5065             cc (message-fetch-field "cc")
5066             mct (when message-use-mail-copies-to
5067                   (message-fetch-field "mail-copies-to"))
5068             author (or mrt
5069                        reply-to
5070                        (message-fetch-field "from")
5071                        "")
5072             mft (when (and (not (or to-address mrt reply-to))
5073                            message-use-mail-followup-to)
5074                   (message-fetch-field "mail-followup-to"))))
5075
5076     (save-match-data
5077       ;; Handle special values of Mail-Copies-To.
5078       (when mct
5079         (cond ((or (equal (downcase mct) "never")
5080                    (equal (downcase mct) "nobody"))
5081                (when (or (not (eq message-use-mail-copies-to 'ask))
5082                          (message-y-or-n-p
5083                           (concat "Obey Mail-Copies-To: never? ") t "\
5084 You should normally obey the Mail-Copies-To: header.
5085
5086         `Mail-Copies-To: " mct "'
5087 directs you not to send your response to the author."))
5088                  (setq never-mct t))
5089                (setq mct nil))
5090               ((or (equal (downcase mct) "always")
5091                    (equal (downcase mct) "poster"))
5092                (if (or (not (eq message-use-mail-copies-to 'ask))
5093                        (message-y-or-n-p
5094                         (concat "Obey Mail-Copies-To: always? ") t "\
5095 You should normally obey the Mail-Copies-To: header.
5096
5097         `Mail-Copies-To: " mct "'
5098 sends a copy of your response to the author."))
5099                    (setq mct author)
5100                  (setq mct nil)))
5101               ((and (eq message-use-mail-copies-to 'ask)
5102                     (not (message-y-or-n-p
5103                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5104 You should normally obey the Mail-Copies-To: header.
5105
5106         `Mail-Copies-To: " mct "'
5107 sends a copy of your response to " (if (string-match "," mct)
5108                                        "the specified addresses"
5109                                      "that address") ".")))
5110                (setq mct nil))))
5111
5112       ;; Build (textual) list of new recipient addresses.
5113       (cond
5114        ((not wide)
5115         (setq recipients (concat ", " author)))
5116        ((and mft
5117              (string-match "[^ \t,]" mft)
5118              (or (not (eq message-use-mail-followup-to 'ask))
5119                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5120 You should normally obey the Mail-Followup-To: header.  In this
5121 article, it has the value of
5122
5123 " mft "
5124
5125 which directs your response to " (if (string-match "," mft)
5126                                      "the specified addresses"
5127                                    "that address only") ".
5128
5129 Most commonly, Mail-Followup-To is used by a mailing list poster to
5130 express that responses should be sent to just the list, and not the
5131 poster as well.
5132
5133 If a message is posted to several mailing lists, Mail-Followup-To may
5134 also be used to direct the following discussion to one list only,
5135 because discussions that are spread over several lists tend to be
5136 fragmented and very difficult to follow.
5137
5138 Also, some source/announcement lists are not intended for discussion;
5139 responses here are directed to other addresses.")))
5140         (setq recipients (concat ", " mft)))
5141        (to-address
5142         (setq recipients (concat ", " to-address))
5143         ;; If the author explicitly asked for a copy, we don't deny it to them.
5144         (if mct (setq recipients (concat recipients ", " mct))))
5145        (t
5146         (setq recipients (if never-mct "" (concat ", " author)))
5147         (if to  (setq recipients (concat recipients ", " to)))
5148         (if cc  (setq recipients (concat recipients ", " cc)))
5149         (if mct (setq recipients (concat recipients ", " mct)))))
5150       (if (>= (length recipients) 2)
5151           ;; Strip the leading ", ".
5152           (setq recipients (substring recipients 2)))
5153       ;; Squeeze whitespace.
5154       (while (string-match "[ \t][ \t]+" recipients)
5155         (setq recipients (replace-match " " t t recipients)))
5156       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5157       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5158         (setq recipients (rmail-dont-reply-to recipients)))
5159       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5160       (if (string-equal recipients "")
5161           (setq recipients author))
5162       ;; Convert string to a list of (("foo@bar" . "Name <foo@bar>") ...).
5163       (setq recipients
5164             (mapcar
5165              (lambda (addr)
5166                (cons (mail-strip-quoted-names addr) addr))
5167              (message-tokenize-header recipients)))
5168       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5169       (let ((s recipients))
5170         (while s
5171           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5172       ;; Build the header alist.  Allow the user to be asked whether
5173       ;; or not to reply to all recipients in a wide reply.
5174       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5175       (when (and recipients
5176                  (or (not message-wide-reply-confirm-recipients)
5177                      (y-or-n-p "Reply to all recipients? ")))
5178         (setq recipients (mapconcat
5179                           (lambda (addr) (cdr addr)) recipients ", "))
5180         (if (string-match "^ +" recipients)
5181             (setq recipients (substring recipients (match-end 0))))
5182         (push (cons 'Cc recipients) follow-to)))
5183     follow-to))
5184
5185 ;;;###autoload
5186 (defun message-reply (&optional to-address wide)
5187   "Start editing a reply to the article in the current buffer."
5188   (interactive)
5189   (require 'gnus-sum)                   ; for gnus-list-identifiers
5190   (let ((cur (current-buffer))
5191         from subject date
5192         references message-id follow-to
5193         (inhibit-point-motion-hooks t)
5194         (message-this-is-mail t)
5195         gnus-warning in-reply-to)
5196     (save-restriction
5197       (message-narrow-to-head-1)
5198       ;; Allow customizations to have their say.
5199       (if (not wide)
5200           ;; This is a regular reply.
5201           (when (message-functionp message-reply-to-function)
5202             (save-excursion
5203               (setq follow-to (funcall message-reply-to-function))))
5204         ;; This is a followup.
5205         (when (message-functionp message-wide-reply-to-function)
5206           (save-excursion
5207             (setq follow-to
5208                   (funcall message-wide-reply-to-function)))))
5209       (setq message-id (message-fetch-field "message-id" t)
5210             references (message-fetch-field "references")
5211             date (message-fetch-field "date")
5212             from (message-fetch-field "from")
5213             subject (or (message-fetch-field "subject") "none"))
5214       (when gnus-list-identifiers
5215         (setq subject (message-strip-list-identifiers subject)))
5216       (setq subject (message-make-followup-subject subject))
5217
5218       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5219                  (string-match "<[^>]+>" gnus-warning))
5220         (setq message-id (match-string 0 gnus-warning)))
5221
5222       (unless follow-to
5223         (setq follow-to (message-get-reply-headers wide to-address)))
5224
5225       ;; Get the references from "In-Reply-To" field if there were
5226       ;; no references and "In-Reply-To" field looks promising.
5227       (unless references
5228         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
5229                    (string-match "<[^>]+>" in-reply-to))
5230           (setq references (match-string 0 in-reply-to)))))
5231
5232     (unless (message-mail-user-agent)
5233       (message-pop-to-buffer
5234        (message-buffer-name
5235         (if wide "wide reply" "reply") from
5236         (if wide to-address nil))))
5237
5238     (setq message-reply-headers
5239           (make-full-mail-header-from-decoded-header
5240            0 subject from date message-id references 0 0 ""))
5241
5242     (message-setup
5243      `((Subject . ,subject)
5244        ,@follow-to
5245        ,@(if (or references message-id)
5246              `((References . ,(concat (or references "") (and references " ")
5247                                       (or message-id ""))))
5248            nil))
5249      cur)))
5250
5251 ;;;###autoload
5252 (defun message-wide-reply (&optional to-address)
5253   "Make a \"wide\" reply to the message in the current buffer."
5254   (interactive)
5255   (message-reply to-address t))
5256
5257 ;;;###autoload
5258 (defun message-followup (&optional to-newsgroups)
5259   "Follow up to the message in the current buffer.
5260 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5261   (interactive)
5262   (require 'gnus-sum)                   ; for gnus-list-identifiers
5263   (let ((cur (current-buffer))
5264         from subject date reply-to mrt mct mft
5265         references message-id follow-to
5266         (inhibit-point-motion-hooks t)
5267         (message-this-is-news t)
5268         followup-to distribution newsgroups gnus-warning posted-to)
5269     (save-restriction
5270       (message-narrow-to-head)
5271       (when (message-functionp message-followup-to-function)
5272         (setq follow-to
5273               (funcall message-followup-to-function)))
5274       (setq from (message-fetch-field "from")
5275             date (message-fetch-field "date")
5276             subject (or (message-fetch-field "subject") "none")
5277             references (message-fetch-field "references")
5278             message-id (message-fetch-field "message-id" t)
5279             followup-to (message-fetch-field "followup-to")
5280             newsgroups (message-fetch-field "newsgroups")
5281             posted-to (message-fetch-field "posted-to")
5282             reply-to (message-fetch-field "reply-to")
5283             mrt (when message-use-mail-reply-to
5284                   (message-fetch-field "mail-reply-to"))
5285             distribution (message-fetch-field "distribution")
5286             mct (when message-use-mail-copies-to
5287                   (message-fetch-field "mail-copies-to"))
5288             mft (when message-use-mail-followup-to
5289                   (message-fetch-field "mail-followup-to")))
5290       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5291                  (string-match "<[^>]+>" gnus-warning))
5292         (setq message-id (match-string 0 gnus-warning)))
5293       ;; Remove bogus distribution.
5294       (when (and (stringp distribution)
5295                  (let ((case-fold-search t))
5296                    (string-match "world" distribution)))
5297         (setq distribution nil))
5298       (if gnus-list-identifiers
5299           (setq subject (message-strip-list-identifiers subject)))
5300       (setq subject (message-make-followup-subject subject))
5301       (widen))
5302
5303     ;; Handle special values of Mail-Copies-To.
5304     (when mct
5305       (cond
5306        ((and (or (equal (downcase mct) "never")
5307                  (equal (downcase mct) "nobody")))
5308         (setq mct nil))
5309        ((and (or (equal (downcase mct) "always")
5310                  (equal (downcase mct) "poster")))
5311         (if (or (not (eq message-use-mail-copies-to 'ask))
5312                 (message-y-or-n-p
5313                  (concat "Obey Mail-Copies-To: always? ") t "\
5314 You should normally obey the Mail-Copies-To: header.
5315
5316         `Mail-Copies-To: " mct "'
5317 sends a copy of your response to the author."))
5318             (setq mct (or mrt reply-to from))
5319           (setq mct nil)))
5320        ((and (eq message-use-mail-copies-to 'ask)
5321              (not
5322               (message-y-or-n-p
5323                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
5324 You should normally obey the Mail-Copies-To: header.
5325
5326         `Mail-Copies-To: " mct "'
5327 sends a copy of your response to " (if (string-match "," mct)
5328                                        "the specified addresses"
5329                                      "that address") ".")))
5330         (setq mct nil))))
5331
5332     (unless follow-to
5333       (cond
5334        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
5335        ;; Handle Followup-To.
5336        (followup-to
5337         (cond
5338          ((equal (downcase followup-to) "poster")
5339           (if (or (and followup-to (eq message-use-followup-to 'use))
5340                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
5341 You should normally obey the Followup-To: header.
5342
5343         `Followup-To: poster'
5344 sends your response via e-mail instead of news.
5345
5346 A typical situation where `Followup-To: poster' is used is when the author
5347 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5348               (setq message-this-is-news nil
5349                     distribution nil
5350                     follow-to (list (cons 'To (or mrt reply-to from ""))))
5351             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
5352          (t
5353           (if (or (equal followup-to newsgroups)
5354                   (not (and followup-to (eq message-use-followup-to 'ask)))
5355                   (message-y-or-n-p
5356                    (concat "Obey Followup-To: " followup-to "? ") t "\
5357 You should normally obey the Followup-To: header.
5358
5359         `Followup-To: " followup-to "'
5360 directs your response to " (if (string-match "," followup-to)
5361                                "the specified newsgroups"
5362                              "that newsgroup only") ".
5363
5364 If a message is posted to several newsgroups, Followup-To is often
5365 used to direct the following discussion to one newsgroup only,
5366 because discussions that are spread over several newsgroup tend to
5367 be fragmented and very difficult to follow.
5368
5369 Also, some source/announcement newsgroups are not intended for discussion;
5370 responses here are directed to other newsgroups."))
5371               (setq follow-to (list (cons 'Newsgroups followup-to)))
5372             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
5373        ;; Handle Mail-Followup-To, followup via e-mail.
5374        ((and mft
5375              (or (not (eq message-use-mail-followup-to 'ask))
5376                  (message-y-or-n-p
5377                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
5378 You should normally obey the Mail-Followup-To: header.
5379
5380         `Mail-Followup-To: " mft "'
5381 directs your response to " (if (string-match "," mft)
5382                                "the specified addresses"
5383                              "that address only") " instead of news.
5384
5385 A typical situation where Mail-Followup-To is used is when the author thinks
5386 that further discussion should take place only in "
5387                              (if (string-match "," mft)
5388                                  "the specified mailing lists"
5389                                "that mailing list") ".")))
5390         (setq message-this-is-news nil
5391               distribution nil
5392               follow-to (list (cons 'To mft))))
5393        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
5394        (t
5395         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
5396
5397     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5398
5399     (message-setup
5400      `((Subject . ,subject)
5401        ,@follow-to
5402        ,@(and mct (list (cons 'Cc mct)))
5403        ,@(and distribution (list (cons 'Distribution distribution)))
5404        ,@(if (or references message-id)
5405              `((References . ,(concat (or references "") (and references " ")
5406                                       (or message-id ""))))))
5407      cur)
5408
5409     (setq message-reply-headers
5410           (make-full-mail-header-from-decoded-header
5411            0 subject from date message-id references 0 0 ""))))
5412
5413 ;;;###autoload
5414 (defun message-cancel-news (&optional arg)
5415   "Cancel an article you posted.
5416 If ARG, allow editing of the cancellation message."
5417   (interactive "P")
5418   (unless (message-news-p)
5419     (error "This is not a news article; canceling is impossible"))
5420   (let (from newsgroups message-id distribution buf sender)
5421     (save-excursion
5422       ;; Get header info from original article.
5423       (save-restriction
5424         (message-narrow-to-head-1)
5425         (setq from (message-fetch-field "from")
5426               sender (message-fetch-field "sender")
5427               newsgroups (message-fetch-field "newsgroups")
5428               message-id (message-fetch-field "message-id" t)
5429               distribution (message-fetch-field "distribution")))
5430       ;; Make sure that this article was written by the user.
5431       (unless (or
5432                ;; Canlock-logic as suggested by Per Abrahamsen
5433                ;; <abraham@dina.kvl.dk>
5434                ;;
5435                ;; IF article has cancel-lock THEN
5436                ;;   IF we can verify it THEN
5437                ;;     issue cancel
5438                ;;   ELSE
5439                ;;     error: cancellock: article is not yours
5440                ;; ELSE
5441                ;;   Use old rules, comparing sender...
5442                (if (message-fetch-field "Cancel-Lock")
5443                    (if (null (canlock-verify))
5444                        t
5445                      (error "Failed to verify Cancel-lock: This article is not yours"))
5446                  nil)
5447                (message-gnksa-enable-p 'cancel-messages)
5448                (and sender
5449                     (string-equal
5450                      (downcase sender)
5451                      (downcase (message-make-sender))))
5452                (string-equal
5453                 (downcase (cadr (std11-extract-address-components from)))
5454                 (downcase (cadr (std11-extract-address-components
5455                                  (message-make-from))))))
5456         (error "This article is not yours"))
5457       (when (yes-or-no-p "Do you really want to cancel this article? ")
5458         ;; Make control message.
5459         (if arg
5460             (message-news)
5461           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5462         (erase-buffer)
5463         (insert "Newsgroups: " newsgroups "\n"
5464                 "From: " from "\n"
5465                 "Subject: cmsg cancel " message-id "\n"
5466                 "Control: cancel " message-id "\n"
5467                 (if distribution
5468                     (concat "Distribution: " distribution "\n")
5469                   "")
5470                 mail-header-separator "\n"
5471                 message-cancel-message)
5472         (run-hooks 'message-cancel-hook)
5473         (unless arg
5474           (message "Canceling your article...")
5475           (if (let ((message-syntax-checks
5476                      'dont-check-for-anything-just-trust-me)
5477                     (message-encoding-buffer (current-buffer))
5478                     (message-edit-buffer (current-buffer)))
5479                 (message-send-news))
5480               (message "Canceling your article...done"))
5481           (kill-buffer buf))))))
5482
5483 (defun message-supersede-setup-for-mime-edit ()
5484   (set (make-local-variable 'message-setup-hook) nil)
5485   (mime-edit-again))
5486
5487 ;;;###autoload
5488 (defun message-supersede ()
5489   "Start composing a message to supersede the current message.
5490 This is done simply by taking the old article and adding a Supersedes
5491 header line with the old Message-ID."
5492   (interactive)
5493   (let ((cur (current-buffer))
5494         (sender (message-fetch-field "sender"))
5495         (from (message-fetch-field "from")))
5496     ;; Check whether the user owns the article that is to be superseded.
5497     (unless (or
5498              ;; Canlock-logic as suggested by Per Abrahamsen
5499              ;; <abraham@dina.kvl.dk>
5500              ;;
5501              ;; IF article has cancel-lock THEN
5502              ;;   IF we can verify it THEN
5503              ;;     issue cancel
5504              ;;   ELSE
5505              ;;     error: cancellock: article is not yours
5506              ;; ELSE
5507              ;;   Use old rules, comparing sender...
5508              (if (message-fetch-field "Cancel-Lock")
5509                  (if (null (canlock-verify))
5510                      t
5511                    (error "Failed to verify Cancel-lock: This article is not yours"))
5512                nil)
5513              (message-gnksa-enable-p 'cancel-messages)
5514              (and sender
5515                   (string-equal
5516                    (downcase sender)
5517                    (downcase (message-make-sender))))
5518              (string-equal
5519               (downcase (cadr (std11-extract-address-components from)))
5520               (downcase (cadr (std11-extract-address-components
5521                                (message-make-from))))))
5522       (error "This article is not yours"))
5523     ;; Get a normal message buffer.
5524     (message-pop-to-buffer (message-buffer-name "supersede"))
5525     (insert-buffer-substring cur)
5526     (message-narrow-to-head-1)
5527     ;; Remove unwanted headers.
5528     (when message-ignored-supersedes-headers
5529       (message-remove-header message-ignored-supersedes-headers t))
5530     (goto-char (point-min))
5531     (if (not (re-search-forward "^Message-ID: " nil t))
5532         (error "No Message-ID in this article")
5533       (replace-match "Supersedes: " t t))
5534     (goto-char (point-max))
5535     (insert mail-header-separator)
5536     (widen)
5537     (when message-supersede-setup-function
5538       (funcall message-supersede-setup-function))
5539     (run-hooks 'message-supersede-setup-hook)
5540     (goto-char (point-min))
5541     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
5542
5543 ;;;###autoload
5544 (defun message-recover ()
5545   "Reread contents of current buffer from its last auto-save file."
5546   (interactive)
5547   (let ((file-name (make-auto-save-file-name)))
5548     (cond ((save-window-excursion
5549              (if (not (eq system-type 'vax-vms))
5550                  (with-output-to-temp-buffer "*Directory*"
5551                    (with-current-buffer standard-output
5552                      (fundamental-mode)) ; for Emacs 20.4+
5553                    (buffer-disable-undo standard-output)
5554                    (let ((default-directory "/"))
5555                      (call-process
5556                       "ls" nil standard-output nil "-l" file-name))))
5557              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5558            (let ((buffer-read-only nil))
5559              (erase-buffer)
5560              (insert-file-contents file-name nil)))
5561           (t (error "message-recover cancelled")))))
5562
5563 ;;; Washing Subject:
5564
5565 (defun message-wash-subject (subject)
5566   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5567 Previous forwarders, replyers, etc. may add it."
5568   (with-temp-buffer
5569     (insert subject)
5570     (goto-char (point-min))
5571     ;; strip Re/Fwd stuff off the beginning
5572     (while (re-search-forward
5573             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5574       (replace-match ""))
5575
5576     ;; and gnus-style forwards [foo@bar.com] subject
5577     (goto-char (point-min))
5578     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5579       (replace-match ""))
5580
5581     ;; and off the end
5582     (goto-char (point-max))
5583     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5584       (replace-match ""))
5585
5586     ;; and finally, any whitespace that was left-over
5587     (goto-char (point-min))
5588     (while (re-search-forward "^[ \t]+" nil t)
5589       (replace-match ""))
5590     (goto-char (point-max))
5591     (while (re-search-backward "[ \t]+$" nil t)
5592       (replace-match ""))
5593
5594     (buffer-string)))
5595
5596 ;;; Forwarding messages.
5597
5598 (defvar message-forward-decoded-p nil
5599   "Non-nil means the original message is decoded.")
5600
5601 (defun message-forward-subject-author-subject (subject)
5602   "Generate a SUBJECT for a forwarded message.
5603 The form is: [Source] Subject, where if the original message was mail,
5604 Source is the sender, and if the original message was news, Source is
5605 the list of newsgroups is was posted to."
5606   (concat "["
5607           (let ((prefix (message-fetch-field "newsgroups")))
5608             (or prefix
5609                 (and (setq prefix (message-fetch-field "from"))
5610                      (nnheader-decode-from prefix))
5611                 "(nowhere)"))
5612           "] " subject))
5613
5614 (defun message-forward-subject-fwd (subject)
5615   "Generate a SUBJECT for a forwarded message.
5616 The form is: Fwd: Subject, where Subject is the original subject of
5617 the message."
5618   (concat "Fwd: " subject))
5619
5620 (defun message-make-forward-subject ()
5621   "Return a Subject header suitable for the message in the current buffer."
5622   (save-excursion
5623     (save-restriction
5624       (message-narrow-to-head-1)
5625       (let ((funcs message-make-forward-subject-function)
5626             (subject (message-fetch-field "Subject")))
5627         (setq subject
5628               (if subject
5629                   (if message-forward-decoded-p
5630                       subject
5631                     (nnheader-decode-subject subject))
5632                 ""))
5633         (if message-wash-forwarded-subjects
5634             (setq subject (message-wash-subject subject)))
5635         ;; Make sure funcs is a list.
5636         (and funcs
5637              (not (listp funcs))
5638              (setq funcs (list funcs)))
5639         ;; Apply funcs in order, passing subject generated by previous
5640         ;; func to the next one.
5641         (while funcs
5642           (when (message-functionp (car funcs))
5643             (setq subject (funcall (car funcs) subject)))
5644           (setq funcs (cdr funcs)))
5645         subject))))
5646
5647 ;;;###autoload
5648 (defun message-forward (&optional news)
5649   "Forward the current message via mail.
5650 Optional NEWS will use news to forward instead of mail."
5651   (interactive "P")
5652   (let ((cur (current-buffer))
5653         (subject (message-make-forward-subject)))
5654     (if news
5655         (message-news nil subject)
5656       (message-mail nil subject))
5657     (message-forward-make-body cur)))
5658
5659 ;;;###autoload
5660 (defun message-forward-make-body (forward-buffer)
5661   ;; Put point where we want it before inserting the forwarded
5662   ;; message.
5663   (if message-forward-before-signature
5664       (message-goto-body)
5665     (goto-char (point-max)))
5666   ;; Make sure we're at the start of the line.
5667   (unless (bolp)
5668     (insert "\n"))
5669   ;; Narrow to the area we are to insert.
5670   (narrow-to-region (point) (point))
5671   ;; Insert the separators and the forwarded buffer.
5672   (insert message-forward-start-separator)
5673   (let ((art-beg (point)))
5674     (insert-buffer-substring forward-buffer)
5675     (goto-char (point-max))
5676     (insert message-forward-end-separator)
5677     (set-text-properties (point-min) (point-max) nil)
5678     ;; Remove all unwanted headers.
5679     (goto-char art-beg)
5680     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
5681                                   (1- (point))
5682                                 (point)))
5683     (goto-char (point-min))
5684     (message-remove-header message-included-forward-headers t nil t)
5685     (widen)
5686     (message-position-point)))
5687
5688 ;;;###autoload
5689 (defun message-forward-rmail-make-body (forward-buffer)
5690   (save-window-excursion
5691     (set-buffer forward-buffer)
5692     (let (rmail-enable-mime)
5693       (rmail-toggle-header 0)))
5694   (message-forward-make-body forward-buffer))
5695
5696 ;;;###autoload
5697 (defun message-insinuate-rmail ()
5698   "Let RMAIL uses message to forward."
5699   (interactive)
5700   (setq rmail-enable-mime-composing t)
5701   (setq rmail-insert-mime-forwarded-message-function
5702         'message-forward-rmail-make-body))
5703
5704 ;;;###autoload
5705 (defun message-resend (address)
5706   "Resend the current article to ADDRESS."
5707   (interactive
5708    (list (message-read-from-minibuffer "Resend message to: ")))
5709   (message "Resending message to %s..." address)
5710   (save-excursion
5711     (let ((cur (current-buffer))
5712           beg)
5713       ;; We first set up a normal mail buffer.
5714       (unless (message-mail-user-agent)
5715         (set-buffer (get-buffer-create " *message resend*"))
5716         (erase-buffer)
5717         (let ((message-this-is-mail t)
5718               ;; avoid to turn-on-mime-edit
5719               message-setup-hook)
5720           (message-setup `((To . ,address)))))
5721       ;; Insert our usual headers.
5722       (message-generate-headers '(From Date To))
5723       (message-narrow-to-headers)
5724       ;; Rename them all to "Resent-*".
5725       (while (re-search-forward "^[A-Za-z]" nil t)
5726         (forward-char -1)
5727         (insert "Resent-"))
5728       (widen)
5729       (forward-line)
5730       (delete-region (point) (point-max))
5731       (setq beg (point))
5732       ;; Insert the message to be resent.
5733       (insert-buffer-substring cur)
5734       (goto-char (point-min))
5735       (search-forward "\n\n")
5736       (forward-char -1)
5737       (save-restriction
5738         (narrow-to-region beg (point))
5739         (message-remove-header message-ignored-resent-headers t)
5740         (goto-char (point-max)))
5741       (insert mail-header-separator)
5742       ;; Rename all old ("Also-")Resent headers.
5743       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
5744         (beginning-of-line)
5745         (insert "Also-"))
5746       ;; Quote any "From " lines at the beginning.
5747       (goto-char beg)
5748       (when (looking-at "From ")
5749         (replace-match "X-From-Line: "))
5750       ;; Send it.
5751       (let ((message-encoding-buffer (current-buffer))
5752             (message-edit-buffer (current-buffer))
5753             message-required-mail-headers)
5754         (message-send-mail))
5755       (kill-buffer (current-buffer)))
5756     (message "Resending message to %s...done" address)))
5757
5758 (defun message-bounce-setup-for-mime-edit ()
5759   (set (make-local-variable 'message-setup-hook) nil)
5760   (mime-edit-again))
5761
5762 ;;;###autoload
5763 (defun message-bounce ()
5764   "Re-mail the current message.
5765 This only makes sense if the current message is a bounce message that
5766 contains some mail you have written which has been bounced back to
5767 you."
5768   (interactive)
5769   (let ((cur (current-buffer))
5770         boundary)
5771     (message-pop-to-buffer (message-buffer-name "bounce"))
5772     (insert-buffer-substring cur)
5773     (undo-boundary)
5774     (message-narrow-to-head)
5775     (if (and (message-fetch-field "MIME-Version")
5776              (setq boundary (message-fetch-field "Content-Type")))
5777         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
5778             (setq boundary (concat (match-string 1 boundary) " *\n"
5779                                    "Content-Type: message/rfc822"))
5780           (setq boundary nil)))
5781     (widen)
5782     (goto-char (point-min))
5783     (search-forward "\n\n" nil t)
5784     (if (or (and boundary
5785                  (re-search-forward boundary nil t)
5786                  (forward-line 2))
5787             (and (re-search-forward message-unsent-separator nil t)
5788                  (forward-line 1))
5789             (re-search-forward "^Return-Path:.*\n" nil t))
5790         ;; We remove everything before the bounced mail.
5791         (delete-region
5792          (point-min)
5793          (if (re-search-forward "^[^ \n\t]+:" nil t)
5794              (match-beginning 0)
5795            (point)))
5796       (when (re-search-backward "^.?From .*\n" nil t)
5797         (delete-region (match-beginning 0) (match-end 0))))
5798     (save-restriction
5799       (message-narrow-to-head-1)
5800       (message-remove-header message-ignored-bounced-headers t)
5801       (goto-char (point-max))
5802       (insert mail-header-separator))
5803     (when message-bounce-setup-function
5804       (funcall message-bounce-setup-function))
5805     (run-hooks 'message-bounce-setup-hook)
5806     (message-position-point)))
5807
5808 ;;;
5809 ;;; Interactive entry points for new message buffers.
5810 ;;;
5811
5812 ;;;###autoload
5813 (defun message-mail-other-window (&optional to subject)
5814   "Like `message-mail' command, but display mail buffer in another window."
5815   (interactive)
5816   (unless (message-mail-user-agent)
5817     (let ((pop-up-windows t)
5818           (special-display-buffer-names nil)
5819           (special-display-regexps nil)
5820           (same-window-buffer-names nil)
5821           (same-window-regexps nil))
5822       (message-pop-to-buffer (message-buffer-name "mail" to))))
5823   (let ((message-this-is-mail t))
5824     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5825                    nil nil 'switch-to-buffer-other-window)))
5826
5827 ;;;###autoload
5828 (defun message-mail-other-frame (&optional to subject)
5829   "Like `message-mail' command, but display mail buffer in another frame."
5830   (interactive)
5831   (unless (message-mail-user-agent)
5832     (let ((pop-up-frames t)
5833           (special-display-buffer-names nil)
5834           (special-display-regexps nil)
5835           (same-window-buffer-names nil)
5836           (same-window-regexps nil))
5837       (message-pop-to-buffer (message-buffer-name "mail" to))))
5838   (let ((message-this-is-mail t))
5839     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
5840                    nil nil 'switch-to-buffer-other-frame)))
5841
5842 ;;;###autoload
5843 (defun message-news-other-window (&optional newsgroups subject)
5844   "Start editing a news article to be sent."
5845   (interactive)
5846   (let ((pop-up-windows t)
5847         (special-display-buffer-names nil)
5848         (special-display-regexps nil)
5849         (same-window-buffer-names nil)
5850         (same-window-regexps nil))
5851     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5852   (let ((message-this-is-news t))
5853     (message-setup `((Newsgroups . ,(or newsgroups ""))
5854                      (Subject . ,(or subject ""))))))
5855
5856 ;;;###autoload
5857 (defun message-news-other-frame (&optional newsgroups subject)
5858   "Start editing a news article to be sent."
5859   (interactive)
5860   (let ((pop-up-frames t)
5861         (special-display-buffer-names nil)
5862         (special-display-regexps nil)
5863         (same-window-buffer-names nil)
5864         (same-window-regexps nil))
5865     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
5866   (let ((message-this-is-news t))
5867     (message-setup `((Newsgroups . ,(or newsgroups ""))
5868                      (Subject . ,(or subject ""))))))
5869
5870 ;;; underline.el
5871
5872 ;; This code should be moved to underline.el (from which it is stolen).
5873
5874 ;;;###autoload
5875 (defun bold-region (start end)
5876   "Bold all nonblank characters in the region.
5877 Works by overstriking characters.
5878 Called from program, takes two arguments START and END
5879 which specify the range to operate on."
5880   (interactive "r")
5881   (save-excursion
5882     (let ((end1 (make-marker)))
5883       (move-marker end1 (max start end))
5884       (goto-char (min start end))
5885       (while (< (point) end1)
5886         (or (looking-at "[_\^@- ]")
5887             (insert (char-after) "\b"))
5888         (forward-char 1)))))
5889
5890 ;;;###autoload
5891 (defun unbold-region (start end)
5892   "Remove all boldness (overstruck characters) in the region.
5893 Called from program, takes two arguments START and END
5894 which specify the range to operate on."
5895   (interactive "r")
5896   (save-excursion
5897     (let ((end1 (make-marker)))
5898       (move-marker end1 (max start end))
5899       (goto-char (min start end))
5900       (while (re-search-forward "\b" end1 t)
5901         (if (eq (char-after) (char-after (- (point) 2)))
5902             (delete-char -2))))))
5903
5904 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
5905
5906 ;; Support for toolbar
5907 (eval-when-compile
5908   (defvar tool-bar-map)
5909   (defvar tool-bar-mode))
5910
5911 (defun message-tool-bar-map ()
5912   (or message-tool-bar-map
5913       (setq message-tool-bar-map
5914             (and (fboundp 'tool-bar-add-item-from-menu)
5915                  tool-bar-mode
5916                  (let ((tool-bar-map (copy-keymap tool-bar-map))
5917                        (load-path (mm-image-load-path)))
5918                    ;; Zap some items which aren't so relevant and take
5919                    ;; up space.
5920                    (dolist (key '(print-buffer kill-buffer save-buffer
5921                                                write-file dired open-file))
5922                      (define-key tool-bar-map (vector key) nil))
5923                    (tool-bar-add-item-from-menu
5924                     'message-send-and-exit "mail_send" message-mode-map)
5925                    (tool-bar-add-item-from-menu
5926                     'message-kill-buffer "close" message-mode-map)
5927                    (tool-bar-add-item-from-menu
5928                     'message-dont-send "cancel" message-mode-map)
5929                    (tool-bar-add-item-from-menu
5930                     'mime-edit-insert-file "attach" message-mode-map)
5931                    (tool-bar-add-item-from-menu
5932                     'ispell-message "spell" message-mode-map)
5933                    (tool-bar-add-item-from-menu
5934                     'message-insert-importance-high "important"
5935                     message-mode-map)
5936                    (tool-bar-add-item-from-menu
5937                     'message-insert-importance-low "unimportant"
5938                     message-mode-map)
5939                    tool-bar-map)))))
5940
5941 ;;; Group name completion.
5942
5943 (defcustom message-newgroups-header-regexp
5944   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
5945   "Regexp that match headers that lists groups."
5946   :group 'message
5947   :type 'regexp)
5948
5949 (defcustom message-completion-alist
5950   (list (cons message-newgroups-header-regexp 'message-expand-group)
5951         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name))
5952   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
5953   :group 'message
5954   :type '(alist :key-type regexp :value-type function))
5955
5956 (defcustom message-tab-body-function nil
5957   "*Function to execute when `message-tab' (TAB) is executed in the body.
5958 If nil, the function bound in `text-mode-map' or `global-map' is executed."
5959   :group 'message
5960   :type 'function)
5961
5962 (defun message-tab ()
5963   "Complete names according to `message-completion-alist'.
5964 Execute function specified by `message-tab-body-function' when not in
5965 those headers."
5966   (interactive)
5967   (let ((alist message-completion-alist))
5968     (while (and alist
5969                 (let ((mail-abbrev-mode-regexp (caar alist)))
5970                   (not (mail-abbrev-in-expansion-header-p))))
5971       (setq alist (cdr alist)))
5972     (funcall (or (cdar alist) message-tab-body-function
5973                  (lookup-key text-mode-map "\t")
5974                  (lookup-key global-map "\t")
5975                  'indent-relative))))
5976
5977 (defun message-expand-group ()
5978   "Expand the group name under point."
5979   (let* ((b (save-excursion
5980               (save-restriction
5981                 (narrow-to-region
5982                  (save-excursion
5983                    (beginning-of-line)
5984                    (skip-chars-forward "^:")
5985                    (1+ (point)))
5986                  (point))
5987                 (skip-chars-backward "^, \t\n") (point))))
5988          (completion-ignore-case t)
5989          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
5990                                             (point))))
5991          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
5992          (completions (all-completions string hashtb))
5993          comp)
5994     (delete-region b (point))
5995     (cond
5996      ((= (length completions) 1)
5997       (if (string= (car completions) string)
5998           (progn
5999             (insert string)
6000             (message "Only matching group"))
6001         (insert (car completions))))
6002      ((and (setq comp (try-completion string hashtb))
6003            (not (string= comp string)))
6004       (insert comp))
6005      (t
6006       (insert string)
6007       (if (not comp)
6008           (message "No matching groups")
6009         (save-selected-window
6010           (pop-to-buffer "*Completions*")
6011           (buffer-disable-undo)
6012           (let ((buffer-read-only nil))
6013             (erase-buffer)
6014             (let ((standard-output (current-buffer)))
6015               (display-completion-list (sort completions 'string<)))
6016             (goto-char (point-min))
6017             (delete-region (point) (progn (forward-line 3) (point))))))))))
6018
6019 (defun message-expand-name ()
6020   (if (fboundp 'bbdb-complete-name)
6021       (bbdb-complete-name)
6022     (expand-abbrev)))
6023
6024 ;;; Help stuff.
6025
6026 (defun message-talkative-question (ask question show &rest text)
6027   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6028 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6029 The following arguments may contain lists of values."
6030   (if (and show
6031            (setq text (message-flatten-list text)))
6032       (save-window-excursion
6033         (save-excursion
6034           (with-output-to-temp-buffer " *MESSAGE information message*"
6035             (set-buffer " *MESSAGE information message*")
6036             (fundamental-mode)          ; for Emacs 20.4+
6037             (mapcar 'princ text)
6038             (goto-char (point-min))))
6039         (funcall ask question))
6040     (funcall ask question)))
6041
6042 (defun message-flatten-list (list)
6043   "Return a new, flat list that contains all elements of LIST.
6044
6045 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6046 => (1 2 3 4 5 6 7)"
6047   (cond ((consp list)
6048          (apply 'append (mapcar 'message-flatten-list list)))
6049         (list
6050          (list list))))
6051
6052 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6053   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6054 Then clone the local variables and values from the old buffer to the
6055 new one, cloning only the locals having a substring matching the
6056 regexp varstr."
6057   (let ((oldbuf (current-buffer)))
6058     (save-excursion
6059       (set-buffer (generate-new-buffer name))
6060       (message-clone-locals oldbuf varstr)
6061       (current-buffer))))
6062
6063 (defun message-clone-locals (buffer &optional varstr)
6064   "Clone the local variables from BUFFER to the current buffer."
6065   (let ((locals (save-excursion
6066                   (set-buffer buffer)
6067                   (buffer-local-variables)))
6068         (regexp
6069          "^\\(gnus\\|nn\\|message\\|user-\\(mail-address\\|full-name\\)\\)"))
6070     (mapcar
6071      (lambda (local)
6072        (when (and (consp local)
6073                   (car local)
6074                   (string-match regexp (symbol-name (car local)))
6075                   (or (null varstr)
6076                       (string-match varstr (symbol-name (car local)))))
6077          (ignore-errors
6078            (set (make-local-variable (car local))
6079                 (cdr local)))))
6080      locals)))
6081
6082
6083 ;;; @ for MIME Edit mode
6084 ;;;
6085
6086 (defun message-maybe-encode ()
6087   (when message-mime-mode
6088     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
6089     (let ((pgp-processing (with-current-buffer message-edit-buffer
6090                             mime-edit-pgp-processing)))
6091       (setq mime-edit-pgp-processing pgp-processing))
6092     (run-hooks 'mime-edit-translate-hook)
6093     (if (catch 'mime-edit-error
6094           (save-excursion
6095             (mime-edit-pgp-enclose-buffer)
6096             (mime-edit-translate-body)))
6097         (error "Translation error!"))
6098     (run-hooks 'mime-edit-exit-hook)))
6099
6100 (defun message-mime-insert-article (&optional full-headers)
6101   (interactive "P")
6102   (let ((message-cite-function 'mime-edit-inserted-message-filter)
6103         (message-reply-buffer
6104          (message-get-parameter-with-eval 'original-buffer))
6105         (start (point)))
6106     (message-yank-original nil)
6107     (save-excursion
6108       (narrow-to-region (goto-char start)
6109                         (if (search-forward "\n\n" nil t)
6110                             (1- (point))
6111                           (point-max)))
6112       (goto-char (point-min))
6113       (let ((message-included-forward-headers
6114              (if full-headers "" message-included-forward-headers)))
6115         (message-remove-header message-included-forward-headers t nil t))
6116       (widen))))
6117
6118 (set-alist 'mime-edit-message-inserter-alist
6119            'message-mode (function message-mime-insert-article))
6120
6121 ;;; Miscellaneous functions
6122
6123 ;; stolen (and renamed) from nnheader.el
6124 (static-if (fboundp 'subst-char-in-string)
6125     (defsubst message-replace-chars-in-string (string from to)
6126       (subst-char-in-string from to string))
6127   (defun message-replace-chars-in-string (string from to)
6128     "Replace characters in STRING from FROM to TO."
6129     (let ((string (substring string 0)) ;Copy string.
6130           (len (length string))
6131           (idx 0))
6132       ;; Replace all occurrences of FROM with TO.
6133       (while (< idx len)
6134         (when (= (aref string idx) from)
6135           (aset string idx to))
6136         (setq idx (1+ idx)))
6137       string)))
6138
6139 ;;;
6140 ;;; MIME functions
6141 ;;;
6142
6143 (defvar message-inhibit-body-encoding t)
6144
6145 (defun message-encode-message-body ()
6146   (unless message-inhibit-body-encoding
6147     (let ((mail-parse-charset (or mail-parse-charset
6148                                   message-default-charset))
6149           (case-fold-search t)
6150           lines content-type-p)
6151       (message-goto-body)
6152       (save-restriction
6153         (narrow-to-region (point) (point-max))
6154         (let ((new (mml-generate-mime)))
6155           (when new
6156             (delete-region (point-min) (point-max))
6157             (insert new)
6158             (goto-char (point-min))
6159             (if (eq (aref new 0) ?\n)
6160                 (delete-char 1)
6161               (search-forward "\n\n")
6162               (setq lines (buffer-substring (point-min) (1- (point))))
6163               (delete-region (point-min) (point))))))
6164       (save-restriction
6165         (message-narrow-to-headers-or-head)
6166         (message-remove-header "Mime-Version")
6167         (goto-char (point-max))
6168         (insert "MIME-Version: 1.0\n")
6169         (when lines
6170           (insert lines))
6171         (setq content-type-p
6172               (or mml-boundary
6173                   (re-search-backward "^Content-Type:" nil t))))
6174       (save-restriction
6175         (message-narrow-to-headers-or-head)
6176         (message-remove-first-header "Content-Type")
6177         (message-remove-first-header "Content-Transfer-Encoding"))
6178       ;; We always make sure that the message has a Content-Type header.
6179       ;; This is because some broken MTAs and MUAs get awfully confused
6180       ;; when confronted with a message with a MIME-Version header and
6181       ;; without a Content-Type header.  For instance, Solaris'
6182       ;; /usr/bin/mail.
6183       (unless content-type-p
6184         (goto-char (point-min))
6185         ;; For unknown reason, MIME-Version doesn't exist.
6186         (when (re-search-forward "^MIME-Version:" nil t)
6187           (forward-line 1)
6188           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6189
6190 (defun message-read-from-minibuffer (prompt)
6191   "Read from the minibuffer while providing abbrev expansion."
6192   (if (fboundp 'mail-abbrevs-setup)
6193       (let ((mail-abbrev-mode-regexp "")
6194             (minibuffer-setup-hook 'mail-abbrevs-setup)
6195             (minibuffer-local-map message-minibuffer-local-map))
6196         (read-from-minibuffer prompt))
6197     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6198           (minibuffer-local-map message-minibuffer-local-map))
6199       (read-string prompt))))
6200
6201 (defun message-use-alternative-email-as-from ()
6202   (require 'mail-utils)
6203   (let* ((fields '("To" "Cc"))
6204          (emails
6205           (split-string
6206            (mail-strip-quoted-names
6207             (mapconcat 'message-fetch-reply-field fields ","))
6208            "[ \f\t\n\r\v,]+"))
6209          email)
6210     (while emails
6211       (if (string-match message-alternative-emails (car emails))
6212           (setq email (car emails)
6213                 emails nil))
6214       (pop emails))
6215     (unless (or (not email) (equal email user-mail-address))
6216       (goto-char (point-max))
6217       (insert "From: " email "\n"))))
6218
6219 (defun message-options-get (symbol)
6220   (cdr (assq symbol message-options)))
6221
6222 (defun message-options-set (symbol value)
6223   (let ((the-cons (assq symbol message-options)))
6224     (if the-cons
6225         (if value
6226             (setcdr the-cons value)
6227           (setq message-options (delq the-cons message-options)))
6228       (and value
6229            (push (cons symbol value) message-options))))
6230   value)
6231
6232 (defun message-options-set-recipient ()
6233   (save-restriction
6234     (message-narrow-to-headers-or-head)
6235     (message-options-set 'message-sender
6236                          (mail-strip-quoted-names
6237                           (message-fetch-field "from")))
6238     (message-options-set 'message-recipients
6239                          (mail-strip-quoted-names
6240                           (let ((to (message-fetch-field "to"))
6241                                 (cc (message-fetch-field "cc"))
6242                                 (bcc (message-fetch-field "bcc")))
6243                             (concat
6244                              (or to "")
6245                              (if (and to cc) ", ")
6246                              (or cc "")
6247                              (if (and (or to cc) bcc) ", ")
6248                              (or bcc "")))))))
6249
6250 (when (featurep 'xemacs)
6251   (require 'messagexmas)
6252   (message-xmas-redefine))
6253
6254 (defun message-save-drafts ()
6255   "Postponing the message."
6256   (interactive)
6257   (message "Saving %s..." buffer-file-name)
6258   (let ((reply-headers message-reply-headers)
6259         (buffer (current-buffer)))
6260     (with-temp-file buffer-file-name
6261       (insert-buffer buffer)
6262       (setq message-reply-headers reply-headers)
6263       (message-generate-headers '((optional . In-Reply-To)))
6264       (mime-edit-translate-buffer))
6265     (set-buffer-modified-p nil))
6266   (message "Saving %s...done" buffer-file-name))
6267
6268 (provide 'message)
6269
6270 (run-hooks 'message-load-hook)
6271
6272 ;; Local Variables:
6273 ;; coding: iso-8859-1
6274 ;; End:
6275
6276 ;;; message.el ends here