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