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