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