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