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