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