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