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