*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile 
33   (require 'cl))
34 (require 'mailheader)
35 (require 'rmail)
36 (require 'nnheader)
37 (require 'timezone)
38 (require 'easymenu)
39 (require 'custom)
40 (if (string-match "XEmacs\\|Lucid" emacs-version)
41     (require 'mail-abbrevs)
42   (require 'mailabbrev))
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'emacs)
49
50 (put 'user-mail-address 'custom-type 'string)
51 (put 'user-full-name 'custom-type 'string)
52
53 (defgroup message-various nil
54   "Various Message Variables"
55   :link '(custom-manual "(message)Various Message Variables")
56   :group 'message)
57
58 (defgroup message-buffers nil
59   "Message Buffers"
60   :link '(custom-manual "(message)Message Buffers")
61   :group 'message)
62
63 (defgroup message-sending nil
64   "Message Sending"
65   :link '(custom-manual "(message)Sending Variables")
66   :group 'message)
67
68 (defgroup message-interface nil
69   "Message Interface"
70   :link '(custom-manual "(message)Interface")
71   :group 'message)
72
73 (defgroup message-forwarding nil
74   "Message Forwarding"
75   :link '(custom-manual "(message)Forwarding")
76   :group 'message-interface)
77
78 (defgroup message-insertion nil
79   "Message Insertion"
80   :link '(custom-manual "(message)Insertion")
81   :group 'message)
82
83 (defgroup message-headers nil
84   "Message Headers"
85   :link '(custom-manual "(message)Message Headers")
86   :group 'message)
87
88 (defgroup message-news nil
89   "Composing News Messages"
90   :group 'message)
91
92 (defgroup message-mail nil
93   "Composing Mail Messages"
94   :group 'message)
95
96 (defcustom message-directory "~/Mail/"
97   "*Directory from which all other mail file variables are derived."
98   :group 'message-various
99   :type 'directory)
100
101 (defcustom message-max-buffers 10
102   "*How many buffers to keep before starting to kill them off."
103   :group 'message-buffers
104   :type 'integer)
105
106 (defcustom message-send-rename-function nil
107   "Function called to rename the buffer after sending it."
108   :group 'message-buffers
109   :type 'function)
110
111 ;;;###autoload
112 (defcustom message-fcc-handler-function 'message-output
113   "*A function called to save outgoing articles.
114 This function will be called with the name of the file to store the
115 article in.  The default function is `message-output' which saves in Unix
116 mailbox format."
117   :type '(radio (function-item message-output)
118                 (function :tag "Other"))
119   :group 'message-sending)
120
121 (defcustom message-courtesy-message
122   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
123   "*This is inserted at the start of a mailed copy of a posted message.
124 If the string contains the format spec \"%s\", the Newsgroups
125 the article has been posted to will be inserted there.
126 If this variable is nil, no such courtesy message will be added."
127   :group 'message-sending
128   :type 'string)
129
130 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
131   "*Regexp that matches headers to be removed in resent bounced mail."
132   :group 'message-interface
133   :type 'regexp)
134
135 ;;;###autoload
136 (defcustom message-from-style 'default
137   "*Specifies how \"From\" headers look.
138
139 If `nil', they contain just the return address like:
140         king@grassland.com
141 If `parens', they look like:
142         king@grassland.com (Elvis Parsley)
143 If `angles', they look like:
144         Elvis Parsley <king@grassland.com>
145
146 Otherwise, most addresses look like `angles', but they look like
147 `parens' if `angles' would need quoting and `parens' would not."
148   :type '(choice (const :tag "simple" nil)
149                  (const parens)
150                  (const angles)
151                  (const default))
152   :group 'message-headers)
153
154 (defcustom message-syntax-checks nil
155   ;; Guess this one shouldn't be easy to customize...
156   "Controls what syntax checks should not be performed on outgoing posts.
157 To disable checking of long signatures, for instance, add
158  `(signature . disabled)' to this list.
159
160 Don't touch this variable unless you really know what you're doing.
161
162 Checks include subject-cmsg multiple-headers sendsys message-id from
163 long-lines control-chars size new-text redirected-followup signature
164 approved sender empty empty-headers message-id from subject
165 shorten-followup-to existing-newsgroups."
166   :group 'message-news)
167
168 (defcustom message-required-news-headers
169   '(From Newsgroups Subject Date Message-ID 
170          (optional . Organization) Lines 
171          (optional . X-Newsreader))
172   "Headers to be generated or prompted for when posting an article.
173 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
174 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
175 X-Newsreader are optional.  If don't you want message to insert some
176 header, remove it from this list."
177   :group 'message-news
178   :group 'message-headers
179   :type '(repeat sexp))
180
181 (defcustom message-required-mail-headers 
182   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
183          (optional . X-Mailer))
184   "Headers to be generated or prompted for when mailing a message.
185 RFC822 required that From, Date, To, Subject and Message-ID be
186 included.  Organization, Lines and X-Mailer are optional."
187   :group 'message-mail
188   :group 'message-headers
189   :type '(repeat sexp))
190
191 (defcustom message-deletable-headers '(Message-ID Date Lines)
192   "Headers to be deleted if they already exist and were generated by message previously."
193   :group 'message-headers
194   :type 'sexp)
195
196 (defcustom message-ignored-news-headers 
197   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
198   "*Regexp of headers to be removed unconditionally before posting."
199   :group 'message-news
200   :group 'message-headers
201   :type 'regexp)
202
203 (defcustom message-ignored-mail-headers "^Gcc:\\|^Fcc:\\|^Resent-Fcc:"
204   "*Regexp of headers to be removed unconditionally before mailing."
205   :group 'message-mail
206   :group 'message-headers
207   :type 'regexp)
208
209 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:\\|^Supersedes:"
210   "*Header lines matching this regexp will be deleted before posting.
211 It's best to delete old Path and Date headers before posting to avoid
212 any confusion."
213   :group 'message-interface
214   :type 'regexp)
215
216 ;;;###autoload
217 (defcustom message-signature-separator "^-- *$"
218   "Regexp matching the signature separator."
219   :type 'regexp
220   :group 'message-various)
221
222 (defcustom message-elide-elipsis "\n[...]\n\n"
223   "*The string which is inserted for elided text.")
224
225 (defcustom message-interactive nil 
226   "Non-nil means when sending a message wait for and display errors.
227 nil means let mailer mail back a message to report errors."
228   :group 'message-sending
229   :group 'message-mail
230   :type 'boolean)
231
232 (defcustom message-generate-new-buffers t
233   "*Non-nil means that a new message buffer will be created whenever `mail-setup' is called.
234 If this is a function, call that function with three parameters:  The type,
235 the to address and the group name.  (Any of these may be nil.)  The function
236 should return the new buffer name."
237   :group 'message-buffers
238   :type '(choice (const :tag "off" nil)
239                  (const :tag "on" t)
240                  (function fun)))
241
242 (defcustom message-kill-buffer-on-exit nil
243   "*Non-nil means that the message buffer will be killed after sending a message."
244   :group 'message-buffers
245   :type 'boolean)
246
247 (defvar gnus-local-organization)
248 (defcustom message-user-organization 
249   (or (and (boundp 'gnus-local-organization)
250            (stringp gnus-local-organization)
251            gnus-local-organization)
252       (getenv "ORGANIZATION")
253       t)
254   "*String to be used as an Organization header.
255 If t, use `message-user-organization-file'."
256   :group 'message-headers
257   :type '(choice string
258                  (const :tag "consult file" t)))
259
260 ;;;###autoload
261 (defcustom message-user-organization-file "/usr/lib/news/organization"
262   "*Local news organization file."
263   :type 'file
264   :group 'message-headers)
265
266 (defcustom message-autosave-directory "~/"
267   ; (concat (file-name-as-directory message-directory) "drafts/")
268   "*Directory where message autosaves buffers.
269 If nil, message won't autosave."
270   :group 'message-buffers
271   :type 'directory)
272
273 (defcustom message-forward-start-separator 
274   "------- Start of forwarded message -------\n"
275   "*Delimiter inserted before forwarded messages."
276   :group 'message-forwarding
277   :type 'string)
278
279 (defcustom message-forward-end-separator
280   "------- End of forwarded message -------\n"
281   "*Delimiter inserted after forwarded messages."
282   :group 'message-forwarding
283   :type 'string)
284
285 (defcustom message-signature-before-forwarded-message t
286   "*If non-nil, put the signature before any included forwarded message."
287   :group 'message-forwarding
288   :type 'boolean)
289
290 (defcustom message-included-forward-headers 
291   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:"
292   "*Regexp matching headers to be included in forwarded messages."
293   :group 'message-forwarding
294   :type 'regexp)
295
296 (defcustom message-ignored-resent-headers "^Return-receipt"
297   "*All headers that match this regexp will be deleted when resending a message."
298   :group 'message-interface
299   :type 'regexp)
300
301 (defcustom message-ignored-cited-headers "."
302   "*Delete these headers from the messages you yank."
303   :group 'message-insertion
304   :type 'regexp)
305
306 (defcustom message-cancel-message "I am canceling my own article."
307   "Message to be inserted in the cancel message."
308   :group 'message-interface
309   :type 'string)
310
311 ;; Useful to set in site-init.el
312 ;;;###autoload
313 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
314   "Function to call to send the current buffer as mail.
315 The headers should be delimited by a line whose contents match the
316 variable `mail-header-separator'.
317
318 Legal values include `message-send-mail-with-sendmail' (the default),
319 `message-send-mail-with-mh' and `message-send-mail-with-qmail'."
320   :type '(radio (function-item message-send-mail-with-sendmail)
321                 (function-item message-send-mail-with-mh)
322                 (function-item message-send-mail-with-qmail)
323                 (function :tag "Other"))
324   :group 'message-sending
325   :group 'message-mail)
326
327 (defcustom message-send-news-function 'message-send-news
328   "Function to call to send the current buffer as news.
329 The headers should be delimited by a line whose contents match the
330 variable `mail-header-separator'."
331   :group 'message-sending
332   :group 'message-news
333   :type 'function)
334
335 (defcustom message-reply-to-function nil
336   "Function that should return a list of headers.
337 This function should pick out addresses from the To, Cc, and From headers
338 and respond with new To and Cc headers."
339   :group 'message-interface
340   :type 'function)
341
342 (defcustom message-wide-reply-to-function nil
343   "Function that should return a list of headers.
344 This function should pick out addresses from the To, Cc, and From headers
345 and respond with new To and Cc headers."
346   :group 'message-interface
347   :type 'function)
348
349 (defcustom message-followup-to-function nil
350   "Function that should return a list of headers.
351 This function should pick out addresses from the To, Cc, and From headers
352 and respond with new To and Cc headers."
353   :group 'message-interface
354   :type 'function)
355
356 (defcustom message-use-followup-to 'ask
357   "*Specifies what to do with Followup-To header.
358 If nil, always ignore the header.  If it is t, use its value, but
359 query before using the \"poster\" value.  If it is the symbol `ask',
360 always query the user whether to use the value.  If it is the symbol
361 `use', always use the value."
362   :group 'message-interface
363   :type '(choice (const :tag "ignore" nil)
364                  (const use)
365                  (const ask)))
366
367 ;; stuff relating to broken sendmail in MMDF
368 (defcustom message-sendmail-f-is-evil nil
369   "*Non-nil means that \"-f username\" should not be added to the sendmail
370 command line, because it is even more evil than leaving it out."
371   :group 'message-sending
372   :type 'boolean)
373
374 ;; qmail-related stuff
375 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
376   "Location of the qmail-inject program."
377   :group 'message-sending
378   :type 'file)
379
380 (defcustom message-qmail-inject-args nil
381   "Arguments passed to qmail-inject programs.
382 This should be a list of strings, one string for each argument.
383
384 For e.g., if you wish to set the envelope sender address so that bounces
385 go to the right place or to deal with listserv's usage of that address, you
386 might set this variable to '(\"-f\" \"you@some.where\")."
387   :group 'message-sending
388   :type '(repeat string))
389
390 (defvar gnus-post-method)
391 (defvar gnus-select-method)
392 (defcustom message-post-method 
393   (cond ((and (boundp 'gnus-post-method)
394               gnus-post-method)
395          gnus-post-method)
396         ((boundp 'gnus-select-method)
397          gnus-select-method)
398         (t '(nnspool "")))
399   "Method used to post news."
400   :group 'message-news
401   :group 'mesage-sending
402   ;; This should be the `gnus-select-method' widget, but that might
403   ;; create a dependence to `gnus.el'.
404   :type 'sexp)
405
406 (defcustom message-generate-headers-first nil
407   "*If non-nil, generate all possible headers before composing."
408   :group 'message-headers
409   :type 'boolean)
410
411 (defcustom message-setup-hook nil
412   "Normal hook, run each time a new outgoing message is initialized.
413 The function `message-setup' runs this hook."
414   :group 'message-various
415   :type 'hook)
416
417 (defcustom message-signature-setup-hook nil
418   "Normal hook, run each time a new outgoing message is initialized.
419 It is run after the headers have been inserted and before 
420 the signature is inserted."
421   :group 'message-various
422   :type 'hook)
423
424 (defcustom message-mode-hook nil
425   "Hook run in message mode buffers."
426   :group 'message-various
427   :type 'hook)
428
429 (defcustom message-header-hook nil
430   "Hook run in a message mode buffer narrowed to the headers."
431   :group 'message-various
432   :type 'hook)
433
434 (defcustom message-header-setup-hook nil
435   "Hook called narrowed to the headers when setting up a message
436 buffer."
437   :group 'message-various
438   :type 'hook)
439
440 ;;;###autoload
441 (defcustom message-citation-line-function 'message-insert-citation-line
442   "*Function called to insert the \"Whomever writes:\" line."
443   :type 'function
444   :group 'message-insertion)
445
446 ;;;###autoload
447 (defcustom message-yank-prefix "> "
448   "*Prefix inserted on the lines of yanked messages.
449 nil means use indentation."
450   :type 'string
451   :group 'message-insertion)
452
453 (defcustom message-indentation-spaces 3
454   "*Number of spaces to insert at the beginning of each cited line.
455 Used by `message-yank-original' via `message-yank-cite'."
456   :group 'message-insertion
457   :type 'integer)
458
459 ;;;###autoload
460 (defcustom message-cite-function
461   (if (and (boundp 'mail-citation-hook)
462            mail-citation-hook)
463       mail-citation-hook
464     'message-cite-original)
465   "*Function for citing an original message."
466   :type '(radio (function-item message-cite-original)
467                 (function-item sc-cite-original)
468                 (function :tag "Other"))
469   :group 'message-insertion)
470
471 ;;;###autoload
472 (defcustom message-indent-citation-function 'message-indent-citation
473   "*Function for modifying a citation just inserted in the mail buffer.
474 This can also be a list of functions.  Each function can find the
475 citation between (point) and (mark t).  And each function should leave
476 point and mark around the citation text as modified."
477   :type 'function
478   :group 'message-insertion)
479
480 (defvar message-abbrevs-loaded nil)
481
482 ;;;###autoload
483 (defcustom message-signature t
484   "*String to be inserted at the end of the message buffer.
485 If t, the `message-signature-file' file will be inserted instead.
486 If a function, the result from the function will be used instead.
487 If a form, the result from the form will be used instead."
488   :type 'sexp
489   :group 'message-insertion)
490
491 ;;;###autoload
492 (defcustom message-signature-file "~/.signature"
493   "*File containing the text inserted at end of message buffer."
494   :type 'file
495   :group 'message-insertion)
496
497 (defcustom message-distribution-function nil
498   "*Function called to return a Distribution header."
499   :group 'message-news
500   :group 'message-headers
501   :type 'function)
502
503 (defcustom message-expires 14
504   "Number of days before your article expires."
505   :group 'message-news
506   :group 'message-headers
507   :link '(custom-manual "(message)News Headers")
508   :type 'integer)
509
510 (defcustom message-user-path nil
511   "If nil, use the NNTP server name in the Path header.
512 If stringp, use this; if non-nil, use no host name (user name only)."
513   :group 'message-news
514   :group 'message-headers
515   :link '(custom-manual "(message)News Headers")
516   :type '(choice (const :tag "nntp" nil)
517                  (string :tag "name")
518                  (sexp :tag "none" :format "%t" t)))
519
520 (defvar message-reply-buffer nil)
521 (defvar message-reply-headers nil)
522 (defvar message-newsreader nil)
523 (defvar message-mailer nil)
524 (defvar message-sent-message-via nil)
525 (defvar message-checksum nil)
526 (defvar message-send-actions nil
527   "A list of actions to be performed upon successful sending of a message.")
528 (defvar message-exit-actions nil
529   "A list of actions to be performed upon exiting after sending a message.")
530 (defvar message-kill-actions nil
531   "A list of actions to be performed before killing a message buffer.")
532 (defvar message-postpone-actions nil
533   "A list of actions to be performed after postponing a message.")
534
535 (defcustom message-default-headers ""
536   "*A string containing header lines to be inserted in outgoing messages.
537 It is inserted before you edit the message, so you can edit or delete
538 these lines."
539   :group 'message-headers
540   :type 'string)
541
542 (defcustom message-default-mail-headers ""
543   "*A string of header lines to be inserted in outgoing mails."
544   :group 'message-headers
545   :group 'message-mail
546   :type 'string)
547
548 (defcustom message-default-news-headers ""
549   "*A string of header lines to be inserted in outgoing news
550 articles."
551   :group 'message-headers
552   :group 'message-news
553   :type 'string)
554
555 ;; Note: could use /usr/ucb/mail instead of sendmail;
556 ;; options -t, and -v if not interactive.
557 (defcustom message-mailer-swallows-blank-line
558   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" 
559                          system-configuration)
560            (file-readable-p "/etc/sendmail.cf")
561            (let ((buffer (get-buffer-create " *temp*")))
562              (unwind-protect
563                  (save-excursion
564                    (set-buffer buffer)
565                    (insert-file-contents "/etc/sendmail.cf")
566                    (goto-char (point-min))
567                    (let ((case-fold-search nil))
568                      (re-search-forward "^OR\\>" nil t)))
569                (kill-buffer buffer))))
570       ;; According to RFC822, "The field-name must be composed of printable
571       ;; ASCII characters (i. e., characters that have decimal values between
572       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
573       ;; space, or colon.
574       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
575   "Set this non-nil if the system's mailer runs the header and body together.
576 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
577 The value should be an expression to test whether the problem will
578 actually occur."
579   :group 'message-sending
580   :type 'sexp)
581
582 (ignore-errors
583   (define-mail-user-agent 'message-user-agent
584     'message-mail 'message-send-and-exit 
585     'message-kill-buffer 'message-send-hook))
586
587 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
588   "If non-nil, delete the deletable headers before feeding to mh.")
589
590 ;;; Internal variables.
591 ;;; Well, not really internal.
592
593 (defvar message-mode-syntax-table 
594   (let ((table (copy-syntax-table text-mode-syntax-table)))
595     (modify-syntax-entry ?% ". " table)
596     table)
597   "Syntax table used while in Message mode.")
598
599 (defvar message-mode-abbrev-table text-mode-abbrev-table
600   "Abbrev table used in Message mode buffers.
601 Defaults to `text-mode-abbrev-table'.")
602
603 (defvar message-font-lock-keywords
604   (let* ((cite-prefix "A-Za-z") (cite-suffix (concat cite-prefix "0-9_.@-")))
605     (list '("^To:" . font-lock-function-name-face)
606           '("^[GBF]?[Cc][Cc]:\\|^Reply-To:" . font-lock-keyword-face)
607           '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
608             (1 font-lock-comment-face) (2 font-lock-type-face nil t))
609           (list (concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
610                 1 'font-lock-comment-face)
611           (cons (concat "^[ \t]*"
612                         "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
613                         "[>|}].*")
614                 'font-lock-reference-face)
615           '("^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):.*"
616             . font-lock-string-face)))
617   "Additional expressions to highlight in Message mode.")
618
619 (defvar message-face-alist
620   '((bold . bold-region)
621     (underline . underline-region)
622     (default . (lambda (b e) 
623                  (unbold-region b e)
624                  (ununderline-region b e))))
625   "Alist of mail and news faces for facemenu.
626 The cdr of ech entry is a function for applying the face to a region.")
627
628 (defcustom message-send-hook nil
629   "Hook run before sending messages."
630   :group 'message-various
631   :options '(ispell-message)
632   :type 'hook)
633
634 (defcustom message-send-mail-hook nil
635   "Hook run before sending mail messages."
636   :group 'message-various
637   :type 'hook)
638
639 (defcustom message-send-news-hook nil
640   "Hook run before sending news messages."
641   :group 'message-various
642   :type 'hook)
643
644 (defcustom message-sent-hook nil
645   "Hook run after sending messages."
646   :group 'message-various
647   :type 'hook)
648
649 ;;; Internal variables.
650
651 (defvar message-buffer-list nil)
652 (defvar message-this-is-news nil)
653 (defvar message-this-is-mail nil)
654
655 ;; Byte-compiler warning
656 (defvar gnus-active-hashtb)
657 (defvar gnus-read-active-file)
658
659 ;;; Regexp matching the delimiter of messages in UNIX mail format
660 ;;; (UNIX From lines), minus the initial ^.  
661 (defvar message-unix-mail-delimiter
662   (let ((time-zone-regexp
663          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
664                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
665                  "\\|"
666                  "\\) *")))
667     (concat
668      "From "
669
670      ;; Username, perhaps with a quoted section that can contain spaces.
671      "\\("
672      "[^ \n]*"
673      "\\(\\|\".*\"[^ \n]*\\)"
674      "\\|<[^<>\n]+>"
675      "\\)  ?"
676
677      ;; The time the message was sent.
678      "\\([^ \n]*\\) *"                  ; day of the week
679      "\\([^ ]*\\) *"                    ; month
680      "\\([0-9]*\\) *"                   ; day of month
681      "\\([0-9:]*\\) *"                  ; time of day
682
683      ;; Perhaps a time zone, specified by an abbreviation, or by a
684      ;; numeric offset.
685      time-zone-regexp
686
687      ;; The year.
688      " [0-9][0-9]\\([0-9]*\\) *"
689
690      ;; On some systems the time zone can appear after the year, too.
691      time-zone-regexp
692
693      ;; Old uucp cruft.
694      "\\(remote from .*\\)?"
695
696      "\n")))
697
698 (defvar message-unsent-separator
699   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
700           "^ *---+ +Returned message +---+ *$\\|"
701           "^Start of returned message$\\|"
702           "^ *---+ +Original message +---+ *$\\|"
703           "^ *--+ +begin message +--+ *$\\|"
704           "^ *---+ +Original message follows +---+ *$\\|"
705           "^|? *---+ +Message text follows: +---+ *|?$")
706   "A regexp that matches the separator before the text of a failed message.")
707
708 (defvar message-header-format-alist 
709   `((Newsgroups)
710     (To . message-fill-address) 
711     (Cc . message-fill-address)
712     (Subject)
713     (In-Reply-To)
714     (Fcc)
715     (Bcc)
716     (Date)
717     (Organization)
718     (Distribution)
719     (Lines)
720     (Expires)
721     (Message-ID)
722     (References)
723     (X-Mailer)
724     (X-Newsreader))
725   "Alist used for formatting headers.")
726
727 (eval-and-compile
728   (autoload 'message-setup-toolbar "messagexmas")
729   (autoload 'mh-send-letter "mh-comp")
730   (autoload 'gnus-point-at-eol "gnus-util")
731   (autoload 'gnus-point-at-bol "gnus-util")
732   (autoload 'gnus-output-to-mail "gnus-util")
733   (autoload 'gnus-output-to-rmail "gnus-util"))
734
735 \f
736
737 ;;; 
738 ;;; Utility functions.
739 ;;;
740
741 (defmacro message-y-or-n-p (question show &rest text)
742   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
743   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
744
745 ;; Delete the current line (and the next N lines.);
746 (defmacro message-delete-line (&optional n)
747   `(delete-region (progn (beginning-of-line) (point))
748                   (progn (forward-line ,(or n 1)) (point))))
749
750 (defun message-tokenize-header (header &optional separator)
751   "Split HEADER into a list of header elements.
752 \",\" is used as the separator."
753   (if (not header)
754       nil
755     (let ((regexp (format "[%s]+" (or separator ",")))
756           (beg 1)
757           (first t)
758           quoted elems paren)
759       (save-excursion
760         (message-set-work-buffer)
761         (insert header)
762         (goto-char (point-min))
763         (while (not (eobp))
764           (if first
765               (setq first nil)
766             (forward-char 1))
767           (cond ((and (> (point) beg)
768                       (or (eobp)
769                           (and (looking-at regexp)
770                                (not quoted)
771                                (not paren))))
772                  (push (buffer-substring beg (point)) elems)
773                  (setq beg (match-end 0)))
774                 ((= (following-char) ?\")
775                  (setq quoted (not quoted)))
776                 ((and (= (following-char) ?\()
777                       (not quoted))
778                  (setq paren t))
779                 ((and (= (following-char) ?\))
780                       (not quoted))
781                  (setq paren nil))))
782         (nreverse elems)))))
783
784 (defun message-fetch-field (header &optional not-all)
785   "The same as `mail-fetch-field', only remove all newlines."
786   (let ((value (mail-fetch-field header nil (not not-all))))
787     (when value
788       (nnheader-replace-chars-in-string value ?\n ? ))))
789
790 (defun message-fetch-reply-field (header)
791   "Fetch FIELD from the message we're replying to."
792   (when (and message-reply-buffer
793              (buffer-name message-reply-buffer))
794     (save-excursion
795       (set-buffer message-reply-buffer)
796       (message-fetch-field header))))
797
798 (defun message-set-work-buffer ()
799   (if (get-buffer " *message work*")
800       (progn
801         (set-buffer " *message work*")
802         (erase-buffer))
803     (set-buffer (get-buffer-create " *message work*"))
804     (kill-all-local-variables)
805     (buffer-disable-undo (current-buffer))))
806
807 (defun message-functionp (form)
808   "Return non-nil if FORM is funcallable."
809   (or (and (symbolp form) (fboundp form))
810       (and (listp form) (eq (car form) 'lambda))))
811
812 (defun message-strip-subject-re (subject)
813   "Remove \"Re:\" from subject lines."
814   (if (string-match "^[Rr][Ee]: *" subject)
815       (substring subject (match-end 0))
816     subject))
817
818 (defun message-remove-header (header &optional is-regexp first reverse)
819   "Remove HEADER in the narrowed buffer.
820 If REGEXP, HEADER is a regular expression.
821 If FIRST, only remove the first instance of the header.
822 Return the number of headers removed."
823   (goto-char (point-min))
824   (let ((regexp (if is-regexp header (concat "^" header ":")))
825         (number 0)
826         (case-fold-search t)
827         last)
828     (while (and (not (eobp))
829                 (not last))
830       (if (if reverse
831               (not (looking-at regexp))
832             (looking-at regexp))
833           (progn
834             (incf number)
835             (when first
836               (setq last t))
837             (delete-region
838              (point)
839              ;; There might be a continuation header, so we have to search
840              ;; until we find a new non-continuation line.
841              (progn
842                (forward-line 1)
843                (if (re-search-forward "^[^ \t]" nil t)
844                    (goto-char (match-beginning 0))
845                  (point-max)))))
846         (forward-line 1)
847         (if (re-search-forward "^[^ \t]" nil t)
848             (goto-char (match-beginning 0))
849           (point-max))))
850     number))
851
852 (defun message-narrow-to-headers ()
853   "Narrow the buffer to the head of the message."
854   (widen)
855   (narrow-to-region
856    (goto-char (point-min))
857    (if (re-search-forward
858         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
859        (match-beginning 0)
860      (point-max)))
861   (goto-char (point-min)))
862
863 (defun message-narrow-to-head ()
864   "Narrow the buffer to the head of the message."
865   (widen)
866   (narrow-to-region
867    (goto-char (point-min))
868    (if (search-forward "\n\n" nil 1)
869        (1- (point))
870      (point-max)))
871   (goto-char (point-min)))
872
873 (defun message-news-p ()
874   "Say whether the current buffer contains a news message."
875   (or message-this-is-news
876       (save-excursion
877         (save-restriction
878           (message-narrow-to-headers)
879           (message-fetch-field "newsgroups")))))
880
881 (defun message-mail-p ()
882   "Say whether the current buffer contains a mail message."
883   (or message-this-is-mail
884       (save-excursion
885         (save-restriction
886           (message-narrow-to-headers)
887           (or (message-fetch-field "to")
888               (message-fetch-field "cc")
889               (message-fetch-field "bcc"))))))
890
891 (defun message-next-header ()
892   "Go to the beginning of the next header."
893   (beginning-of-line)
894   (or (eobp) (forward-char 1))
895   (not (if (re-search-forward "^[^ \t]" nil t)
896            (beginning-of-line)
897          (goto-char (point-max)))))
898     
899 (defun message-sort-headers-1 ()
900   "Sort the buffer as headers using `message-rank' text props."
901   (goto-char (point-min))
902   (sort-subr 
903    nil 'message-next-header 
904    (lambda ()
905      (message-next-header)
906      (unless (bobp)
907        (forward-char -1)))
908    (lambda ()
909      (or (get-text-property (point) 'message-rank)
910          10000))))
911
912 (defun message-sort-headers ()
913   "Sort the headers of the current message according to `message-header-format-alist'."
914   (interactive)
915   (save-excursion
916     (save-restriction
917       (let ((max (1+ (length message-header-format-alist)))
918             rank)
919         (message-narrow-to-headers)
920         (while (re-search-forward "^[^ \n]+:" nil t)
921           (put-text-property
922            (match-beginning 0) (1+ (match-beginning 0))
923            'message-rank
924            (if (setq rank (length (memq (assq (intern (buffer-substring
925                                                        (match-beginning 0)
926                                                        (1- (match-end 0))))
927                                               message-header-format-alist)
928                                         message-header-format-alist)))
929                (- max rank)
930              (1+ max)))))
931       (message-sort-headers-1))))
932
933 \f
934
935 ;;;
936 ;;; Message mode
937 ;;;
938
939 ;;; Set up keymap.
940
941 (defvar message-mode-map nil)
942
943 (unless message-mode-map
944   (setq message-mode-map (copy-keymap text-mode-map))
945   (define-key message-mode-map "\C-c?" 'describe-mode)
946
947   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
948   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
949   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
950   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
951   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
952   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
953   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
954   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
955   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
956   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
957   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
958   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
959   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
960
961   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
962   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
963   
964   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
965   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
966   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
967   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
968   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
969   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
970
971   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
972   (define-key message-mode-map "\C-c\C-s" 'message-send)
973   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
974   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
975
976   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
977
978   (define-key message-mode-map "\t" 'message-tab))
979
980 (easy-menu-define 
981  message-mode-menu message-mode-map "Message Menu."
982  '("Message"
983    ["Sort Headers" message-sort-headers t]
984    ["Yank Original" message-yank-original t]
985    ["Fill Yanked Message" message-fill-yanked-message t]
986    ["Insert Signature" message-insert-signature t]
987    ["Caesar (rot13) Message" message-caesar-buffer-body t]
988    ["Caesar (rot13) Region" message-caesar-region (mark t)]
989    ["Elide Region" message-elide-region (mark t)]
990    ["Rename buffer" message-rename-buffer t]
991    ["Spellcheck" ispell-message t]
992    "----"
993    ["Send Message" message-send-and-exit t]
994    ["Abort Message" message-dont-send t]))
995
996 (easy-menu-define 
997  message-mode-field-menu message-mode-map ""
998  '("Field"
999    ["Fetch To" message-insert-to t]
1000    ["Fetch Newsgroups" message-insert-newsgroups t]
1001    "----"
1002    ["To" message-goto-to t]
1003    ["Subject" message-goto-subject t]
1004    ["Cc" message-goto-cc t]
1005    ["Reply-To" message-goto-reply-to t]
1006    ["Summary" message-goto-summary t]
1007    ["Keywords" message-goto-keywords t]
1008    ["Newsgroups" message-goto-newsgroups t]
1009    ["Followup-To" message-goto-followup-to t]
1010    ["Distribution" message-goto-distribution t]
1011    ["Body" message-goto-body t]
1012    ["Signature" message-goto-signature t]))
1013
1014 (defvar facemenu-add-face-function)
1015 (defvar facemenu-remove-face-function)
1016
1017 ;;;###autoload
1018 (defun message-mode ()
1019   "Major mode for editing mail and news to be sent.
1020 Like Text Mode but with these additional commands:
1021 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1022 C-c C-f  move to a header field (and create it if there isn't):
1023          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1024          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1025          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1026          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1027          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1028          C-c C-f C-f  move to Followup-To
1029 C-c C-t  message-insert-to (add a To header to a news followup)
1030 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1031 C-c C-b  message-goto-body (move to beginning of message text).
1032 C-c C-i  message-goto-signature (move to the beginning of the signature).
1033 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1034 C-c C-y  message-yank-original (insert current message, if any).
1035 C-c C-q  message-fill-yanked-message (fill what was yanked).
1036 C-c C-e  message-elide-region (elide the text between point and mark).
1037 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1038   (interactive)
1039   (kill-all-local-variables)
1040   (make-local-variable 'message-reply-buffer)
1041   (setq message-reply-buffer nil)
1042   (set (make-local-variable 'message-send-actions) nil)
1043   (set (make-local-variable 'message-exit-actions) nil)
1044   (set (make-local-variable 'message-kill-actions) nil)
1045   (set (make-local-variable 'message-postpone-actions) nil)
1046   (set-syntax-table message-mode-syntax-table)
1047   (use-local-map message-mode-map)
1048   (setq local-abbrev-table message-mode-abbrev-table)
1049   (setq major-mode 'message-mode)
1050   (setq mode-name "Message")
1051   (setq buffer-offer-save t)
1052   (make-local-variable 'font-lock-defaults)
1053   (setq font-lock-defaults '(message-font-lock-keywords t))
1054   (make-local-variable 'facemenu-add-face-function)
1055   (make-local-variable 'facemenu-remove-face-function)
1056   (setq facemenu-add-face-function
1057         (lambda (face end)
1058           (let ((face-fun (cdr (assq face message-face-alist))))
1059             (if face-fun
1060                 (funcall face-fun (point) end)
1061               (error "Face %s not configured for %s mode" face mode-name)))
1062           "")
1063         facemenu-remove-face-function t)
1064   (make-local-variable 'paragraph-separate)
1065   (make-local-variable 'paragraph-start)
1066   (setq paragraph-start (concat (regexp-quote mail-header-separator)
1067                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1068                                 "-- $\\|"
1069                                 paragraph-start))
1070   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
1071                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
1072                                    "-- $\\|"
1073                                    paragraph-separate))
1074   (make-local-variable 'message-reply-headers)
1075   (setq message-reply-headers nil)
1076   (make-local-variable 'message-newsreader)
1077   (make-local-variable 'message-mailer)
1078   (make-local-variable 'message-post-method)
1079   (make-local-variable 'message-sent-message-via)
1080   (setq message-sent-message-via nil)
1081   (make-local-variable 'message-checksum)
1082   (setq message-checksum nil)
1083   ;;(when (fboundp 'mail-hist-define-keys)
1084   ;;  (mail-hist-define-keys))
1085   (when (string-match "XEmacs\\|Lucid" emacs-version)
1086     (message-setup-toolbar))
1087   (easy-menu-add message-mode-menu message-mode-map)
1088   (easy-menu-add message-mode-field-menu message-mode-map)
1089   ;; Allow mail alias things.
1090   (if (fboundp 'mail-abbrevs-setup)
1091       (mail-abbrevs-setup)
1092     (funcall (intern "mail-aliases-setup")))
1093   (run-hooks 'text-mode-hook 'message-mode-hook))
1094
1095 \f
1096
1097 ;;;
1098 ;;; Message mode commands
1099 ;;;
1100
1101 ;;; Movement commands
1102
1103 (defun message-goto-to ()
1104   "Move point to the To header."
1105   (interactive)
1106   (message-position-on-field "To"))
1107
1108 (defun message-goto-subject ()
1109   "Move point to the Subject header."
1110   (interactive)
1111   (message-position-on-field "Subject"))
1112
1113 (defun message-goto-cc ()
1114   "Move point to the Cc header."
1115   (interactive)
1116   (message-position-on-field "Cc" "To"))
1117
1118 (defun message-goto-bcc ()
1119   "Move point to the Bcc  header."
1120   (interactive)
1121   (message-position-on-field "Bcc" "Cc" "To"))
1122
1123 (defun message-goto-fcc ()
1124   "Move point to the Fcc header."
1125   (interactive)
1126   (message-position-on-field "Fcc" "To" "Newsgroups"))
1127
1128 (defun message-goto-reply-to ()
1129   "Move point to the Reply-To header."
1130   (interactive)
1131   (message-position-on-field "Reply-To" "Subject"))
1132
1133 (defun message-goto-newsgroups ()
1134   "Move point to the Newsgroups header."
1135   (interactive)
1136   (message-position-on-field "Newsgroups"))
1137
1138 (defun message-goto-distribution ()
1139   "Move point to the Distribution header."
1140   (interactive)
1141   (message-position-on-field "Distribution"))
1142
1143 (defun message-goto-followup-to ()
1144   "Move point to the Followup-To header."
1145   (interactive)
1146   (message-position-on-field "Followup-To" "Newsgroups"))
1147
1148 (defun message-goto-keywords ()
1149   "Move point to the Keywords header."
1150   (interactive)
1151   (message-position-on-field "Keywords" "Subject"))
1152
1153 (defun message-goto-summary ()
1154   "Move point to the Summary header."
1155   (interactive)
1156   (message-position-on-field "Summary" "Subject"))
1157
1158 (defun message-goto-body ()
1159   "Move point to the beginning of the message body."
1160   (interactive)
1161   (if (looking-at "[ \t]*\n") (expand-abbrev))
1162   (goto-char (point-min))
1163   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1164
1165 (defun message-goto-signature ()
1166   "Move point to the beginning of the message signature."
1167   (interactive)
1168   (goto-char (point-min))
1169   (if (re-search-forward message-signature-separator nil t)
1170       (forward-line 1)
1171     (goto-char (point-max))))
1172
1173 \f
1174
1175 (defun message-insert-to ()
1176   "Insert a To header that points to the author of the article being replied to."
1177   (interactive)
1178   (let ((co (message-fetch-field "courtesy-copies-to")))
1179     (when (and co 
1180                (equal (downcase co) "never"))
1181       (error "The user has requested not to have copies sent via mail")))
1182   (when (and (message-position-on-field "To")
1183              (mail-fetch-field "to")
1184              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1185     (insert ", "))
1186   (insert (or (message-fetch-reply-field "reply-to")
1187               (message-fetch-reply-field "from") "")))
1188
1189 (defun message-insert-newsgroups ()
1190   "Insert the Newsgroups header from the article being replied to."
1191   (interactive)
1192   (when (and (message-position-on-field "Newsgroups")
1193              (mail-fetch-field "newsgroups")
1194              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1195     (insert ","))
1196   (insert (or (message-fetch-reply-field "newsgroups") "")))
1197
1198 \f
1199
1200 ;;; Various commands
1201
1202 (defun message-insert-signature (&optional force)
1203   "Insert a signature.  See documentation for the `message-signature' variable."
1204   (interactive (list 0))
1205   (let* ((signature 
1206           (cond
1207            ((and (null message-signature)
1208                  (eq force 0))
1209             (save-excursion
1210               (goto-char (point-max))
1211               (not (re-search-backward
1212                     message-signature-separator nil t))))
1213            ((and (null message-signature)
1214                  force)
1215             t)
1216            ((message-functionp message-signature)
1217             (funcall message-signature))
1218            ((listp message-signature)
1219             (eval message-signature))
1220            (t message-signature)))
1221          (signature
1222           (cond ((stringp signature)
1223                  signature)
1224                 ((and (eq t signature)
1225                       message-signature-file
1226                       (file-exists-p message-signature-file))
1227                  signature))))
1228     (when signature
1229       (goto-char (point-max))
1230       ;; Insert the signature.
1231       (unless (bolp)
1232         (insert "\n"))
1233       (insert "\n-- \n")
1234       (if (eq signature t)
1235           (insert-file-contents message-signature-file)
1236         (insert signature))
1237       (goto-char (point-max))
1238       (or (bolp) (insert "\n")))))
1239
1240 (defun message-elide-region (b e)
1241   "Elide the text between point and mark.  An ellipsis (from
1242 message-elide-elipsis) will be inserted where the text was killed."
1243   (interactive "r")
1244   (kill-region b e)
1245   (unless (bolp)
1246     (insert "\n"))
1247   (insert message-elide-elipsis))
1248
1249 (defvar message-caesar-translation-table nil)
1250
1251 (defun message-caesar-region (b e &optional n)
1252   "Caesar rotation of region by N, default 13, for decrypting netnews."
1253   (interactive
1254    (list
1255     (min (point) (or (mark t) (point)))
1256     (max (point) (or (mark t) (point)))
1257     (when current-prefix-arg
1258       (prefix-numeric-value current-prefix-arg))))
1259
1260   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1261   (unless (or (zerop n)                 ; no action needed for a rot of 0
1262               (= b e))                  ; no region to rotate
1263     ;; We build the table, if necessary.
1264     (when (or (not message-caesar-translation-table)
1265               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1266         (setq message-caesar-translation-table
1267               (message-make-caesar-translation-table n)))
1268     ;; Then we translate the region.  Do it this way to retain 
1269     ;; text properties.
1270     (while (< b e)
1271       (subst-char-in-region 
1272        b (1+ b) (char-after b)
1273        (aref message-caesar-translation-table (char-after b)))
1274       (incf b))))
1275
1276 (defun message-make-caesar-translation-table (n)
1277   "Create a rot table with offset N."
1278   (let ((i -1) 
1279         (table (make-string 256 0)))
1280     (while (< (incf i) 256)
1281       (aset table i i))
1282     (concat
1283      (substring table 0 ?A)
1284      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1285      (substring table ?A (+ ?A n))
1286      (substring table (+ ?A 26) ?a)
1287      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1288      (substring table ?a (+ ?a n))
1289      (substring table (+ ?a 26) 255))))
1290
1291 (defun message-caesar-buffer-body (&optional rotnum)
1292   "Caesar rotates all letters in the current buffer by 13 places.
1293 Used to encode/decode possibly offensive messages (commonly in net.jokes).
1294 With prefix arg, specifies the number of places to rotate each letter forward.
1295 Mail and USENET news headers are not rotated."
1296   (interactive (if current-prefix-arg
1297                    (list (prefix-numeric-value current-prefix-arg))
1298                  (list nil)))
1299   (save-excursion
1300     (save-restriction
1301       (when (message-goto-body)
1302         (narrow-to-region (point) (point-max)))
1303       (message-caesar-region (point-min) (point-max) rotnum))))
1304
1305 (defun message-pipe-buffer-body (program)
1306   "Pipe the message body in the current buffer through PROGRAM."
1307   (save-excursion
1308     (save-restriction
1309       (when (message-goto-body)
1310         (narrow-to-region (point) (point-max)))
1311       (let ((body (buffer-substring (point-min) (point-max))))
1312         (unless (equal 0 (call-process-region
1313                            (point-min) (point-max) program t t))
1314             (insert body)
1315             (gnus-message 1 "%s failed." program))))))
1316
1317 (defun message-rename-buffer (&optional enter-string)
1318   "Rename the *message* buffer to \"*message* RECIPIENT\".  
1319 If the function is run with a prefix, it will ask for a new buffer
1320 name, rather than giving an automatic name."
1321   (interactive "Pbuffer name: ")
1322   (save-excursion
1323     (save-restriction
1324       (goto-char (point-min))
1325       (narrow-to-region (point) 
1326                         (search-forward mail-header-separator nil 'end))
1327       (let* ((mail-to (or
1328                        (if (message-news-p) (message-fetch-field "Newsgroups")
1329                          (message-fetch-field "To"))
1330                        ""))
1331              (mail-trimmed-to
1332               (if (string-match "," mail-to)
1333                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1334                 mail-to))
1335              (name-default (concat "*message* " mail-trimmed-to))
1336              (name (if enter-string
1337                        (read-string "New buffer name: " name-default)
1338                      name-default))
1339              (default-directory
1340                (file-name-as-directory message-autosave-directory)))
1341         (rename-buffer name t)))))
1342
1343 (defun message-fill-yanked-message (&optional justifyp)
1344   "Fill the paragraphs of a message yanked into this one.
1345 Numeric argument means justify as well."
1346   (interactive "P")
1347   (save-excursion
1348     (goto-char (point-min))
1349     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1350     (let ((fill-prefix message-yank-prefix))
1351       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1352
1353 (defun message-indent-citation ()
1354   "Modify text just inserted from a message to be cited.
1355 The inserted text should be the region.
1356 When this function returns, the region is again around the modified text.
1357
1358 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1359 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1360   (let ((start (point)))
1361     ;; Remove unwanted headers.
1362     (when message-ignored-cited-headers
1363       (save-restriction
1364         (narrow-to-region 
1365          (goto-char start)
1366          (if (search-forward "\n\n" nil t)
1367              (1- (point))
1368            (point)))
1369         (message-remove-header message-ignored-cited-headers t)
1370         (goto-char (point-max))))
1371     ;; Delete blank lines at the start of the buffer.
1372     (while (and (point-min)
1373                 (eolp)
1374                 (not (eobp)))
1375       (message-delete-line))
1376     ;; Delete blank lines at the end of the buffer.
1377     (goto-char (point-max))
1378     (unless (eolp)
1379       (insert "\n"))
1380     (while (and (zerop (forward-line -1))
1381                 (looking-at "$"))
1382       (message-delete-line))
1383     ;; Do the indentation.
1384     (if (null message-yank-prefix)
1385         (indent-rigidly start (mark t) message-indentation-spaces)
1386       (save-excursion
1387         (goto-char start)
1388         (while (< (point) (mark t))
1389           (insert message-yank-prefix)
1390           (forward-line 1))))
1391     (goto-char start)))
1392
1393 (defun message-yank-original (&optional arg)
1394   "Insert the message being replied to, if any.
1395 Puts point before the text and mark after.
1396 Normally indents each nonblank line ARG spaces (default 3).  However,
1397 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1398
1399 This function uses `message-cite-function' to do the actual citing.
1400
1401 Just \\[universal-argument] as argument means don't indent, insert no
1402 prefix, and don't delete any headers."
1403   (interactive "P")
1404   (let ((modified (buffer-modified-p)))
1405     (when (and message-reply-buffer
1406                message-cite-function)
1407       (delete-windows-on message-reply-buffer t)
1408       (insert-buffer message-reply-buffer)
1409       (funcall message-cite-function)
1410       (message-exchange-point-and-mark)
1411       (unless (bolp)
1412         (insert ?\n))
1413       (unless modified
1414         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1415
1416 (defun message-cite-original ()
1417   "Cite function in the standard Message manner."
1418   (let ((start (point))
1419         (functions 
1420          (when message-indent-citation-function
1421            (if (listp message-indent-citation-function)
1422                message-indent-citation-function
1423              (list message-indent-citation-function)))))
1424     (goto-char start)
1425     (while functions
1426       (funcall (pop functions)))
1427     (when message-citation-line-function
1428       (unless (bolp)
1429         (insert "\n"))
1430       (funcall message-citation-line-function))))
1431
1432 (defun message-insert-citation-line ()
1433   "Function that inserts a simple citation line."
1434   (when message-reply-headers
1435     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1436
1437 (defun message-position-on-field (header &rest afters)
1438   (let ((case-fold-search t))
1439     (save-restriction
1440       (narrow-to-region
1441        (goto-char (point-min))
1442        (progn
1443          (re-search-forward 
1444           (concat "^" (regexp-quote mail-header-separator) "$"))
1445          (match-beginning 0)))
1446       (goto-char (point-min))
1447       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1448           (progn
1449             (re-search-forward "^[^ \t]" nil 'move)
1450             (beginning-of-line)
1451             (skip-chars-backward "\n")
1452             t)
1453         (while (and afters
1454                     (not (re-search-forward 
1455                           (concat "^" (regexp-quote (car afters)) ":")
1456                           nil t)))
1457           (pop afters))
1458         (when afters
1459           (re-search-forward "^[^ \t]" nil 'move)
1460           (beginning-of-line))
1461         (insert header ": \n")
1462         (forward-char -1)
1463         nil))))
1464
1465 (defun message-remove-signature ()
1466   "Remove the signature from the text between point and mark.
1467 The text will also be indented the normal way."
1468   (save-excursion
1469     (let ((start (point))
1470           mark)
1471       (if (not (re-search-forward message-signature-separator (mark t) t))
1472           ;; No signature here, so we just indent the cited text.
1473           (message-indent-citation)
1474         ;; Find the last non-empty line.
1475         (forward-line -1)
1476         (while (looking-at "[ \t]*$")
1477           (forward-line -1))
1478         (forward-line 1)
1479         (setq mark (set-marker (make-marker) (point)))
1480         (goto-char start)
1481         (message-indent-citation)
1482         ;; Enable undoing the deletion.
1483         (undo-boundary)
1484         (delete-region mark (mark t))
1485         (set-marker mark nil)))))
1486
1487 \f
1488
1489 ;;;
1490 ;;; Sending messages
1491 ;;;
1492
1493 (defun message-send-and-exit (&optional arg)
1494   "Send message like `message-send', then, if no errors, exit from mail buffer."
1495   (interactive "P")
1496   (let ((buf (current-buffer))
1497         (actions message-exit-actions))
1498     (when (and (message-send arg)
1499                (buffer-name buf))
1500       (if message-kill-buffer-on-exit
1501           (kill-buffer buf)
1502         (bury-buffer buf)
1503         (when (eq buf (current-buffer))
1504           (message-bury buf)))
1505       (message-do-actions actions))))
1506
1507 (defun message-dont-send ()
1508   "Don't send the message you have been editing."
1509   (interactive)
1510   (let ((actions message-postpone-actions))
1511     (message-bury (current-buffer))
1512     (message-do-actions actions)))
1513
1514 (defun message-kill-buffer ()
1515   "Kill the current buffer."
1516   (interactive)
1517   (let ((actions message-kill-actions))
1518     (kill-buffer (current-buffer))
1519     (message-do-actions actions)))
1520
1521 (defun message-bury (buffer)
1522   "Bury this mail buffer."
1523   (let ((newbuf (other-buffer buffer)))
1524     (bury-buffer buffer)
1525     (if (and (fboundp 'frame-parameters)
1526              (cdr (assq 'dedicated (frame-parameters)))
1527              (not (null (delq (selected-frame) (visible-frame-list)))))
1528         (delete-frame (selected-frame))
1529       (switch-to-buffer newbuf))))
1530
1531 (defun message-send (&optional arg)
1532   "Send the message in the current buffer.
1533 If `message-interactive' is non-nil, wait for success indication
1534 or error messages, and inform user.
1535 Otherwise any failure is reported in a message back to
1536 the user from the mailer."
1537   (interactive "P")
1538   (when (if buffer-file-name
1539             (y-or-n-p (format "Send buffer contents as %s message? "
1540                               (if (message-mail-p)
1541                                   (if (message-news-p) "mail and news" "mail")
1542                                 "news")))
1543           (or (buffer-modified-p)
1544               (y-or-n-p "No changes in the buffer; really send? ")))
1545     ;; Make it possible to undo the coming changes.
1546     (undo-boundary)
1547     (let ((inhibit-read-only t))
1548       (put-text-property (point-min) (point-max) 'read-only nil))
1549     (message-fix-before-sending)
1550     (run-hooks 'message-send-hook)
1551     (message "Sending...")
1552     (when (and (or (not (message-news-p))
1553                    (and (or (not (memq 'news message-sent-message-via))
1554                             (y-or-n-p
1555                              "Already sent message via news; resend? "))
1556                         (funcall message-send-news-function arg)))
1557                (or (not (message-mail-p))
1558                    (and (or (not (memq 'mail message-sent-message-via))
1559                             (y-or-n-p
1560                              "Already sent message via mail; resend? "))
1561                         (message-send-mail arg))))
1562       (message-do-fcc)
1563       ;;(when (fboundp 'mail-hist-put-headers-into-history)
1564       ;; (mail-hist-put-headers-into-history))
1565       (run-hooks 'message-sent-hook)
1566       (message "Sending...done")
1567       ;; If buffer has no file, mark it as unmodified and delete autosave.
1568       (unless buffer-file-name
1569         (set-buffer-modified-p nil)
1570         (delete-auto-save-file-if-necessary t))
1571       ;; Delete other mail buffers and stuff.
1572       (message-do-send-housekeeping)
1573       (message-do-actions message-send-actions)
1574       ;; Return success.
1575       t)))
1576
1577 (defun message-fix-before-sending ()
1578   "Do various things to make the message nice before sending it."
1579   ;; Make sure there's a newline at the end of the message.
1580   (goto-char (point-max))
1581   (unless (bolp)
1582     (insert "\n")))
1583
1584 (defun message-add-action (action &rest types)
1585   "Add ACTION to be performed when doing an exit of type TYPES."
1586   (let (var)
1587     (while types
1588       (set (setq var (intern (format "message-%s-actions" (pop types))))
1589            (nconc (symbol-value var) (list action))))))
1590
1591 (defun message-do-actions (actions)
1592   "Perform all actions in ACTIONS."
1593   ;; Now perform actions on successful sending.
1594   (while actions
1595     (ignore-errors
1596       (cond 
1597        ;; A simple function.
1598        ((message-functionp (car actions))
1599         (funcall (car actions)))
1600        ;; Something to be evaled.
1601        (t
1602         (eval (car actions)))))
1603     (pop actions)))
1604
1605 (defun message-send-mail (&optional arg)
1606   (require 'mail-utils)
1607   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1608         (case-fold-search nil)
1609         (news (message-news-p))
1610         (mailbuf (current-buffer)))
1611     (save-restriction
1612       (message-narrow-to-headers)
1613       ;; Insert some headers.
1614       (let ((message-deletable-headers
1615              (if news nil message-deletable-headers)))
1616         (message-generate-headers message-required-mail-headers))
1617       ;; Let the user do all of the above.
1618       (run-hooks 'message-header-hook))
1619     (unwind-protect
1620         (save-excursion
1621           (set-buffer tembuf)
1622           (erase-buffer)
1623           ;; Avoid copying text props.
1624           (insert (format 
1625                    "%s" (save-excursion
1626                           (set-buffer mailbuf)
1627                           (buffer-string))))
1628           ;; Remove some headers.
1629           (save-restriction
1630             (message-narrow-to-headers)
1631             ;; Remove some headers.
1632             (message-remove-header message-ignored-mail-headers t))
1633           (goto-char (point-max))
1634           ;; require one newline at the end.
1635           (or (= (preceding-char) ?\n)
1636               (insert ?\n))
1637           (when (and news
1638                      (or (message-fetch-field "cc")
1639                          (message-fetch-field "to")))
1640             (message-insert-courtesy-copy))
1641           (funcall message-send-mail-function))
1642       (kill-buffer tembuf))
1643     (set-buffer mailbuf)
1644     (push 'mail message-sent-message-via)))
1645
1646 (defun message-send-mail-with-sendmail ()
1647   "Send off the prepared buffer with sendmail."
1648   (let ((errbuf (if message-interactive
1649                     (generate-new-buffer " sendmail errors")
1650                   0))
1651         resend-to-addresses delimline)
1652     (let ((case-fold-search t))
1653       (save-restriction
1654         (message-narrow-to-headers)
1655         (setq resend-to-addresses (message-fetch-field "resent-to")))
1656       ;; Change header-delimiter to be what sendmail expects.
1657       (goto-char (point-min))
1658       (re-search-forward
1659        (concat "^" (regexp-quote mail-header-separator) "\n"))
1660       (replace-match "\n")
1661       (backward-char 1)
1662       (setq delimline (point-marker))
1663       (run-hooks 'message-send-mail-hook)
1664       ;; Insert an extra newline if we need it to work around
1665       ;; Sun's bug that swallows newlines.
1666       (goto-char (1+ delimline))
1667       (when (eval message-mailer-swallows-blank-line)
1668         (newline))
1669       (when message-interactive
1670         (save-excursion
1671           (set-buffer errbuf)
1672           (erase-buffer))))
1673     (let ((default-directory "/"))
1674       (apply 'call-process-region
1675              (append (list (point-min) (point-max)
1676                            (if (boundp 'sendmail-program)
1677                                sendmail-program
1678                              "/usr/lib/sendmail")
1679                            nil errbuf nil "-oi")
1680                      ;; Always specify who from,
1681                      ;; since some systems have broken sendmails.
1682                      ;; But some systems are more broken with -f, so
1683                      ;; we'll let users override this.
1684                      (if (null message-sendmail-f-is-evil)
1685                          (list "-f" (user-login-name)))
1686                      ;; These mean "report errors by mail"
1687                      ;; and "deliver in background".
1688                      (if (null message-interactive) '("-oem" "-odb"))
1689                      ;; Get the addresses from the message
1690                      ;; unless this is a resend.
1691                      ;; We must not do that for a resend
1692                      ;; because we would find the original addresses.
1693                      ;; For a resend, include the specific addresses.
1694                      (if resend-to-addresses
1695                          (list resend-to-addresses)
1696                        '("-t")))))
1697     (when message-interactive
1698       (save-excursion
1699         (set-buffer errbuf)
1700         (goto-char (point-min))
1701         (while (re-search-forward "\n\n* *" nil t)
1702           (replace-match "; "))
1703         (if (not (zerop (buffer-size)))
1704             (error "Sending...failed to %s"
1705                    (buffer-substring (point-min) (point-max)))))
1706       (when (bufferp errbuf)
1707         (kill-buffer errbuf)))))
1708
1709 (defun message-send-mail-with-qmail ()
1710   "Pass the prepared message buffer to qmail-inject.
1711 Refer to the documentation for the variable `message-send-mail-function'
1712 to find out how to use this."
1713   ;; replace the header delimiter with a blank line
1714   (goto-char (point-min))
1715   (re-search-forward
1716    (concat "^" (regexp-quote mail-header-separator) "\n"))
1717   (replace-match "\n")
1718   (run-hooks 'message-send-mail-hook)
1719   ;; send the message
1720   (case
1721       (apply
1722        'call-process-region 1 (point-max) message-qmail-inject-program
1723        nil nil nil
1724        ;; qmail-inject's default behaviour is to look for addresses on the
1725        ;; command line; if there're none, it scans the headers.
1726        ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
1727        ;;
1728        ;; in general, ALL of qmail-inject's defaults are perfect for simply
1729        ;; reading a formatted (i. e., at least a To: or Resent-To header)
1730        ;; message from stdin.
1731        ;;
1732        ;; qmail also has the advantage of not having been raped by
1733        ;; various vendors, so we don't have to allow for that, either --
1734        ;; compare this with message-send-mail-with-sendmail and weep 
1735        ;; for sendmail's lost innocence.
1736        ;;
1737        ;; all this is way cool coz it lets us keep the arguments entirely
1738        ;; free for -inject-arguments -- a big win for the user and for us
1739        ;; since we don't have to play that double-guessing game and the user
1740        ;; gets full control (no gestapo'ish -f's, for instance).  --sj
1741        message-qmail-inject-args)
1742     ;; qmail-inject doesn't say anything on it's stdout/stderr,
1743     ;; we have to look at the retval instead
1744     (0 nil)
1745     (1   (error "qmail-inject reported permanent failure."))
1746     (111 (error "qmail-inject reported transient failure."))
1747     ;; should never happen
1748     (t   (error "qmail-inject reported unknown failure."))))
1749
1750 (defun message-send-mail-with-mh ()
1751   "Send the prepared message buffer with mh."
1752   (let ((mh-previous-window-config nil)
1753         (name (make-temp-name
1754                (concat (file-name-as-directory 
1755                         (expand-file-name message-autosave-directory))
1756                        "msg."))))
1757     (setq buffer-file-name name)
1758     ;; MH wants to generate these headers itself.
1759     (when message-mh-deletable-headers
1760       (let ((headers message-mh-deletable-headers))
1761         (while headers
1762           (goto-char (point-min)) 
1763           (and (re-search-forward 
1764                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1765                (message-delete-line))
1766           (pop headers))))
1767     (run-hooks 'message-send-mail-hook)
1768     ;; Pass it on to mh.
1769     (mh-send-letter)))
1770
1771 (defun message-send-news (&optional arg)
1772   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
1773         (case-fold-search nil)
1774         (method (if (message-functionp message-post-method)
1775                     (funcall message-post-method arg)
1776                   message-post-method))
1777         (messbuf (current-buffer))
1778         (message-syntax-checks
1779          (if arg
1780              (cons '(existing-newsgroups . disabled)
1781                    message-syntax-checks)
1782            message-syntax-checks))
1783         result)
1784     (save-restriction
1785       (message-narrow-to-headers)
1786       ;; Insert some headers.
1787       (message-generate-headers message-required-news-headers)
1788       ;; Let the user do all of the above.
1789       (run-hooks 'message-header-hook))
1790     (message-cleanup-headers)
1791     (if (not (message-check-news-syntax))
1792         (progn
1793           ;;(message "Posting not performed")
1794           nil)
1795       (unwind-protect
1796           (save-excursion
1797             (set-buffer tembuf)
1798             (buffer-disable-undo (current-buffer))
1799             (erase-buffer) 
1800             ;; Avoid copying text props.
1801             (insert (format 
1802                      "%s" (save-excursion
1803                             (set-buffer messbuf)
1804                             (buffer-string))))
1805             ;; Remove some headers.
1806             (save-restriction
1807               (message-narrow-to-headers)
1808               ;; Remove some headers.
1809               (message-remove-header message-ignored-news-headers t))
1810             (goto-char (point-max))
1811             ;; require one newline at the end.
1812             (or (= (preceding-char) ?\n)
1813                 (insert ?\n))
1814             (let ((case-fold-search t))
1815               ;; Remove the delimiter.
1816               (goto-char (point-min))
1817               (re-search-forward
1818                (concat "^" (regexp-quote mail-header-separator) "\n"))
1819               (replace-match "\n")
1820               (backward-char 1))
1821             (run-hooks 'message-send-news-hook)
1822             (require (car method))
1823             (funcall (intern (format "%s-open-server" (car method)))
1824                      (cadr method) (cddr method))
1825             (setq result
1826                   (funcall (intern (format "%s-request-post" (car method))))))
1827         (kill-buffer tembuf))
1828       (set-buffer messbuf)
1829       (if result
1830           (push 'news message-sent-message-via)
1831         (message "Couldn't send message via news: %s"
1832                  (nnheader-get-report (car method)))
1833         nil))))
1834
1835 ;;;
1836 ;;; Header generation & syntax checking.
1837 ;;;
1838
1839 (defmacro message-check (type &rest forms)
1840   "Eval FORMS if TYPE is to be checked."
1841   `(or (message-check-element ,type)
1842        (save-excursion
1843          ,@forms)))
1844
1845 (put 'message-check 'lisp-indent-function 1)
1846 (put 'message-check 'edebug-form-spec '(form body))
1847
1848 (defun message-check-element (type)
1849   "Returns non-nil if this type is not to be checked."
1850   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1851       t
1852     (let ((able (assq type message-syntax-checks)))
1853       (and (consp able)
1854            (eq (cdr able) 'disabled)))))
1855
1856 (defun message-check-news-syntax ()
1857   "Check the syntax of the message."
1858   (save-excursion
1859     (save-restriction
1860       (widen)
1861       (and 
1862        ;; We narrow to the headers and check them first.
1863        (save-excursion
1864          (save-restriction
1865            (message-narrow-to-headers)
1866            (message-check-news-header-syntax)))
1867        ;; Check the body.
1868        (message-check-news-body-syntax)))))
1869
1870 (defun message-check-news-header-syntax ()
1871   (and 
1872    ;; Check for commands in Subject.
1873    (message-check 'subject-cmsg
1874      (if (string-match "^cmsg " (message-fetch-field "subject"))
1875          (y-or-n-p
1876           "The control code \"cmsg\" is in the subject.  Really post? ")
1877        t))
1878    ;; Check for multiple identical headers.
1879    (message-check 'multiple-headers
1880      (let (found)
1881        (while (and (not found) 
1882                    (re-search-forward "^[^ \t:]+: " nil t))
1883          (save-excursion
1884            (or (re-search-forward 
1885                 (concat "^" 
1886                         (regexp-quote
1887                          (setq found
1888                                (buffer-substring
1889                                 (match-beginning 0) (- (match-end 0) 2))))
1890                         ":")
1891                 nil t)
1892                (setq found nil))))
1893        (if found
1894            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
1895          t)))
1896    ;; Check for Version and Sendsys.
1897    (message-check 'sendsys
1898      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1899          (y-or-n-p
1900           (format "The article contains a %s command.  Really post? "
1901                   (buffer-substring (match-beginning 0) 
1902                                     (1- (match-end 0)))))
1903        t))
1904    ;; See whether we can shorten Followup-To.
1905    (message-check 'shorten-followup-to
1906      (let ((newsgroups (message-fetch-field "newsgroups"))
1907            (followup-to (message-fetch-field "followup-to"))
1908            to)
1909        (when (and newsgroups
1910                   (string-match "," newsgroups)
1911                   (not followup-to)
1912                   (not
1913                    (zerop
1914                     (length
1915                      (setq to (completing-read 
1916                                "Followups to: (default all groups) " 
1917                                (mapcar (lambda (g) (list g))
1918                                        (cons "poster" 
1919                                              (message-tokenize-header 
1920                                               newsgroups)))))))))
1921          (goto-char (point-min))
1922          (insert "Followup-To: " to "\n"))
1923        t))
1924    ;; Check "Shoot me".
1925    (message-check 'shoot
1926      (if (re-search-forward
1927           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
1928          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
1929        t))
1930    ;; Check for Approved.
1931    (message-check 'approved
1932      (if (re-search-forward "^Approved:" nil t)
1933          (y-or-n-p "The article contains an Approved header.  Really post? ")
1934        t))
1935    ;; Check the Message-ID header.
1936    (message-check 'message-id
1937      (let* ((case-fold-search t)
1938             (message-id (message-fetch-field "message-id" t)))
1939        (or (not message-id)
1940            (and (string-match "@" message-id)
1941                 (string-match "@[^\\.]*\\." message-id))
1942            (y-or-n-p
1943             (format "The Message-ID looks strange: \"%s\".  Really post? "
1944                     message-id)))))
1945    ;; Check the Subject header.
1946    (message-check 'subject
1947      (let* ((case-fold-search t)
1948             (subject (message-fetch-field "subject")))
1949        (or
1950         (and subject
1951              (not (string-match "\\`[ \t]*\\'" subject)))
1952         (ignore
1953          (message 
1954           "The subject field is empty or missing.  Posting is denied.")))))
1955    ;; Check the Newsgroups & Followup-To headers.
1956    (message-check 'existing-newsgroups
1957      (let* ((case-fold-search t)
1958             (newsgroups (message-fetch-field "newsgroups"))
1959             (followup-to (message-fetch-field "followup-to"))
1960             (groups (message-tokenize-header
1961                      (if followup-to
1962                          (concat newsgroups "," followup-to)
1963                        newsgroups)))
1964             (hashtb (and (boundp 'gnus-active-hashtb)
1965                          gnus-active-hashtb))
1966             errors)
1967        (if (or (not hashtb)
1968                (not (boundp 'gnus-read-active-file))
1969                (not gnus-read-active-file)
1970                (eq gnus-read-active-file 'some))
1971            t
1972          (while groups
1973            (when (and (not (boundp (intern (car groups) hashtb)))
1974                       (not (equal (car groups) "poster")))
1975              (push (car groups) errors))
1976            (pop groups))
1977          (if (not errors)
1978              t
1979            (y-or-n-p
1980             (format
1981              "Really post to %s unknown group%s: %s "
1982              (if (= (length errors) 1) "this" "these")
1983              (if (= (length errors) 1) "" "s")
1984              (mapconcat 'identity errors ", ")))))))
1985    ;; Check the Newsgroups & Followup-To headers for syntax errors.
1986    (message-check 'valid-newsgroups
1987      (let ((case-fold-search t)
1988            (headers '("Newsgroups" "Followup-To"))
1989            header error)
1990        (while (and headers (not error))
1991          (when (setq header (mail-fetch-field (car headers)))
1992            (if (or
1993                 (not 
1994                  (string-match
1995                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
1996                   header))
1997                 (memq 
1998                  nil (mapcar 
1999                       (lambda (g)
2000                         (not (string-match "\\.\\'\\|\\.\\." g)))
2001                       (message-tokenize-header header ","))))
2002                (setq error t)))
2003          (unless error
2004            (pop headers)))
2005        (if (not error)
2006            t
2007          (y-or-n-p
2008           (format "The %s header looks odd: \"%s\".  Really post? "
2009                   (car headers) header)))))
2010    ;; Check the From header.
2011    (message-check 'from
2012      (let* ((case-fold-search t)
2013             (from (message-fetch-field "from"))
2014             (ad (nth 1 (mail-extract-address-components from))))
2015        (cond
2016         ((not from)
2017          (message "There is no From line.  Posting is denied.")
2018          nil)
2019         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2020              (string-match "\\.\\." ad) ;larsi@ifi..uio
2021              (string-match "@\\." ad)   ;larsi@.ifi.uio
2022              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2023              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2024              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2025          (message
2026           "Denied posting -- the From looks strange: \"%s\"." from)
2027          nil)
2028         (t t))))))
2029
2030 (defun message-check-news-body-syntax ()
2031   (and
2032    ;; Check for long lines.
2033    (message-check 'long-lines
2034      (goto-char (point-min))
2035      (re-search-forward
2036       (concat "^" (regexp-quote mail-header-separator) "$"))
2037      (while (and
2038              (progn
2039                (end-of-line)
2040                (< (current-column) 80))
2041              (zerop (forward-line 1))))
2042      (or (bolp)
2043          (eobp)
2044          (y-or-n-p
2045           "You have lines longer than 79 characters.  Really post? ")))
2046    ;; Check whether the article is empty.
2047    (message-check 'empty
2048      (goto-char (point-min))
2049      (re-search-forward
2050       (concat "^" (regexp-quote mail-header-separator) "$"))
2051      (forward-line 1)
2052      (let ((b (point)))
2053        (goto-char (point-max))
2054        (re-search-backward message-signature-separator nil t)
2055        (beginning-of-line)
2056        (or (re-search-backward "[^ \n\t]" b t)
2057            (y-or-n-p "Empty article.  Really post? "))))
2058    ;; Check for control characters.
2059    (message-check 'control-chars
2060      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2061          (y-or-n-p 
2062           "The article contains control characters.  Really post? ")
2063        t))
2064    ;; Check excessive size.
2065    (message-check 'size
2066      (if (> (buffer-size) 60000)
2067          (y-or-n-p
2068           (format "The article is %d octets long.  Really post? "
2069                   (buffer-size)))
2070        t))
2071    ;; Check whether any new text has been added.
2072    (message-check 'new-text
2073      (or
2074       (not message-checksum)
2075       (not (and (eq (message-checksum) (car message-checksum))
2076                 (eq (buffer-size) (cdr message-checksum))))
2077       (y-or-n-p
2078        "It looks like no new text has been added.  Really post? ")))
2079    ;; Check the length of the signature.
2080    (message-check 'signature
2081      (goto-char (point-max))
2082      (if (or (not (re-search-backward message-signature-separator nil t))
2083              (search-forward message-forward-end-separator nil t))
2084          t
2085        (if (> (count-lines (point) (point-max)) 5)
2086            (y-or-n-p
2087             (format
2088              "Your .sig is %d lines; it should be max 4.  Really post? "
2089              (1- (count-lines (point) (point-max)))))
2090          t)))))
2091
2092 (defun message-checksum ()
2093   "Return a \"checksum\" for the current buffer."
2094   (let ((sum 0))
2095     (save-excursion
2096       (goto-char (point-min))
2097       (re-search-forward
2098        (concat "^" (regexp-quote mail-header-separator) "$"))
2099       (while (not (eobp))
2100         (when (not (looking-at "[ \t\n]"))
2101           (setq sum (logxor (ash sum 1) (following-char))))
2102         (forward-char 1)))
2103     sum))
2104
2105 (defun message-do-fcc ()
2106   "Process Fcc headers in the current buffer."
2107   (let ((case-fold-search t)
2108         (buf (current-buffer))
2109         list file)
2110     (save-excursion
2111       (set-buffer (get-buffer-create " *message temp*"))
2112       (buffer-disable-undo (current-buffer))
2113       (erase-buffer)
2114       (insert-buffer-substring buf)
2115       (save-restriction
2116         (message-narrow-to-headers)
2117         (while (setq file (message-fetch-field "fcc"))
2118           (push file list)
2119           (message-remove-header "fcc" nil t)))
2120       (goto-char (point-min))
2121       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2122       (replace-match "" t t)
2123       ;; Process FCC operations.
2124       (while list
2125         (setq file (pop list))
2126         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2127             ;; Pipe the article to the program in question.
2128             (call-process-region (point-min) (point-max) shell-file-name
2129                                  nil nil nil shell-command-switch
2130                                  (match-string 1 file))
2131           ;; Save the article.
2132           (setq file (expand-file-name file))
2133           (unless (file-exists-p (file-name-directory file))
2134             (make-directory (file-name-directory file) t))
2135           (if (and message-fcc-handler-function
2136                    (not (eq message-fcc-handler-function 'rmail-output)))
2137               (funcall message-fcc-handler-function file)
2138             (if (and (file-readable-p file) (mail-file-babyl-p file))
2139                 (rmail-output file 1 nil t)
2140               (let ((mail-use-rfc822 t))
2141                 (rmail-output file 1 t t))))))
2142       
2143       (kill-buffer (current-buffer)))))
2144
2145 (defun message-output (filename)
2146   "Append this article to Unix/babyl mail file.."
2147   (if (and (file-readable-p filename)
2148            (mail-file-babyl-p filename))
2149       (gnus-output-to-rmail filename t)
2150     (gnus-output-to-mail filename t)))
2151
2152 (defun message-cleanup-headers ()
2153   "Do various automatic cleanups of the headers."
2154   ;; Remove empty lines in the header.
2155   (save-restriction
2156     (message-narrow-to-headers)
2157     (while (re-search-forward "^[ \t]*\n" nil t)
2158       (replace-match "" t t)))
2159
2160   ;; Correct Newsgroups and Followup-To headers: change sequence of
2161   ;; spaces to comma and eliminate spaces around commas.  Eliminate
2162   ;; embedded line breaks.
2163   (goto-char (point-min))
2164   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2165     (save-restriction
2166       (narrow-to-region
2167        (point)
2168        (if (re-search-forward "^[^ \t]" nil t)
2169            (match-beginning 0)
2170          (forward-line 1)
2171          (point)))
2172       (goto-char (point-min))
2173       (while (re-search-forward "\n[ \t]+" nil t)
2174         (replace-match " " t t))        ;No line breaks (too confusing)
2175       (goto-char (point-min))
2176       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2177         (replace-match "," t t))
2178       (goto-char (point-min))
2179       ;; Remove trailing commas.
2180       (when (re-search-forward ",+$" nil t)
2181         (replace-match "" t t)))))
2182
2183 (defun message-make-date ()
2184   "Make a valid data header."
2185   (let ((now (current-time)))
2186     (timezone-make-date-arpa-standard 
2187      (current-time-string now) (current-time-zone now))))
2188
2189 (defun message-make-message-id ()
2190   "Make a unique Message-ID."
2191   (concat "<" (message-unique-id) 
2192           (let ((psubject (save-excursion (message-fetch-field "subject"))))
2193             (if (and message-reply-headers
2194                      (mail-header-references message-reply-headers)
2195                      (mail-header-subject message-reply-headers)
2196                      psubject
2197                      (mail-header-subject message-reply-headers)
2198                      (not (string= 
2199                            (message-strip-subject-re
2200                             (mail-header-subject message-reply-headers))
2201                            (message-strip-subject-re psubject))))
2202                 "_-_" ""))
2203           "@" (message-make-fqdn) ">"))
2204
2205 (defvar message-unique-id-char nil)
2206
2207 ;; If you ever change this function, make sure the new version
2208 ;; cannot generate IDs that the old version could.
2209 ;; You might for example insert a "." somewhere (not next to another dot
2210 ;; or string boundary), or modify the "fsf" string.
2211 (defun message-unique-id ()
2212   ;; Don't use microseconds from (current-time), they may be unsupported.
2213   ;; Instead we use this randomly inited counter.
2214   (setq message-unique-id-char
2215         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2216            ;; (current-time) returns 16-bit ints,
2217            ;; and 2^16*25 just fits into 4 digits i base 36.
2218            (* 25 25)))
2219   (let ((tm (current-time)))
2220     (concat
2221      (if (memq system-type '(ms-dos emx vax-vms))
2222          (let ((user (downcase (user-login-name))))
2223            (while (string-match "[^a-z0-9_]" user)
2224              (aset user (match-beginning 0) ?_))
2225            user)
2226        (message-number-base36 (user-uid) -1))
2227      (message-number-base36 (+ (car   tm) 
2228                                (lsh (% message-unique-id-char 25) 16)) 4)
2229      (message-number-base36 (+ (nth 1 tm)
2230                                (lsh (/ message-unique-id-char 25) 16)) 4)
2231      ;; Append the newsreader name, because while the generated
2232      ;; ID is unique to this newsreader, other newsreaders might
2233      ;; otherwise generate the same ID via another algorithm.
2234      ".fsf")))
2235
2236 (defun message-number-base36 (num len)
2237   (if (if (< len 0) (<= num 0) (= len 0))
2238       ""
2239     (concat (message-number-base36 (/ num 36) (1- len))
2240             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2241                                   (% num 36))))))
2242
2243 (defun message-make-organization ()
2244   "Make an Organization header."
2245   (let* ((organization 
2246           (or (getenv "ORGANIZATION")
2247               (when message-user-organization
2248                 (if (message-functionp message-user-organization)
2249                     (funcall message-user-organization)
2250                   message-user-organization)))))
2251     (save-excursion
2252       (message-set-work-buffer)
2253       (cond ((stringp organization)
2254              (insert organization))
2255             ((and (eq t organization)
2256                   message-user-organization-file
2257                   (file-exists-p message-user-organization-file))
2258              (insert-file-contents message-user-organization-file)))
2259       (goto-char (point-min))
2260       (while (re-search-forward "[\t\n]+" nil t)
2261         (replace-match "" t t))
2262       (unless (zerop (buffer-size))
2263         (buffer-string)))))
2264
2265 (defun message-make-lines ()
2266   "Count the number of lines and return numeric string."
2267   (save-excursion
2268     (save-restriction
2269       (widen)
2270       (goto-char (point-min))
2271       (re-search-forward 
2272        (concat "^" (regexp-quote mail-header-separator) "$"))
2273       (forward-line 1)
2274       (int-to-string (count-lines (point) (point-max))))))
2275
2276 (defun message-make-in-reply-to ()
2277   "Return the In-Reply-To header for this message."
2278   (when message-reply-headers
2279     (let ((from (mail-header-from message-reply-headers))
2280           (date (mail-header-date message-reply-headers)))
2281       (when from
2282         (let ((stop-pos 
2283                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2284           (concat (if stop-pos (substring from 0 stop-pos) from)
2285                   "'s message of " 
2286                   (if (or (not date) (string= date ""))
2287                       "(unknown date)" date)))))))
2288
2289 (defun message-make-distribution ()
2290   "Make a Distribution header."
2291   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2292     (cond ((message-functionp message-distribution-function)
2293            (funcall message-distribution-function))
2294           (t orig-distribution))))
2295
2296 (defun message-make-expires ()
2297   "Return an Expires header based on `message-expires'."
2298   (let ((current (current-time))
2299         (future (* 1.0 message-expires 60 60 24)))
2300     ;; Add the future to current.
2301     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2302     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2303     ;; Return the date in the future in UT.
2304     (timezone-make-date-arpa-standard 
2305      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2306
2307 (defun message-make-path ()
2308   "Return uucp path."
2309   (let ((login-name (user-login-name)))
2310     (cond ((null message-user-path)
2311            (concat (system-name) "!" login-name))
2312           ((stringp message-user-path)
2313            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2314            (concat message-user-path "!" login-name))
2315           (t login-name))))
2316
2317 (defun message-make-from ()
2318   "Make a From header."
2319   (let* ((login (message-make-address))
2320          (fullname 
2321           (or (and (boundp 'user-full-name)
2322                    user-full-name)
2323               (user-full-name))))
2324     (when (string= fullname "&")
2325       (setq fullname (user-login-name)))
2326     (save-excursion
2327       (message-set-work-buffer)
2328       (cond 
2329        ((or (null message-from-style)
2330             (equal fullname ""))
2331         (insert login))
2332        ((or (eq message-from-style 'angles)
2333             (and (not (eq message-from-style 'parens))
2334                  ;; Use angles if no quoting is needed, or if parens would
2335                  ;; need quoting too.
2336                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2337                      (let ((tmp (concat fullname nil)))
2338                        (while (string-match "([^()]*)" tmp)
2339                          (aset tmp (match-beginning 0) ?-)
2340                          (aset tmp (1- (match-end 0)) ?-))
2341                        (string-match "[\\()]" tmp)))))
2342         (insert fullname)
2343         (goto-char (point-min))
2344         ;; Look for a character that cannot appear unquoted
2345         ;; according to RFC 822.
2346         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2347           ;; Quote fullname, escaping specials.
2348           (goto-char (point-min))
2349           (insert "\"")
2350           (while (re-search-forward "[\"\\]" nil 1)
2351             (replace-match "\\\\\\&" t))
2352           (insert "\""))
2353         (insert " <" login ">"))
2354        (t                               ; 'parens or default
2355         (insert login " (")
2356         (let ((fullname-start (point)))
2357           (insert fullname)
2358           (goto-char fullname-start)
2359           ;; RFC 822 says \ and nonmatching parentheses
2360           ;; must be escaped in comments.
2361           ;; Escape every instance of ()\ ...
2362           (while (re-search-forward "[()\\]" nil 1)
2363             (replace-match "\\\\\\&" t))
2364           ;; ... then undo escaping of matching parentheses,
2365           ;; including matching nested parentheses.
2366           (goto-char fullname-start)
2367           (while (re-search-forward 
2368                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2369                   nil 1)
2370             (replace-match "\\1(\\3)" t)
2371             (goto-char fullname-start)))
2372         (insert ")")))
2373       (buffer-string))))
2374
2375 (defun message-make-sender ()
2376   "Return the \"real\" user address.
2377 This function tries to ignore all user modifications, and 
2378 give as trustworthy answer as possible."
2379   (concat (user-login-name) "@" (system-name)))
2380
2381 (defun message-make-address ()
2382   "Make the address of the user."
2383   (or (message-user-mail-address)
2384       (concat (user-login-name) "@" (message-make-domain))))
2385
2386 (defun message-user-mail-address ()
2387   "Return the pertinent part of `user-mail-address'."
2388   (when user-mail-address
2389     (if (string-match " " user-mail-address)
2390         (nth 1 (mail-extract-address-components user-mail-address))
2391       user-mail-address)))
2392
2393 (defun message-make-fqdn ()
2394   "Return user's fully qualified domain name."
2395   (let ((system-name (system-name))
2396         (user-mail (message-user-mail-address)))
2397     (cond 
2398      ((string-match "[^.]\\.[^.]" system-name)
2399       ;; `system-name' returned the right result.
2400       system-name)
2401      ;; Try `mail-host-address'.
2402      ((and (boundp 'mail-host-address)
2403            (stringp mail-host-address)
2404            (string-match "\\." mail-host-address))
2405       mail-host-address)
2406      ;; We try `user-mail-address' as a backup.
2407      ((and (string-match "\\." user-mail)
2408            (string-match "@\\(.*\\)\\'" user-mail))
2409       (match-string 1 user-mail))
2410      ;; Default to this bogus thing.
2411      (t
2412       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2413
2414 (defun message-make-host-name ()
2415   "Return the name of the host."
2416   (let ((fqdn (message-make-fqdn)))
2417     (string-match "^[^.]+\\." fqdn)
2418     (substring fqdn 0 (1- (match-end 0)))))
2419
2420 (defun message-make-domain ()
2421   "Return the domain name."
2422   (or mail-host-address
2423       (message-make-fqdn)))
2424
2425 (defun message-generate-headers (headers)
2426   "Prepare article HEADERS.
2427 Headers already prepared in the buffer are not modified."
2428   (save-restriction
2429     (message-narrow-to-headers)
2430     (let* ((Date (message-make-date))
2431            (Message-ID (message-make-message-id))
2432            (Organization (message-make-organization))
2433            (From (message-make-from))
2434            (Path (message-make-path))
2435            (Subject nil)
2436            (Newsgroups nil)
2437            (In-Reply-To (message-make-in-reply-to))
2438            (To nil)
2439            (Distribution (message-make-distribution))
2440            (Lines (message-make-lines))
2441            (X-Newsreader message-newsreader)
2442            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2443                           message-mailer))
2444            (Expires (message-make-expires))
2445            (case-fold-search t)
2446            header value elem)
2447       ;; First we remove any old generated headers.
2448       (let ((headers message-deletable-headers))
2449         (while headers
2450           (goto-char (point-min))
2451           (and (re-search-forward 
2452                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2453                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2454                (message-delete-line))
2455           (pop headers)))
2456       ;; Go through all the required headers and see if they are in the
2457       ;; articles already.  If they are not, or are empty, they are
2458       ;; inserted automatically - except for Subject, Newsgroups and
2459       ;; Distribution. 
2460       (while headers
2461         (goto-char (point-min))
2462         (setq elem (pop headers))
2463         (if (consp elem)
2464             (if (eq (car elem) 'optional)
2465                 (setq header (cdr elem))
2466               (setq header (car elem)))
2467           (setq header elem))
2468         (when (or (not (re-search-forward 
2469                         (concat "^" (downcase (symbol-name header)) ":") 
2470                         nil t))
2471                   (progn
2472                     ;; The header was found.  We insert a space after the
2473                     ;; colon, if there is none.
2474                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2475                     ;; Find out whether the header is empty...
2476                     (looking-at "[ \t]*$")))
2477           ;; So we find out what value we should insert.
2478           (setq value
2479                 (cond 
2480                  ((and (consp elem) (eq (car elem) 'optional))
2481                   ;; This is an optional header.  If the cdr of this
2482                   ;; is something that is nil, then we do not insert
2483                   ;; this header.
2484                   (setq header (cdr elem))
2485                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2486                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2487                  ((consp elem)
2488                   ;; The element is a cons.  Either the cdr is a
2489                   ;; string to be inserted verbatim, or it is a
2490                   ;; function, and we insert the value returned from
2491                   ;; this function.
2492                   (or (and (stringp (cdr elem)) (cdr elem))
2493                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2494                  ((and (boundp header) (symbol-value header))
2495                   ;; The element is a symbol.  We insert the value
2496                   ;; of this symbol, if any.
2497                   (symbol-value header))
2498                  (t
2499                   ;; We couldn't generate a value for this header,
2500                   ;; so we just ask the user.
2501                   (read-from-minibuffer
2502                    (format "Empty header for %s; enter value: " header)))))
2503           ;; Finally insert the header.
2504           (when (and value 
2505                      (not (equal value "")))
2506             (save-excursion
2507               (if (bolp)
2508                   (progn
2509                     ;; This header didn't exist, so we insert it.
2510                     (goto-char (point-max))
2511                     (insert (symbol-name header) ": " value "\n")
2512                     (forward-line -1))
2513                 ;; The value of this header was empty, so we clear
2514                 ;; totally and insert the new value.
2515                 (delete-region (point) (gnus-point-at-eol))
2516                 (insert value))
2517               ;; Add the deletable property to the headers that require it.
2518               (and (memq header message-deletable-headers)
2519                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2520                    (add-text-properties 
2521                     (point) (match-end 0)
2522                     '(message-deletable t face italic) (current-buffer)))))))
2523       ;; Insert new Sender if the From is strange. 
2524       (let ((from (message-fetch-field "from"))
2525             (sender (message-fetch-field "sender"))
2526             (secure-sender (message-make-sender)))
2527         (when (and from 
2528                    (not (message-check-element 'sender))
2529                    (not (string=
2530                          (downcase
2531                           (cadr (mail-extract-address-components from)))
2532                          (downcase secure-sender)))
2533                    (or (null sender)
2534                        (not 
2535                         (string=
2536                          (downcase
2537                           (cadr (mail-extract-address-components sender)))
2538                          (downcase secure-sender)))))
2539           (goto-char (point-min))    
2540           ;; Rename any old Sender headers to Original-Sender.
2541           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2542             (beginning-of-line)
2543             (insert "Original-")
2544             (beginning-of-line))
2545           (insert "Sender: " secure-sender "\n"))))))
2546
2547 (defun message-insert-courtesy-copy ()
2548   "Insert a courtesy message in mail copies of combined messages."
2549   (let (newsgroups)
2550     (save-excursion
2551       (save-restriction
2552         (message-narrow-to-headers)
2553         (when (setq newsgroups (message-fetch-field "newsgroups"))
2554           (goto-char (point-max))
2555           (insert "Posted-To: " newsgroups "\n")))
2556       (forward-line 1)
2557       (when message-courtesy-message
2558         (cond
2559          ((string-match "%s" message-courtesy-message)
2560           (insert (format message-courtesy-message newsgroups)))
2561          (t
2562           (insert message-courtesy-message)))))))
2563     
2564 ;;;
2565 ;;; Setting up a message buffer
2566 ;;;
2567
2568 (defun message-fill-address (header value)
2569   (save-restriction
2570     (narrow-to-region (point) (point))
2571     (insert (capitalize (symbol-name header))
2572             ": "
2573             (if (consp value) (car value) value)
2574             "\n")
2575     (narrow-to-region (point-min) (1- (point-max)))
2576     (let (quoted last)
2577       (goto-char (point-min))
2578       (while (not (eobp))
2579         (skip-chars-forward "^,\"" (point-max))
2580         (if (or (= (following-char) ?,)
2581                 (eobp))
2582             (when (not quoted)
2583               (if (and (> (current-column) 78)
2584                        last)
2585                   (progn
2586                     (save-excursion
2587                       (goto-char last)
2588                       (insert "\n\t"))
2589                     (setq last (1+ (point))))
2590                 (setq last (1+ (point)))))
2591           (setq quoted (not quoted)))
2592         (unless (eobp)
2593           (forward-char 1))))
2594     (goto-char (point-max))
2595     (widen)
2596     (forward-line 1)))
2597
2598 (defun message-fill-header (header value)
2599   (let ((begin (point))
2600         (fill-column 78)
2601         (fill-prefix "\t"))
2602     (insert (capitalize (symbol-name header))
2603             ": "
2604             (if (consp value) (car value) value)
2605             "\n")
2606     (save-restriction
2607       (narrow-to-region begin (point))
2608       (fill-region-as-paragraph begin (point))
2609       ;; Tapdance around looong Message-IDs.
2610       (forward-line -1)
2611       (when (looking-at "[ \t]*$")
2612         (message-delete-line))
2613       (goto-char begin)
2614       (re-search-forward ":" nil t)
2615       (when (looking-at "\n[ \t]+")
2616         (replace-match " " t t))
2617       (goto-char (point-max)))))
2618
2619 (defun message-position-point ()
2620   "Move point to where the user probably wants to find it."
2621   (message-narrow-to-headers)
2622   (cond 
2623    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2624     (search-backward ":" )
2625     (widen)
2626     (forward-char 1)
2627     (if (= (following-char) ? )
2628         (forward-char 1)
2629       (insert " ")))
2630    (t
2631     (goto-char (point-max))
2632     (widen)
2633     (forward-line 1)
2634     (unless (looking-at "$")
2635       (forward-line 2)))
2636    (sit-for 0)))
2637
2638 (defun message-buffer-name (type &optional to group)
2639   "Return a new (unique) buffer name based on TYPE and TO."
2640   (cond
2641    ;; Check whether `message-generate-new-buffers' is a function, 
2642    ;; and if so, call it.
2643    ((message-functionp message-generate-new-buffers)
2644     (funcall message-generate-new-buffers type to group))
2645    ;; Generate a new buffer name The Message Way.
2646    (message-generate-new-buffers
2647     (generate-new-buffer-name
2648      (concat "*" type
2649              (if to
2650                  (concat " to "
2651                          (or (car (mail-extract-address-components to))
2652                              to) "")
2653                "")
2654              (if (and group (not (string= group ""))) (concat " on " group) "")
2655              "*")))
2656    ;; Use standard name.
2657    (t
2658     (format "*%s message*" type))))
2659
2660 (defun message-pop-to-buffer (name)
2661   "Pop to buffer NAME, and warn if it already exists and is modified."
2662   (let ((buffer (get-buffer name)))
2663     (if (and buffer
2664              (buffer-name buffer))
2665         (progn
2666           (set-buffer (pop-to-buffer buffer))
2667           (when (and (buffer-modified-p)
2668                      (not (y-or-n-p
2669                            "Message already being composed; erase? ")))
2670             (error "Message being composed")))
2671       (set-buffer (pop-to-buffer name))))
2672   (erase-buffer)
2673   (message-mode))
2674
2675 (defun message-do-send-housekeeping ()
2676   "Kill old message buffers."
2677   ;; We might have sent this buffer already.  Delete it from the
2678   ;; list of buffers.
2679   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2680   (while (and message-max-buffers
2681               message-buffer-list
2682               (>= (length message-buffer-list) message-max-buffers))
2683     ;; Kill the oldest buffer -- unless it has been changed.
2684     (let ((buffer (pop message-buffer-list)))
2685       (when (and (buffer-name buffer)
2686                  (not (buffer-modified-p buffer)))
2687         (kill-buffer buffer))))
2688   ;; Rename the buffer.
2689   (if message-send-rename-function
2690       (funcall message-send-rename-function)
2691     (when (string-match "\\`\\*" (buffer-name))
2692       (rename-buffer 
2693        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2694   ;; Push the current buffer onto the list.
2695   (when message-max-buffers
2696     (setq message-buffer-list 
2697           (nconc message-buffer-list (list (current-buffer))))))
2698
2699 (defvar mc-modes-alist)
2700 (defun message-setup (headers &optional replybuffer actions)
2701   (when (and (boundp 'mc-modes-alist)
2702              (not (assq 'message-mode mc-modes-alist)))
2703     (push '(message-mode (encrypt . mc-encrypt-message)
2704                          (sign . mc-sign-message))
2705           mc-modes-alist))
2706   (when actions
2707     (setq message-send-actions actions))
2708   (setq message-reply-buffer replybuffer)
2709   (goto-char (point-min))
2710   ;; Insert all the headers.
2711   (mail-header-format 
2712    (let ((h headers)
2713          (alist message-header-format-alist))
2714      (while h
2715        (unless (assq (caar h) message-header-format-alist)
2716          (push (list (caar h)) alist))
2717        (pop h))
2718      alist)
2719    headers)
2720   (delete-region (point) (progn (forward-line -1) (point)))
2721   (when message-default-headers
2722     (insert message-default-headers))
2723   (put-text-property
2724    (point)
2725    (progn
2726      (insert mail-header-separator "\n")
2727      (1- (point)))
2728    'read-only nil)
2729   (forward-line -1)
2730   (when (message-news-p)
2731     (when message-default-news-headers
2732       (insert message-default-news-headers))
2733     (when message-generate-headers-first
2734       (message-generate-headers
2735        (delq 'Lines
2736              (delq 'Subject
2737                    (copy-sequence message-required-news-headers))))))
2738   (when (message-mail-p)
2739     (when message-default-mail-headers
2740       (insert message-default-mail-headers))
2741     (when message-generate-headers-first
2742       (message-generate-headers
2743        (delq 'Lines
2744              (delq 'Subject
2745                    (copy-sequence message-required-mail-headers))))))
2746   (run-hooks 'message-signature-setup-hook)
2747   (message-insert-signature)
2748   (message-set-auto-save-file-name)
2749   (save-restriction
2750     (message-narrow-to-headers)
2751     (run-hooks 'message-header-setup-hook))
2752   (set-buffer-modified-p nil)
2753   (run-hooks 'message-setup-hook)
2754   (message-position-point)
2755   (undo-boundary))
2756
2757 (defun message-set-auto-save-file-name ()
2758   "Associate the message buffer with a file in the drafts directory."
2759   (when message-autosave-directory
2760     (unless (file-exists-p message-autosave-directory)
2761       (make-directory message-autosave-directory t))
2762     (let ((name (make-temp-name
2763                  (concat (file-name-as-directory message-autosave-directory)
2764                          "msg."))))
2765       (setq buffer-auto-save-file-name
2766             (save-excursion
2767               (prog1
2768                   (progn
2769                     (set-buffer (get-buffer-create " *draft tmp*"))
2770                     (setq buffer-file-name name)
2771                     (make-auto-save-file-name))
2772                 (kill-buffer (current-buffer)))))
2773       (clear-visited-file-modtime))))
2774
2775 \f
2776
2777 ;;;
2778 ;;; Commands for interfacing with message
2779 ;;;
2780
2781 ;;;###autoload
2782 (defun message-mail (&optional to subject
2783                                other-headers continue switch-function
2784                                yank-action send-actions)
2785   "Start editing a mail message to be sent."
2786   (interactive)
2787   (let ((message-this-is-mail t))
2788     (message-pop-to-buffer (message-buffer-name "mail" to))
2789     (message-setup 
2790      (nconc
2791       `((To . ,(or to "")) (Subject . ,(or subject "")))
2792       (when other-headers (list other-headers))))))
2793
2794 ;;;###autoload
2795 (defun message-news (&optional newsgroups subject)
2796   "Start editing a news article to be sent."
2797   (interactive)
2798   (let ((message-this-is-news t))
2799     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2800     (message-setup `((Newsgroups . ,(or newsgroups "")) 
2801                      (Subject . ,(or subject ""))))))
2802
2803 ;;;###autoload
2804 (defun message-reply (&optional to-address wide ignore-reply-to)
2805   "Start editing a reply to the article in the current buffer."
2806   (interactive)
2807   (let ((cur (current-buffer))
2808         from subject date reply-to to cc
2809         references message-id follow-to 
2810         (inhibit-point-motion-hooks t)
2811         mct never-mct gnus-warning)
2812     (save-restriction
2813       (message-narrow-to-head)
2814       ;; Allow customizations to have their say.
2815       (if (not wide)
2816           ;; This is a regular reply.
2817           (if (message-functionp message-reply-to-function)
2818               (setq follow-to (funcall message-reply-to-function)))
2819         ;; This is a followup.
2820         (if (message-functionp message-wide-reply-to-function)
2821             (save-excursion
2822               (setq follow-to
2823                     (funcall message-wide-reply-to-function)))))
2824       ;; Find all relevant headers we need.
2825       (setq from (message-fetch-field "from")
2826             date (message-fetch-field "date") 
2827             subject (or (message-fetch-field "subject") "none")
2828             to (message-fetch-field "to")
2829             cc (message-fetch-field "cc")
2830             mct (message-fetch-field "mail-copies-to")
2831             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2832             references (message-fetch-field "references")
2833             message-id (message-fetch-field "message-id" t))
2834       ;; Remove any (buggy) Re:'s that are present and make a
2835       ;; proper one.
2836       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2837         (setq subject (substring subject (match-end 0))))
2838       (setq subject (concat "Re: " subject))
2839
2840       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2841                  (string-match "<[^>]+>" gnus-warning))
2842         (setq message-id (match-string 0 gnus-warning)))
2843             
2844       ;; Handle special values of Mail-Copies-To.
2845       (when mct
2846         (cond ((equal (downcase mct) "never")
2847                (setq never-mct t)
2848                (setq mct nil))
2849               ((equal (downcase mct) "always")
2850                (setq mct (or reply-to from)))))
2851
2852       (unless follow-to
2853         (if (or (not wide)
2854                 to-address)
2855             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2856           (let (ccalist)
2857             (save-excursion
2858               (message-set-work-buffer)
2859               (unless never-mct
2860                 (insert (or reply-to from "")))
2861               (insert (if (bolp) "" ", ") (or to ""))
2862               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2863               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2864               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2865               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2866                         (erase-buffer)))
2867               (goto-char (point-min))
2868               ;; Perhaps Mail-Copies-To: never removed the only address?
2869               (when (eobp)
2870                 (insert (or reply-to from "")))
2871               (setq ccalist
2872                     (mapcar
2873                      (lambda (addr)
2874                        (cons (mail-strip-quoted-names addr) addr))
2875                      (message-tokenize-header (buffer-string))))
2876               (let ((s ccalist))
2877                 (while s
2878                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2879             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2880             (when ccalist
2881               (let ((ccs (cons 'Cc (mapconcat 
2882                                     (lambda (addr) (cdr addr)) ccalist ", "))))
2883                 (when (string-match "^ +" (cdr ccs))
2884                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
2885                 (push ccs follow-to))))))
2886       (widen))
2887
2888     (message-pop-to-buffer (message-buffer-name
2889                             (if wide "wide reply" "reply") from
2890                             (if wide to-address nil)))
2891
2892     (setq message-reply-headers
2893           (vector 0 subject from date message-id references 0 0 ""))
2894
2895     (message-setup
2896      `((Subject . ,subject)
2897        ,@follow-to 
2898        ,@(if (or references message-id)
2899              `((References . ,(concat (or references "") (and references " ")
2900                                       (or message-id ""))))
2901            nil))
2902      cur)))
2903
2904 ;;;###autoload
2905 (defun message-wide-reply (&optional to-address)
2906   "Make a \"wide\" reply to the message in the current buffer."
2907   (interactive)
2908   (message-reply to-address t))
2909
2910 ;;;###autoload
2911 (defun message-followup (&optional to-newsgroups)
2912   "Follow up to the message in the current buffer.
2913 If TO-NEWSGROUPS, use that as the new Newsgroups line."
2914   (interactive)
2915   (let ((cur (current-buffer))
2916         from subject date reply-to mct
2917         references message-id follow-to 
2918         (inhibit-point-motion-hooks t)
2919         (message-this-is-news t)
2920         followup-to distribution newsgroups gnus-warning posted-to)
2921     (save-restriction
2922       (narrow-to-region
2923        (goto-char (point-min))
2924        (if (search-forward "\n\n" nil t)
2925            (1- (point))
2926          (point-max)))
2927       (when (message-functionp message-followup-to-function)
2928         (setq follow-to
2929               (funcall message-followup-to-function)))
2930       (setq from (message-fetch-field "from")
2931             date (message-fetch-field "date") 
2932             subject (or (message-fetch-field "subject") "none")
2933             references (message-fetch-field "references")
2934             message-id (message-fetch-field "message-id" t)
2935             followup-to (message-fetch-field "followup-to")
2936             newsgroups (message-fetch-field "newsgroups")
2937             posted-to (message-fetch-field "posted-to")
2938             reply-to (message-fetch-field "reply-to")
2939             distribution (message-fetch-field "distribution")
2940             mct (message-fetch-field "mail-copies-to"))
2941       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2942                  (string-match "<[^>]+>" gnus-warning))
2943         (setq message-id (match-string 0 gnus-warning)))
2944       ;; Remove bogus distribution.
2945       (when (and (stringp distribution)
2946                  (let ((case-fold-search t))
2947                    (string-match "world" distribution)))
2948         (setq distribution nil))
2949       ;; Remove any (buggy) Re:'s that are present and make a
2950       ;; proper one.
2951       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2952         (setq subject (substring subject (match-end 0))))
2953       (setq subject (concat "Re: " subject))
2954       (widen))
2955
2956     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2957
2958     (message-setup
2959      `((Subject . ,subject)
2960        ,@(cond 
2961           (to-newsgroups
2962            (list (cons 'Newsgroups to-newsgroups)))
2963           (follow-to follow-to)
2964           ((and followup-to message-use-followup-to)
2965            (list
2966             (cond 
2967              ((equal (downcase followup-to) "poster")
2968               (if (or (eq message-use-followup-to 'use)
2969                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2970 You should normally obey the Followup-To: header.
2971
2972 `Followup-To: poster' sends your response via e-mail instead of news.
2973
2974 A typical situation where `Followup-To: poster' is used is when the poster
2975 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2976                   (cons 'To (or reply-to from ""))
2977                 (cons 'Newsgroups newsgroups)))
2978              (t
2979               (if (or (equal followup-to newsgroups)
2980                       (not (eq message-use-followup-to 'ask))
2981                       (message-y-or-n-p
2982                        (concat "Obey Followup-To: " followup-to "? ") t "\
2983 You should normally obey the Followup-To: header.
2984
2985         `Followup-To: " followup-to "'
2986 directs your response to " (if (string-match "," followup-to)
2987                                "the specified newsgroups"
2988                              "that newsgroup only") ".
2989
2990 If a message is posted to several newsgroups, Followup-To is often
2991 used to direct the following discussion to one newsgroup only,
2992 because discussions that are spread over several newsgroup tend to
2993 be fragmented and very difficult to follow.
2994
2995 Also, some source/announcement newsgroups are not indented for discussion;
2996 responses here are directed to other newsgroups."))
2997                   (cons 'Newsgroups followup-to)
2998                 (cons 'Newsgroups newsgroups))))))
2999           (posted-to
3000            `((Newsgroups . ,posted-to)))
3001           (t
3002            `((Newsgroups . ,newsgroups))))
3003        ,@(and distribution (list (cons 'Distribution distribution)))
3004        ,@(if (or references message-id)
3005              `((References . ,(concat (or references "") (and references " ")
3006                                       (or message-id "")))))
3007        ,@(when (and mct
3008                     (not (equal (downcase mct) "never")))
3009            (list (cons 'Cc (if (equal (downcase mct) "always")
3010                                (or reply-to from "")
3011                              mct)))))
3012
3013      cur)
3014
3015     (setq message-reply-headers
3016           (vector 0 subject from date message-id references 0 0 ""))))
3017
3018
3019 ;;;###autoload
3020 (defun message-cancel-news ()
3021   "Cancel an article you posted."
3022   (interactive)
3023   (unless (message-news-p)
3024     (error "This is not a news article; canceling is impossible"))
3025   (when (yes-or-no-p "Do you really want to cancel this article? ")
3026     (let (from newsgroups message-id distribution buf)
3027       (save-excursion
3028         ;; Get header info. from original article.
3029         (save-restriction
3030           (message-narrow-to-head)
3031           (setq from (message-fetch-field "from")
3032                 newsgroups (message-fetch-field "newsgroups")
3033                 message-id (message-fetch-field "message-id" t)
3034                 distribution (message-fetch-field "distribution")))
3035         ;; Make sure that this article was written by the user.
3036         (unless (string-equal
3037                  (downcase (cadr (mail-extract-address-components from)))
3038                  (downcase (message-make-address)))
3039           (error "This article is not yours"))
3040         ;; Make control message.
3041         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3042         (buffer-disable-undo (current-buffer))
3043         (erase-buffer)
3044         (insert "Newsgroups: " newsgroups "\n"
3045                 "From: " (message-make-from) "\n"
3046                 "Subject: cmsg cancel " message-id "\n"
3047                 "Control: cancel " message-id "\n"
3048                 (if distribution
3049                     (concat "Distribution: " distribution "\n")
3050                   "")
3051                 mail-header-separator "\n"
3052                 message-cancel-message)
3053         (message "Canceling your article...")
3054         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
3055           (funcall message-send-news-function))
3056         (message "Canceling your article...done")
3057         (kill-buffer buf)))))
3058
3059 ;;;###autoload
3060 (defun message-supersede ()
3061   "Start composing a message to supersede the current message.
3062 This is done simply by taking the old article and adding a Supersedes
3063 header line with the old Message-ID."
3064   (interactive)
3065   (let ((cur (current-buffer)))
3066     ;; Check whether the user owns the article that is to be superseded. 
3067     (unless (string-equal
3068              (downcase (cadr (mail-extract-address-components
3069                               (message-fetch-field "from"))))
3070              (downcase (message-make-address)))
3071       (error "This article is not yours"))
3072     ;; Get a normal message buffer.
3073     (message-pop-to-buffer (message-buffer-name "supersede"))
3074     (insert-buffer-substring cur)
3075     (message-narrow-to-head)
3076     ;; Remove unwanted headers.
3077     (when message-ignored-supersedes-headers
3078       (message-remove-header message-ignored-supersedes-headers t))
3079     (goto-char (point-min))
3080     (if (not (re-search-forward "^Message-ID: " nil t))
3081         (error "No Message-ID in this article")
3082       (replace-match "Supersedes: " t t))
3083     (goto-char (point-max))
3084     (insert mail-header-separator)
3085     (widen)
3086     (forward-line 1)))
3087
3088 ;;;###autoload
3089 (defun message-recover ()
3090   "Reread contents of current buffer from its last auto-save file."
3091   (interactive)
3092   (let ((file-name (make-auto-save-file-name)))
3093     (cond ((save-window-excursion
3094              (if (not (eq system-type 'vax-vms))
3095                  (with-output-to-temp-buffer "*Directory*"
3096                    (buffer-disable-undo standard-output)
3097                    (let ((default-directory "/"))
3098                      (call-process
3099                       "ls" nil standard-output nil "-l" file-name))))
3100              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3101            (let ((buffer-read-only nil))
3102              (erase-buffer)
3103              (insert-file-contents file-name nil)))
3104           (t (error "message-recover cancelled")))))
3105
3106 ;;; Forwarding messages.
3107
3108 (defun message-make-forward-subject ()
3109   "Return a Subject header suitable for the message in the current buffer."
3110   (save-excursion
3111     (save-restriction
3112       (current-buffer)
3113       (message-narrow-to-head)
3114       (concat "[" (or (message-fetch-field 
3115                        (if (message-news-p) "newsgroups" "from"))
3116                       "(nowhere)")
3117               "] " (or (message-fetch-field "Subject") "")))))
3118
3119 ;;;###autoload
3120 (defun message-forward (&optional news)
3121   "Forward the current message via mail.  
3122 Optional NEWS will use news to forward instead of mail."
3123   (interactive "P")
3124   (let ((cur (current-buffer))
3125         (subject (message-make-forward-subject))
3126         art-beg)
3127     (if news (message-news nil subject) (message-mail nil subject))
3128     ;; Put point where we want it before inserting the forwarded
3129     ;; message. 
3130     (if message-signature-before-forwarded-message
3131         (goto-char (point-max))
3132       (message-goto-body))
3133     ;; Make sure we're at the start of the line.
3134     (unless (eolp)
3135       (insert "\n"))
3136     ;; Narrow to the area we are to insert.
3137     (narrow-to-region (point) (point))
3138     ;; Insert the separators and the forwarded buffer.
3139     (insert message-forward-start-separator)
3140     (setq art-beg (point))
3141     (insert-buffer-substring cur)
3142     (goto-char (point-max))
3143     (insert message-forward-end-separator)
3144     (set-text-properties (point-min) (point-max) nil)
3145     ;; Remove all unwanted headers.
3146     (goto-char art-beg)
3147     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3148                                   (1- (point))
3149                                 (point)))
3150     (goto-char (point-min))
3151     (message-remove-header message-included-forward-headers t nil t)
3152     (widen)
3153     (message-position-point)))
3154
3155 ;;;###autoload
3156 (defun message-resend (address)
3157   "Resend the current article to ADDRESS."
3158   (interactive "sResend message to: ")
3159   (message "Resending message to %s..." address)
3160   (save-excursion
3161     (let ((cur (current-buffer))
3162           beg)
3163       ;; We first set up a normal mail buffer.
3164       (set-buffer (get-buffer-create " *message resend*"))
3165       (buffer-disable-undo (current-buffer))
3166       (erase-buffer)
3167       (message-setup `((To . ,address)))
3168       ;; Insert our usual headers.
3169       (message-generate-headers '(From Date To))
3170       (message-narrow-to-headers)
3171       ;; Rename them all to "Resent-*".
3172       (while (re-search-forward "^[A-Za-z]" nil t)
3173         (forward-char -1)
3174         (insert "Resent-"))
3175       (widen)
3176       (forward-line)
3177       (delete-region (point) (point-max))
3178       (setq beg (point))
3179       ;; Insert the message to be resent.
3180       (insert-buffer-substring cur)
3181       (goto-char (point-min))
3182       (search-forward "\n\n")
3183       (forward-char -1)
3184       (save-restriction
3185         (narrow-to-region beg (point))
3186         (message-remove-header message-ignored-resent-headers t)
3187         (goto-char (point-max)))
3188       (insert mail-header-separator)
3189       ;; Rename all old ("Also-")Resent headers.
3190       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3191         (beginning-of-line)
3192         (insert "Also-"))
3193       ;; Quote any "From " lines at the beginning.
3194       (goto-char beg)
3195       (when (looking-at "From ")
3196         (replace-match "X-From-Line: "))
3197       ;; Send it.
3198       (message-send-mail)
3199       (kill-buffer (current-buffer)))
3200     (message "Resending message to %s...done" address)))
3201
3202 ;;;###autoload
3203 (defun message-bounce ()
3204   "Re-mail the current message.
3205 This only makes sense if the current message is a bounce message than
3206 contains some mail you have written which has been bounced back to
3207 you."
3208   (interactive)
3209   (let ((cur (current-buffer))
3210         boundary)
3211     (message-pop-to-buffer (message-buffer-name "bounce"))
3212     (insert-buffer-substring cur)
3213     (undo-boundary)
3214     (message-narrow-to-head)
3215     (if (and (message-fetch-field "Mime-Version")
3216              (setq boundary (message-fetch-field "Content-Type")))
3217         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3218             (setq boundary (concat (match-string 1 boundary) " *\n"
3219                                    "Content-Type: message/rfc822"))
3220           (setq boundary nil)))
3221     (widen)
3222     (goto-char (point-min))
3223     (search-forward "\n\n" nil t)
3224     (or (and boundary
3225              (re-search-forward boundary nil t)
3226              (forward-line 2))
3227         (and (re-search-forward message-unsent-separator nil t)
3228              (forward-line 1))
3229         (and (search-forward "\n\n" nil t)
3230              (re-search-forward "^Return-Path:.*\n" nil t)))
3231     ;; We remove everything before the bounced mail.
3232     (delete-region 
3233      (point-min)
3234      (if (re-search-forward "^[^ \n\t]+:" nil t)
3235          (match-beginning 0)
3236        (point)))
3237     (save-restriction
3238       (message-narrow-to-head)
3239       (message-remove-header message-ignored-bounced-headers t)
3240       (goto-char (point-max))
3241       (insert mail-header-separator))
3242     (message-position-point)))
3243
3244 ;;;
3245 ;;; Interactive entry points for new message buffers.
3246 ;;;
3247
3248 ;;;###autoload
3249 (defun message-mail-other-window (&optional to subject)
3250   "Like `message-mail' command, but display mail buffer in another window."
3251   (interactive)
3252   (let ((pop-up-windows t)
3253         (special-display-buffer-names nil)
3254         (special-display-regexps nil)
3255         (same-window-buffer-names nil)
3256         (same-window-regexps nil))
3257     (message-pop-to-buffer (message-buffer-name "mail" to)))
3258   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3259
3260 ;;;###autoload
3261 (defun message-mail-other-frame (&optional to subject)
3262   "Like `message-mail' command, but display mail buffer in another frame."
3263   (interactive)
3264   (let ((pop-up-frames t)
3265         (special-display-buffer-names nil)
3266         (special-display-regexps nil)
3267         (same-window-buffer-names nil)
3268         (same-window-regexps nil))
3269     (message-pop-to-buffer (message-buffer-name "mail" to)))
3270   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3271
3272 ;;;###autoload
3273 (defun message-news-other-window (&optional newsgroups subject)
3274   "Start editing a news article to be sent."
3275   (interactive)
3276   (let ((pop-up-windows t)
3277         (special-display-buffer-names nil)
3278         (special-display-regexps nil)
3279         (same-window-buffer-names nil)
3280         (same-window-regexps nil))
3281     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3282   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3283                    (Subject . ,(or subject "")))))
3284
3285 ;;;###autoload
3286 (defun message-news-other-frame (&optional newsgroups subject)
3287   "Start editing a news article to be sent."
3288   (interactive)
3289   (let ((pop-up-frames t)
3290         (special-display-buffer-names nil)
3291         (special-display-regexps nil)
3292         (same-window-buffer-names nil)
3293         (same-window-regexps nil))
3294     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3295   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3296                    (Subject . ,(or subject "")))))
3297
3298 ;;; underline.el
3299
3300 ;; This code should be moved to underline.el (from which it is stolen). 
3301
3302 ;;;###autoload
3303 (defun bold-region (start end)
3304   "Bold all nonblank characters in the region.
3305 Works by overstriking characters.
3306 Called from program, takes two arguments START and END
3307 which specify the range to operate on."
3308   (interactive "r")
3309   (save-excursion
3310     (let ((end1 (make-marker)))
3311       (move-marker end1 (max start end))
3312       (goto-char (min start end))
3313       (while (< (point) end1)
3314         (or (looking-at "[_\^@- ]")
3315             (insert (following-char) "\b"))
3316         (forward-char 1)))))
3317
3318 ;;;###autoload
3319 (defun unbold-region (start end)
3320   "Remove all boldness (overstruck characters) in the region.
3321 Called from program, takes two arguments START and END
3322 which specify the range to operate on."
3323   (interactive "r")
3324   (save-excursion
3325     (let ((end1 (make-marker)))
3326       (move-marker end1 (max start end))
3327       (goto-char (min start end)) 
3328       (while (re-search-forward "\b" end1 t)
3329         (if (eq (following-char) (char-after (- (point) 2)))
3330             (delete-char -2))))))
3331
3332 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3333
3334 ;; Support for toolbar
3335 (when (string-match "XEmacs\\|Lucid" emacs-version)
3336   (require 'messagexmas))
3337
3338 ;;; Group name completion.
3339
3340 (defvar message-newgroups-header-regexp
3341   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
3342   "Regexp that match headers that lists groups.")
3343
3344 (defun message-tab ()
3345   "Expand group names in Newsgroups and Followup-To headers.
3346 Do a `tab-to-tab-stop' if not in those headers."
3347   (interactive)
3348   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3349         (mail-abbrev-in-expansion-header-p))
3350       (message-expand-group)
3351     (tab-to-tab-stop)))
3352
3353 (defvar gnus-active-hashtb)
3354 (defun message-expand-group ()
3355   (let* ((b (save-excursion 
3356               (save-restriction
3357                 (narrow-to-region 
3358                  (save-excursion
3359                    (beginning-of-line)
3360                    (skip-chars-forward "^:")
3361                    (1+ (point)))
3362                  (point))
3363                 (skip-chars-backward "^, \t\n") (point))))
3364          (completion-ignore-case t)
3365          (string (buffer-substring b (point)))
3366          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3367          (completions (all-completions string hashtb))
3368          (cur (current-buffer))
3369          comp)
3370     (delete-region b (point))
3371     (cond 
3372      ((= (length completions) 1)
3373       (if (string= (car completions) string)
3374           (progn
3375             (insert string)
3376             (message "Only matching group"))
3377         (insert (car completions))))
3378      ((and (setq comp (try-completion string hashtb))
3379            (not (string= comp string)))
3380       (insert comp))
3381      (t
3382       (insert string)
3383       (if (not comp)
3384           (message "No matching groups")
3385         (pop-to-buffer "*Completions*")
3386         (buffer-disable-undo (current-buffer))
3387         (let ((buffer-read-only nil))
3388           (erase-buffer)
3389           (let ((standard-output (current-buffer)))
3390             (display-completion-list (sort completions 'string<)))
3391           (goto-char (point-min))
3392           (pop-to-buffer cur)))))))
3393
3394 ;;; Help stuff.
3395
3396 (defun message-talkative-question (ask question show &rest text)
3397   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
3398 The following arguments may contain lists of values."
3399   (if (and show
3400            (setq text (message-flatten-list text)))
3401       (save-window-excursion
3402         (save-excursion
3403           (with-output-to-temp-buffer " *MESSAGE information message*"
3404             (set-buffer " *MESSAGE information message*")
3405             (mapcar 'princ text)
3406             (goto-char (point-min))))
3407         (funcall ask question))
3408     (funcall ask question)))
3409
3410 (defun message-flatten-list (list)
3411   "Return a new, flat list that contains all elements of LIST.
3412
3413 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3414 => (1 2 3 4 5 6 7)"
3415   (cond ((consp list) 
3416          (apply 'append (mapcar 'message-flatten-list list)))
3417         (list
3418          (list list))))
3419
3420 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3421   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3422 Then clone the local variables and values from the old buffer to the
3423 new one, cloning only the locals having a substring matching the
3424 regexp varstr."
3425   (let ((oldlocals (buffer-local-variables)))
3426     (save-excursion
3427       (set-buffer (generate-new-buffer name))
3428       (mapcar (lambda (dude)
3429                 (when (and (car dude)
3430                            (or (not varstr)
3431                                (string-match varstr (symbol-name (car dude)))))
3432                   (ignore-errors
3433                     (set (make-local-variable (car dude))
3434                          (cdr dude)))))
3435               oldlocals)
3436       (current-buffer))))
3437
3438 (run-hooks 'message-load-hook)
3439
3440 (provide 'message)
3441
3442 ;;; message.el ends here