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