Quassia Gnus v0.15.
[elisp/gnus.git-] / 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     (while (re-search-forward "^[ \t]*\n" nil t)
2455       (replace-match "" t t)))
2456
2457   ;; Correct Newsgroups and Followup-To headers: change sequence of
2458   ;; spaces to comma and eliminate spaces around commas.  Eliminate
2459   ;; embedded line breaks.
2460   (goto-char (point-min))
2461   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2462     (save-restriction
2463       (narrow-to-region
2464        (point)
2465        (if (re-search-forward "^[^ \t]" nil t)
2466            (match-beginning 0)
2467          (forward-line 1)
2468          (point)))
2469       (goto-char (point-min))
2470       (while (re-search-forward "\n[ \t]+" nil t)
2471         (replace-match " " t t))        ;No line breaks (too confusing)
2472       (goto-char (point-min))
2473       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2474         (replace-match "," t t))
2475       (goto-char (point-min))
2476       ;; Remove trailing commas.
2477       (when (re-search-forward ",+$" nil t)
2478         (replace-match "" t t)))))
2479
2480 (defun message-make-date ()
2481   "Make a valid data header."
2482   (let ((now (current-time)))
2483     (timezone-make-date-arpa-standard
2484      (current-time-string now) (current-time-zone now))))
2485
2486 (defun message-make-message-id ()
2487   "Make a unique Message-ID."
2488   (concat "<" (message-unique-id)
2489           (let ((psubject (save-excursion (message-fetch-field "subject")))
2490                 (psupersedes
2491                  (save-excursion (message-fetch-field "supersedes"))))
2492             (if (or
2493                  (and message-reply-headers
2494                       (mail-header-references message-reply-headers)
2495                       (mail-header-subject message-reply-headers)
2496                       psubject
2497                       (mail-header-subject message-reply-headers)
2498                       (not (string=
2499                             (message-strip-subject-re
2500                              (mail-header-subject message-reply-headers))
2501                             (message-strip-subject-re psubject))))
2502                  (and psupersedes
2503                       (string-match "_-_@" psupersedes)))
2504                 "_-_" ""))
2505           "@" (message-make-fqdn) ">"))
2506
2507 (defvar message-unique-id-char nil)
2508
2509 ;; If you ever change this function, make sure the new version
2510 ;; cannot generate IDs that the old version could.
2511 ;; You might for example insert a "." somewhere (not next to another dot
2512 ;; or string boundary), or modify the "fsf" string.
2513 (defun message-unique-id ()
2514   ;; Don't use microseconds from (current-time), they may be unsupported.
2515   ;; Instead we use this randomly inited counter.
2516   (setq message-unique-id-char
2517         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2518            ;; (current-time) returns 16-bit ints,
2519            ;; and 2^16*25 just fits into 4 digits i base 36.
2520            (* 25 25)))
2521   (let ((tm (current-time)))
2522     (concat
2523      (if (memq system-type '(ms-dos emx vax-vms))
2524          (let ((user (downcase (user-login-name))))
2525            (while (string-match "[^a-z0-9_]" user)
2526              (aset user (match-beginning 0) ?_))
2527            user)
2528        (message-number-base36 (user-uid) -1))
2529      (message-number-base36 (+ (car   tm)
2530                                (lsh (% message-unique-id-char 25) 16)) 4)
2531      (message-number-base36 (+ (nth 1 tm)
2532                                (lsh (/ message-unique-id-char 25) 16)) 4)
2533      ;; Append the newsreader name, because while the generated
2534      ;; ID is unique to this newsreader, other newsreaders might
2535      ;; otherwise generate the same ID via another algorithm.
2536      ".fsf")))
2537
2538 (defun message-number-base36 (num len)
2539   (if (if (< len 0)
2540           (<= num 0)
2541         (= len 0))
2542       ""
2543     (concat (message-number-base36 (/ num 36) (1- len))
2544             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2545                                   (% num 36))))))
2546
2547 (defun message-make-organization ()
2548   "Make an Organization header."
2549   (let* ((organization
2550           (when message-user-organization
2551                 (if (message-functionp message-user-organization)
2552                     (funcall message-user-organization)
2553                   message-user-organization))))
2554     (save-excursion
2555       (message-set-work-buffer)
2556       (cond ((stringp organization)
2557              (insert organization))
2558             ((and (eq t organization)
2559                   message-user-organization-file
2560                   (file-exists-p message-user-organization-file))
2561              (insert-file-contents message-user-organization-file)))
2562       (goto-char (point-min))
2563       (while (re-search-forward "[\t\n]+" nil t)
2564         (replace-match "" t t))
2565       (unless (zerop (buffer-size))
2566         (buffer-string)))))
2567
2568 (defun message-make-lines ()
2569   "Count the number of lines and return numeric string."
2570   (save-excursion
2571     (save-restriction
2572       (widen)
2573       (goto-char (point-min))
2574       (re-search-forward
2575        (concat "^" (regexp-quote mail-header-separator) "$"))
2576       (forward-line 1)
2577       (int-to-string (count-lines (point) (point-max))))))
2578
2579 (defun message-make-in-reply-to ()
2580   "Return the In-Reply-To header for this message."
2581   (when message-reply-headers
2582     (let ((from (mail-header-from message-reply-headers))
2583           (date (mail-header-date message-reply-headers)))
2584       (when from
2585         (let ((stop-pos
2586                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2587           (concat (if stop-pos (substring from 0 stop-pos) from)
2588                   "'s message of \""
2589                   (if (or (not date) (string= date ""))
2590                       "(unknown date)" date)
2591                   "\""))))))
2592
2593 (defun message-make-distribution ()
2594   "Make a Distribution header."
2595   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2596     (cond ((message-functionp message-distribution-function)
2597            (funcall message-distribution-function))
2598           (t orig-distribution))))
2599
2600 (defun message-make-expires ()
2601   "Return an Expires header based on `message-expires'."
2602   (let ((current (current-time))
2603         (future (* 1.0 message-expires 60 60 24)))
2604     ;; Add the future to current.
2605     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2606     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2607     ;; Return the date in the future in UT.
2608     (timezone-make-date-arpa-standard
2609      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2610
2611 (defun message-make-path ()
2612   "Return uucp path."
2613   (let ((login-name (user-login-name)))
2614     (cond ((null message-user-path)
2615            (concat (system-name) "!" login-name))
2616           ((stringp message-user-path)
2617            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2618            (concat message-user-path "!" login-name))
2619           (t login-name))))
2620
2621 (defun message-make-from ()
2622   "Make a From header."
2623   (let* ((style message-from-style)
2624          (login (message-make-address))
2625          (fullname
2626           (or (and (boundp 'user-full-name)
2627                    user-full-name)
2628               (user-full-name))))
2629     (when (string= fullname "&")
2630       (setq fullname (user-login-name)))
2631     (save-excursion
2632       (message-set-work-buffer)
2633       (cond
2634        ((or (null style)
2635             (equal fullname ""))
2636         (insert login))
2637        ((or (eq style 'angles)
2638             (and (not (eq style 'parens))
2639                  ;; Use angles if no quoting is needed, or if parens would
2640                  ;; need quoting too.
2641                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2642                      (let ((tmp (concat fullname nil)))
2643                        (while (string-match "([^()]*)" tmp)
2644                          (aset tmp (match-beginning 0) ?-)
2645                          (aset tmp (1- (match-end 0)) ?-))
2646                        (string-match "[\\()]" tmp)))))
2647         (insert fullname)
2648         (goto-char (point-min))
2649         ;; Look for a character that cannot appear unquoted
2650         ;; according to RFC 822.
2651         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2652           ;; Quote fullname, escaping specials.
2653           (goto-char (point-min))
2654           (insert "\"")
2655           (while (re-search-forward "[\"\\]" nil 1)
2656             (replace-match "\\\\\\&" t))
2657           (insert "\""))
2658         (insert " <" login ">"))
2659        (t                               ; 'parens or default
2660         (insert login " (")
2661         (let ((fullname-start (point)))
2662           (insert fullname)
2663           (goto-char fullname-start)
2664           ;; RFC 822 says \ and nonmatching parentheses
2665           ;; must be escaped in comments.
2666           ;; Escape every instance of ()\ ...
2667           (while (re-search-forward "[()\\]" nil 1)
2668             (replace-match "\\\\\\&" t))
2669           ;; ... then undo escaping of matching parentheses,
2670           ;; including matching nested parentheses.
2671           (goto-char fullname-start)
2672           (while (re-search-forward
2673                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2674                   nil 1)
2675             (replace-match "\\1(\\3)" t)
2676             (goto-char fullname-start)))
2677         (insert ")")))
2678       (buffer-string))))
2679
2680 (defun message-make-sender ()
2681   "Return the \"real\" user address.
2682 This function tries to ignore all user modifications, and
2683 give as trustworthy answer as possible."
2684   (concat (user-login-name) "@" (system-name)))
2685
2686 (defun message-make-address ()
2687   "Make the address of the user."
2688   (or (message-user-mail-address)
2689       (concat (user-login-name) "@" (message-make-domain))))
2690
2691 (defun message-user-mail-address ()
2692   "Return the pertinent part of `user-mail-address'."
2693   (when user-mail-address
2694     (if (string-match " " user-mail-address)
2695         (nth 1 (mail-extract-address-components user-mail-address))
2696       user-mail-address)))
2697
2698 (defun message-make-fqdn ()
2699   "Return user's fully qualified domain name."
2700   (let ((system-name (system-name))
2701         (user-mail (message-user-mail-address)))
2702     (cond
2703      ((string-match "[^.]\\.[^.]" system-name)
2704       ;; `system-name' returned the right result.
2705       system-name)
2706      ;; Try `mail-host-address'.
2707      ((and (boundp 'mail-host-address)
2708            (stringp mail-host-address)
2709            (string-match "\\." mail-host-address))
2710       mail-host-address)
2711      ;; We try `user-mail-address' as a backup.
2712      ((and user-mail
2713            (string-match "\\." user-mail)
2714            (string-match "@\\(.*\\)\\'" user-mail))
2715       (match-string 1 user-mail))
2716      ;; Default to this bogus thing.
2717      (t
2718       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2719
2720 (defun message-make-host-name ()
2721   "Return the name of the host."
2722   (let ((fqdn (message-make-fqdn)))
2723     (string-match "^[^.]+\\." fqdn)
2724     (substring fqdn 0 (1- (match-end 0)))))
2725
2726 (defun message-make-domain ()
2727   "Return the domain name."
2728   (or mail-host-address
2729       (message-make-fqdn)))
2730
2731 (defun message-generate-headers (headers)
2732   "Prepare article HEADERS.
2733 Headers already prepared in the buffer are not modified."
2734   (save-restriction
2735     (message-narrow-to-headers)
2736     (let* ((Date (message-make-date))
2737            (Message-ID (message-make-message-id))
2738            (Organization (message-make-organization))
2739            (From (message-make-from))
2740            (Path (message-make-path))
2741            (Subject nil)
2742            (Newsgroups nil)
2743            (In-Reply-To (message-make-in-reply-to))
2744            (To nil)
2745            (Distribution (message-make-distribution))
2746            (Lines (message-make-lines))
2747            (X-Newsreader message-newsreader)
2748            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2749                           message-mailer))
2750            (Expires (message-make-expires))
2751            (case-fold-search t)
2752            header value elem)
2753       ;; First we remove any old generated headers.
2754       (let ((headers message-deletable-headers))
2755         (unless (buffer-modified-p)
2756           (setq headers (delq 'Message-ID (copy-sequence headers))))
2757         (while headers
2758           (goto-char (point-min))
2759           (and (re-search-forward
2760                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2761                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2762                (message-delete-line))
2763           (pop headers)))
2764       ;; Go through all the required headers and see if they are in the
2765       ;; articles already.  If they are not, or are empty, they are
2766       ;; inserted automatically - except for Subject, Newsgroups and
2767       ;; Distribution.
2768       (while headers
2769         (goto-char (point-min))
2770         (setq elem (pop headers))
2771         (if (consp elem)
2772             (if (eq (car elem) 'optional)
2773                 (setq header (cdr elem))
2774               (setq header (car elem)))
2775           (setq header elem))
2776         (when (or (not (re-search-forward
2777                         (concat "^" (downcase (symbol-name header)) ":")
2778                         nil t))
2779                   (progn
2780                     ;; The header was found.  We insert a space after the
2781                     ;; colon, if there is none.
2782                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2783                     ;; Find out whether the header is empty...
2784                     (looking-at "[ \t]*$")))
2785           ;; So we find out what value we should insert.
2786           (setq value
2787                 (cond
2788                  ((and (consp elem) (eq (car elem) 'optional))
2789                   ;; This is an optional header.  If the cdr of this
2790                   ;; is something that is nil, then we do not insert
2791                   ;; this header.
2792                   (setq header (cdr elem))
2793                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2794                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2795                  ((consp elem)
2796                   ;; The element is a cons.  Either the cdr is a
2797                   ;; string to be inserted verbatim, or it is a
2798                   ;; function, and we insert the value returned from
2799                   ;; this function.
2800                   (or (and (stringp (cdr elem)) (cdr elem))
2801                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2802                  ((and (boundp header) (symbol-value header))
2803                   ;; The element is a symbol.  We insert the value
2804                   ;; of this symbol, if any.
2805                   (symbol-value header))
2806                  (t
2807                   ;; We couldn't generate a value for this header,
2808                   ;; so we just ask the user.
2809                   (read-from-minibuffer
2810                    (format "Empty header for %s; enter value: " header)))))
2811           ;; Finally insert the header.
2812           (when (and value
2813                      (not (equal value "")))
2814             (save-excursion
2815               (if (bolp)
2816                   (progn
2817                     ;; This header didn't exist, so we insert it.
2818                     (goto-char (point-max))
2819                     (insert (symbol-name header) ": " value "\n")
2820                     (forward-line -1))
2821                 ;; The value of this header was empty, so we clear
2822                 ;; totally and insert the new value.
2823                 (delete-region (point) (gnus-point-at-eol))
2824                 (insert value))
2825               ;; Add the deletable property to the headers that require it.
2826               (and (memq header message-deletable-headers)
2827                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2828                    (add-text-properties
2829                     (point) (match-end 0)
2830                     '(message-deletable t face italic) (current-buffer)))))))
2831       ;; Insert new Sender if the From is strange.
2832       (let ((from (message-fetch-field "from"))
2833             (sender (message-fetch-field "sender"))
2834             (secure-sender (message-make-sender)))
2835         (when (and from
2836                    (not (message-check-element 'sender))
2837                    (not (string=
2838                          (downcase
2839                           (cadr (mail-extract-address-components from)))
2840                          (downcase secure-sender)))
2841                    (or (null sender)
2842                        (not
2843                         (string=
2844                          (downcase
2845                           (cadr (mail-extract-address-components sender)))
2846                          (downcase secure-sender)))))
2847           (goto-char (point-min))
2848           ;; Rename any old Sender headers to Original-Sender.
2849           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2850             (beginning-of-line)
2851             (insert "Original-")
2852             (beginning-of-line))
2853           (when (or (message-news-p)
2854                     (string-match "^[^@]@.+\\..+" secure-sender))
2855             (insert "Sender: " secure-sender "\n")))))))
2856
2857 (defun message-insert-courtesy-copy ()
2858   "Insert a courtesy message in mail copies of combined messages."
2859   (let (newsgroups)
2860     (save-excursion
2861       (save-restriction
2862         (message-narrow-to-headers)
2863         (when (setq newsgroups (message-fetch-field "newsgroups"))
2864           (goto-char (point-max))
2865           (insert "Posted-To: " newsgroups "\n")))
2866       (forward-line 1)
2867       (when message-courtesy-message
2868         (cond
2869          ((string-match "%s" message-courtesy-message)
2870           (insert (format message-courtesy-message newsgroups)))
2871          (t
2872           (insert message-courtesy-message)))))))
2873
2874 ;;;
2875 ;;; Setting up a message buffer
2876 ;;;
2877
2878 (defun message-fill-address (header value)
2879   (save-restriction
2880     (narrow-to-region (point) (point))
2881     (insert (capitalize (symbol-name header))
2882             ": "
2883             (if (consp value) (car value) value)
2884             "\n")
2885     (narrow-to-region (point-min) (1- (point-max)))
2886     (let (quoted last)
2887       (goto-char (point-min))
2888       (while (not (eobp))
2889         (skip-chars-forward "^,\"" (point-max))
2890         (if (or (= (following-char) ?,)
2891                 (eobp))
2892             (when (not quoted)
2893               (if (and (> (current-column) 78)
2894                        last)
2895                   (progn
2896                     (save-excursion
2897                       (goto-char last)
2898                       (insert "\n\t"))
2899                     (setq last (1+ (point))))
2900                 (setq last (1+ (point)))))
2901           (setq quoted (not quoted)))
2902         (unless (eobp)
2903           (forward-char 1))))
2904     (goto-char (point-max))
2905     (widen)
2906     (forward-line 1)))
2907
2908 (defun message-fill-header (header value)
2909   (let ((begin (point))
2910         (fill-column 78)
2911         (fill-prefix "\t"))
2912     (insert (capitalize (symbol-name header))
2913             ": "
2914             (if (consp value) (car value) value)
2915             "\n")
2916     (save-restriction
2917       (narrow-to-region begin (point))
2918       (fill-region-as-paragraph begin (point))
2919       ;; Tapdance around looong Message-IDs.
2920       (forward-line -1)
2921       (when (looking-at "[ \t]*$")
2922         (message-delete-line))
2923       (goto-char begin)
2924       (re-search-forward ":" nil t)
2925       (when (looking-at "\n[ \t]+")
2926         (replace-match " " t t))
2927       (goto-char (point-max)))))
2928
2929 (defun message-position-point ()
2930   "Move point to where the user probably wants to find it."
2931   (message-narrow-to-headers)
2932   (cond
2933    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2934     (search-backward ":" )
2935     (widen)
2936     (forward-char 1)
2937     (if (= (following-char) ? )
2938         (forward-char 1)
2939       (insert " ")))
2940    (t
2941     (goto-char (point-max))
2942     (widen)
2943     (forward-line 1)
2944     (unless (looking-at "$")
2945       (forward-line 2)))
2946    (sit-for 0)))
2947
2948 (defun message-buffer-name (type &optional to group)
2949   "Return a new (unique) buffer name based on TYPE and TO."
2950   (cond
2951    ;; Check whether `message-generate-new-buffers' is a function,
2952    ;; and if so, call it.
2953    ((message-functionp message-generate-new-buffers)
2954     (funcall message-generate-new-buffers type to group))
2955    ;; Generate a new buffer name The Message Way.
2956    (message-generate-new-buffers
2957     (generate-new-buffer-name
2958      (concat "*" type
2959              (if to
2960                  (concat " to "
2961                          (or (car (mail-extract-address-components to))
2962                              to) "")
2963                "")
2964              (if (and group (not (string= group ""))) (concat " on " group) "")
2965              "*")))
2966    ;; Use standard name.
2967    (t
2968     (format "*%s message*" type))))
2969
2970 (defun message-pop-to-buffer (name)
2971   "Pop to buffer NAME, and warn if it already exists and is modified."
2972   (let ((buffer (get-buffer name)))
2973     (if (and buffer
2974              (buffer-name buffer))
2975         (progn
2976           (set-buffer (pop-to-buffer buffer))
2977           (when (and (buffer-modified-p)
2978                      (not (y-or-n-p
2979                            "Message already being composed; erase? ")))
2980             (error "Message being composed")))
2981       (set-buffer (pop-to-buffer name))))
2982   (erase-buffer)
2983   (message-mode))
2984
2985 (defun message-do-send-housekeeping ()
2986   "Kill old message buffers."
2987   ;; We might have sent this buffer already.  Delete it from the
2988   ;; list of buffers.
2989   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2990   (while (and message-max-buffers
2991               message-buffer-list
2992               (>= (length message-buffer-list) message-max-buffers))
2993     ;; Kill the oldest buffer -- unless it has been changed.
2994     (let ((buffer (pop message-buffer-list)))
2995       (when (and (buffer-name buffer)
2996                  (not (buffer-modified-p buffer)))
2997         (kill-buffer buffer))))
2998   ;; Rename the buffer.
2999   (if message-send-rename-function
3000       (funcall message-send-rename-function)
3001     (when (string-match "\\`\\*" (buffer-name))
3002       (rename-buffer
3003        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3004   ;; Push the current buffer onto the list.
3005   (when message-max-buffers
3006     (setq message-buffer-list
3007           (nconc message-buffer-list (list (current-buffer))))))
3008
3009 (defvar mc-modes-alist)
3010 (defun message-setup (headers &optional replybuffer actions)
3011   (when (and (boundp 'mc-modes-alist)
3012              (not (assq 'message-mode mc-modes-alist)))
3013     (push '(message-mode (encrypt . mc-encrypt-message)
3014                          (sign . mc-sign-message))
3015           mc-modes-alist))
3016   (when actions
3017     (setq message-send-actions actions))
3018   (setq message-reply-buffer replybuffer)
3019   (goto-char (point-min))
3020   ;; Insert all the headers.
3021   (mail-header-format
3022    (let ((h headers)
3023          (alist message-header-format-alist))
3024      (while h
3025        (unless (assq (caar h) message-header-format-alist)
3026          (push (list (caar h)) alist))
3027        (pop h))
3028      alist)
3029    headers)
3030   (delete-region (point) (progn (forward-line -1) (point)))
3031   (when message-default-headers
3032     (insert message-default-headers)
3033     (or (bolp) (insert ?\n)))
3034   (put-text-property
3035    (point)
3036    (progn
3037      (insert mail-header-separator "\n")
3038      (1- (point)))
3039    'read-only nil)
3040   (forward-line -1)
3041   (when (message-news-p)
3042     (when message-default-news-headers
3043       (insert message-default-news-headers)
3044       (or (bolp) (insert ?\n)))
3045     (when message-generate-headers-first
3046       (message-generate-headers
3047        (delq 'Lines
3048              (delq 'Subject
3049                    (copy-sequence message-required-news-headers))))))
3050   (when (message-mail-p)
3051     (when message-default-mail-headers
3052       (insert message-default-mail-headers)
3053       (or (bolp) (insert ?\n)))
3054     (when message-generate-headers-first
3055       (message-generate-headers
3056        (delq 'Lines
3057              (delq 'Subject
3058                    (copy-sequence message-required-mail-headers))))))
3059   (run-hooks 'message-signature-setup-hook)
3060   (message-insert-signature)
3061   (save-restriction
3062     (message-narrow-to-headers)
3063     (run-hooks 'message-header-setup-hook))
3064   (set-buffer-modified-p nil)
3065   (setq buffer-undo-list nil)
3066   (run-hooks 'message-setup-hook)
3067   (message-position-point)
3068   (undo-boundary))
3069
3070 (defun message-set-auto-save-file-name ()
3071   "Associate the message buffer with a file in the drafts directory."
3072   (when message-autosave-directory
3073     (setq message-draft-article (nndraft-request-associate-buffer "drafts"))
3074     (clear-visited-file-modtime)))
3075
3076 (defun message-disassociate-draft ()
3077   "Disassociate the message buffer from the drafts directory."
3078   (when message-draft-article
3079     (nndraft-request-expire-articles
3080      (list message-draft-article) "drafts" nil t)))
3081
3082 \f
3083
3084 ;;;
3085 ;;; Commands for interfacing with message
3086 ;;;
3087
3088 ;;;###autoload
3089 (defun message-mail (&optional to subject
3090                                other-headers continue switch-function
3091                                yank-action send-actions)
3092   "Start editing a mail message to be sent."
3093   (interactive)
3094   (let ((message-this-is-mail t))
3095     (message-pop-to-buffer (message-buffer-name "mail" to))
3096     (message-setup
3097      (nconc
3098       `((To . ,(or to "")) (Subject . ,(or subject "")))
3099       (when other-headers other-headers)))))
3100
3101 ;;;###autoload
3102 (defun message-news (&optional newsgroups subject)
3103   "Start editing a news article to be sent."
3104   (interactive)
3105   (let ((message-this-is-news t))
3106     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3107     (message-setup `((Newsgroups . ,(or newsgroups ""))
3108                      (Subject . ,(or subject ""))))))
3109
3110 ;;;###autoload
3111 (defun message-reply (&optional to-address wide ignore-reply-to)
3112   "Start editing a reply to the article in the current buffer."
3113   (interactive)
3114   (let ((cur (current-buffer))
3115         from subject date reply-to to cc
3116         references message-id follow-to
3117         (inhibit-point-motion-hooks t)
3118         mct never-mct gnus-warning)
3119     (save-restriction
3120       (message-narrow-to-head)
3121       ;; Allow customizations to have their say.
3122       (if (not wide)
3123           ;; This is a regular reply.
3124           (if (message-functionp message-reply-to-function)
3125               (setq follow-to (funcall message-reply-to-function)))
3126         ;; This is a followup.
3127         (if (message-functionp message-wide-reply-to-function)
3128             (save-excursion
3129               (setq follow-to
3130                     (funcall message-wide-reply-to-function)))))
3131       ;; Find all relevant headers we need.
3132       (setq from (message-fetch-field "from")
3133             date (message-fetch-field "date")
3134             subject (or (message-fetch-field "subject") "none")
3135             to (message-fetch-field "to")
3136             cc (message-fetch-field "cc")
3137             mct (message-fetch-field "mail-copies-to")
3138             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
3139             references (message-fetch-field "references")
3140             message-id (message-fetch-field "message-id" t))
3141       ;; Remove any (buggy) Re:'s that are present and make a
3142       ;; proper one.
3143       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3144         (setq subject (substring subject (match-end 0))))
3145       (setq subject (concat "Re: " subject))
3146
3147       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3148                  (string-match "<[^>]+>" gnus-warning))
3149         (setq message-id (match-string 0 gnus-warning)))
3150
3151       ;; Handle special values of Mail-Copies-To.
3152       (when mct
3153         (cond ((equal (downcase mct) "never")
3154                (setq never-mct t)
3155                (setq mct nil))
3156               ((equal (downcase mct) "always")
3157                (setq mct (or reply-to from)))))
3158
3159       (unless follow-to
3160         (if (or (not wide)
3161                 to-address)
3162             (progn
3163               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3164               (when (and wide mct)
3165                 (push (cons 'Cc mct) follow-to)))
3166           (let (ccalist)
3167             (save-excursion
3168               (message-set-work-buffer)
3169               (unless never-mct
3170                 (insert (or reply-to from "")))
3171               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3172               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3173               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3174               (goto-char (point-min))
3175               (while (re-search-forward "[ \t]+" nil t)
3176                 (replace-match " " t t))
3177               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3178               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3179                         (erase-buffer)))
3180               (goto-char (point-min))
3181               ;; Perhaps Mail-Copies-To: never removed the only address?
3182               (when (eobp)
3183                 (insert (or reply-to from "")))
3184               (setq ccalist
3185                     (mapcar
3186                      (lambda (addr)
3187                        (cons (mail-strip-quoted-names addr) addr))
3188                      (message-tokenize-header (buffer-string))))
3189               (let ((s ccalist))
3190                 (while s
3191                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3192             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3193             (when ccalist
3194               (let ((ccs (cons 'Cc (mapconcat
3195                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3196                 (when (string-match "^ +" (cdr ccs))
3197                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3198                 (push ccs follow-to))))))
3199       (widen))
3200
3201     (message-pop-to-buffer (message-buffer-name
3202                             (if wide "wide reply" "reply") from
3203                             (if wide to-address nil)))
3204
3205     (setq message-reply-headers
3206           (vector 0 subject from date message-id references 0 0 ""))
3207
3208     (message-setup
3209      `((Subject . ,subject)
3210        ,@follow-to
3211        ,@(if (or references message-id)
3212              `((References . ,(concat (or references "") (and references " ")
3213                                       (or message-id ""))))
3214            nil))
3215      cur)))
3216
3217 ;;;###autoload
3218 (defun message-wide-reply (&optional to-address ignore-reply-to)
3219   "Make a \"wide\" reply to the message in the current buffer."
3220   (interactive)
3221   (message-reply to-address t ignore-reply-to))
3222
3223 ;;;###autoload
3224 (defun message-followup (&optional to-newsgroups)
3225   "Follow up to the message in the current buffer.
3226 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3227   (interactive)
3228   (let ((cur (current-buffer))
3229         from subject date reply-to mct
3230         references message-id follow-to
3231         (inhibit-point-motion-hooks t)
3232         (message-this-is-news t)
3233         followup-to distribution newsgroups gnus-warning posted-to)
3234     (save-restriction
3235       (narrow-to-region
3236        (goto-char (point-min))
3237        (if (search-forward "\n\n" nil t)
3238            (1- (point))
3239          (point-max)))
3240       (when (message-functionp message-followup-to-function)
3241         (setq follow-to
3242               (funcall message-followup-to-function)))
3243       (setq from (message-fetch-field "from")
3244             date (message-fetch-field "date")
3245             subject (or (message-fetch-field "subject") "none")
3246             references (message-fetch-field "references")
3247             message-id (message-fetch-field "message-id" t)
3248             followup-to (message-fetch-field "followup-to")
3249             newsgroups (message-fetch-field "newsgroups")
3250             posted-to (message-fetch-field "posted-to")
3251             reply-to (message-fetch-field "reply-to")
3252             distribution (message-fetch-field "distribution")
3253             mct (message-fetch-field "mail-copies-to"))
3254       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3255                  (string-match "<[^>]+>" gnus-warning))
3256         (setq message-id (match-string 0 gnus-warning)))
3257       ;; Remove bogus distribution.
3258       (when (and (stringp distribution)
3259                  (let ((case-fold-search t))
3260                    (string-match "world" distribution)))
3261         (setq distribution nil))
3262       ;; Remove any (buggy) Re:'s that are present and make a
3263       ;; proper one.
3264       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3265         (setq subject (substring subject (match-end 0))))
3266       (setq subject (concat "Re: " subject))
3267       (widen))
3268
3269     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3270
3271     (message-setup
3272      `((Subject . ,subject)
3273        ,@(cond
3274           (to-newsgroups
3275            (list (cons 'Newsgroups to-newsgroups)))
3276           (follow-to follow-to)
3277           ((and followup-to message-use-followup-to)
3278            (list
3279             (cond
3280              ((equal (downcase followup-to) "poster")
3281               (if (or (eq message-use-followup-to 'use)
3282                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3283 You should normally obey the Followup-To: header.
3284
3285 `Followup-To: poster' sends your response via e-mail instead of news.
3286
3287 A typical situation where `Followup-To: poster' is used is when the poster
3288 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3289                   (progn
3290                     (setq message-this-is-news nil)
3291                     (cons 'To (or reply-to from "")))
3292                 (cons 'Newsgroups newsgroups)))
3293              (t
3294               (if (or (equal followup-to newsgroups)
3295                       (not (eq message-use-followup-to 'ask))
3296                       (message-y-or-n-p
3297                        (concat "Obey Followup-To: " followup-to "? ") t "\
3298 You should normally obey the Followup-To: header.
3299
3300         `Followup-To: " followup-to "'
3301 directs your response to " (if (string-match "," followup-to)
3302                                "the specified newsgroups"
3303                              "that newsgroup only") ".
3304
3305 If a message is posted to several newsgroups, Followup-To is often
3306 used to direct the following discussion to one newsgroup only,
3307 because discussions that are spread over several newsgroup tend to
3308 be fragmented and very difficult to follow.
3309
3310 Also, some source/announcement newsgroups are not indented for discussion;
3311 responses here are directed to other newsgroups."))
3312                   (cons 'Newsgroups followup-to)
3313                 (cons 'Newsgroups newsgroups))))))
3314           (posted-to
3315            `((Newsgroups . ,posted-to)))
3316           (t
3317            `((Newsgroups . ,newsgroups))))
3318        ,@(and distribution (list (cons 'Distribution distribution)))
3319        ,@(if (or references message-id)
3320              `((References . ,(concat (or references "") (and references " ")
3321                                       (or message-id "")))))
3322        ,@(when (and mct
3323                     (not (equal (downcase mct) "never")))
3324            (list (cons 'Cc (if (equal (downcase mct) "always")
3325                                (or reply-to from "")
3326                              mct)))))
3327
3328      cur)
3329
3330     (setq message-reply-headers
3331           (vector 0 subject from date message-id references 0 0 ""))))
3332
3333
3334 ;;;###autoload
3335 (defun message-cancel-news ()
3336   "Cancel an article you posted."
3337   (interactive)
3338   (unless (message-news-p)
3339     (error "This is not a news article; canceling is impossible"))
3340   (when (yes-or-no-p "Do you really want to cancel this article? ")
3341     (let (from newsgroups message-id distribution buf)
3342       (save-excursion
3343         ;; Get header info. from original article.
3344         (save-restriction
3345           (message-narrow-to-head)
3346           (setq from (message-fetch-field "from")
3347                 newsgroups (message-fetch-field "newsgroups")
3348                 message-id (message-fetch-field "message-id" t)
3349                 distribution (message-fetch-field "distribution")))
3350         ;; Make sure that this article was written by the user.
3351         (unless (string-equal
3352                  (downcase (cadr (mail-extract-address-components from)))
3353                  (downcase (message-make-address)))
3354           (error "This article is not yours"))
3355         ;; Make control message.
3356         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3357         (buffer-disable-undo (current-buffer))
3358         (erase-buffer)
3359         (insert "Newsgroups: " newsgroups "\n"
3360                 "From: " (message-make-from) "\n"
3361                 "Subject: cmsg cancel " message-id "\n"
3362                 "Control: cancel " message-id "\n"
3363                 (if distribution
3364                     (concat "Distribution: " distribution "\n")
3365                   "")
3366                 mail-header-separator "\n"
3367                 message-cancel-message)
3368         (message "Canceling your article...")
3369         (if (let ((message-syntax-checks
3370                    'dont-check-for-anything-just-trust-me))
3371               (funcall message-send-news-function))
3372             (message "Canceling your article...done"))
3373         (kill-buffer buf)))))
3374
3375 ;;;###autoload
3376 (defun message-supersede ()
3377   "Start composing a message to supersede the current message.
3378 This is done simply by taking the old article and adding a Supersedes
3379 header line with the old Message-ID."
3380   (interactive)
3381   (let ((cur (current-buffer)))
3382     ;; Check whether the user owns the article that is to be superseded.
3383     (unless (string-equal
3384              (downcase (cadr (mail-extract-address-components
3385                               (message-fetch-field "from"))))
3386              (downcase (message-make-address)))
3387       (error "This article is not yours"))
3388     ;; Get a normal message buffer.
3389     (message-pop-to-buffer (message-buffer-name "supersede"))
3390     (insert-buffer-substring cur)
3391     (message-narrow-to-head)
3392     ;; Remove unwanted headers.
3393     (when message-ignored-supersedes-headers
3394       (message-remove-header message-ignored-supersedes-headers t))
3395     (goto-char (point-min))
3396     (if (not (re-search-forward "^Message-ID: " nil t))
3397         (error "No Message-ID in this article")
3398       (replace-match "Supersedes: " t t))
3399     (goto-char (point-max))
3400     (insert mail-header-separator)
3401     (widen)
3402     (forward-line 1)))
3403
3404 ;;;###autoload
3405 (defun message-recover ()
3406   "Reread contents of current buffer from its last auto-save file."
3407   (interactive)
3408   (let ((file-name (make-auto-save-file-name)))
3409     (cond ((save-window-excursion
3410              (if (not (eq system-type 'vax-vms))
3411                  (with-output-to-temp-buffer "*Directory*"
3412                    (buffer-disable-undo standard-output)
3413                    (let ((default-directory "/"))
3414                      (call-process
3415                       "ls" nil standard-output nil "-l" file-name))))
3416              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3417            (let ((buffer-read-only nil))
3418              (erase-buffer)
3419              (insert-file-contents file-name nil)))
3420           (t (error "message-recover cancelled")))))
3421
3422 ;;; Forwarding messages.
3423
3424 (defun message-make-forward-subject ()
3425   "Return a Subject header suitable for the message in the current buffer."
3426   (save-excursion
3427     (save-restriction
3428       (current-buffer)
3429       (message-narrow-to-head)
3430       (concat "[" (or (message-fetch-field
3431                        (if (message-news-p) "newsgroups" "from"))
3432                       "(nowhere)")
3433               "] " (or (message-fetch-field "Subject") "")))))
3434
3435 ;;;###autoload
3436 (defun message-forward (&optional news)
3437   "Forward the current message via mail.
3438 Optional NEWS will use news to forward instead of mail."
3439   (interactive "P")
3440   (let ((cur (current-buffer))
3441         (subject (message-make-forward-subject))
3442         art-beg)
3443     (if news (message-news nil subject) (message-mail nil subject))
3444     ;; Put point where we want it before inserting the forwarded
3445     ;; message.
3446     (if message-signature-before-forwarded-message
3447         (goto-char (point-max))
3448       (message-goto-body))
3449     ;; Make sure we're at the start of the line.
3450     (unless (eolp)
3451       (insert "\n"))
3452     ;; Narrow to the area we are to insert.
3453     (narrow-to-region (point) (point))
3454     ;; Insert the separators and the forwarded buffer.
3455     (insert message-forward-start-separator)
3456     (setq art-beg (point))
3457     (insert-buffer-substring cur)
3458     (goto-char (point-max))
3459     (insert message-forward-end-separator)
3460     (set-text-properties (point-min) (point-max) nil)
3461     ;; Remove all unwanted headers.
3462     (goto-char art-beg)
3463     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3464                                   (1- (point))
3465                                 (point)))
3466     (goto-char (point-min))
3467     (message-remove-header message-included-forward-headers t nil t)
3468     (widen)
3469     (message-position-point)))
3470
3471 ;;;###autoload
3472 (defun message-resend (address)
3473   "Resend the current article to ADDRESS."
3474   (interactive "sResend message to: ")
3475   (message "Resending message to %s..." address)
3476   (save-excursion
3477     (let ((cur (current-buffer))
3478           beg)
3479       ;; We first set up a normal mail buffer.
3480       (set-buffer (get-buffer-create " *message resend*"))
3481       (buffer-disable-undo (current-buffer))
3482       (erase-buffer)
3483       (message-setup `((To . ,address)))
3484       ;; Insert our usual headers.
3485       (message-generate-headers '(From Date To))
3486       (message-narrow-to-headers)
3487       ;; Rename them all to "Resent-*".
3488       (while (re-search-forward "^[A-Za-z]" nil t)
3489         (forward-char -1)
3490         (insert "Resent-"))
3491       (widen)
3492       (forward-line)
3493       (delete-region (point) (point-max))
3494       (setq beg (point))
3495       ;; Insert the message to be resent.
3496       (insert-buffer-substring cur)
3497       (goto-char (point-min))
3498       (search-forward "\n\n")
3499       (forward-char -1)
3500       (save-restriction
3501         (narrow-to-region beg (point))
3502         (message-remove-header message-ignored-resent-headers t)
3503         (goto-char (point-max)))
3504       (insert mail-header-separator)
3505       ;; Rename all old ("Also-")Resent headers.
3506       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3507         (beginning-of-line)
3508         (insert "Also-"))
3509       ;; Quote any "From " lines at the beginning.
3510       (goto-char beg)
3511       (when (looking-at "From ")
3512         (replace-match "X-From-Line: "))
3513       ;; Send it.
3514       (message-send-mail)
3515       (kill-buffer (current-buffer)))
3516     (message "Resending message to %s...done" address)))
3517
3518 ;;;###autoload
3519 (defun message-bounce ()
3520   "Re-mail the current message.
3521 This only makes sense if the current message is a bounce message than
3522 contains some mail you have written which has been bounced back to
3523 you."
3524   (interactive)
3525   (let ((cur (current-buffer))
3526         boundary)
3527     (message-pop-to-buffer (message-buffer-name "bounce"))
3528     (insert-buffer-substring cur)
3529     (undo-boundary)
3530     (message-narrow-to-head)
3531     (if (and (message-fetch-field "Mime-Version")
3532              (setq boundary (message-fetch-field "Content-Type")))
3533         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3534             (setq boundary (concat (match-string 1 boundary) " *\n"
3535                                    "Content-Type: message/rfc822"))
3536           (setq boundary nil)))
3537     (widen)
3538     (goto-char (point-min))
3539     (search-forward "\n\n" nil t)
3540     (or (and boundary
3541              (re-search-forward boundary nil t)
3542              (forward-line 2))
3543         (and (re-search-forward message-unsent-separator nil t)
3544              (forward-line 1))
3545         (re-search-forward "^Return-Path:.*\n" nil t))
3546     ;; We remove everything before the bounced mail.
3547     (delete-region
3548      (point-min)
3549      (if (re-search-forward "^[^ \n\t]+:" nil t)
3550          (match-beginning 0)
3551        (point)))
3552     (save-restriction
3553       (message-narrow-to-head)
3554       (message-remove-header message-ignored-bounced-headers t)
3555       (goto-char (point-max))
3556       (insert mail-header-separator))
3557     (message-position-point)))
3558
3559 ;;;
3560 ;;; Interactive entry points for new message buffers.
3561 ;;;
3562
3563 ;;;###autoload
3564 (defun message-mail-other-window (&optional to subject)
3565   "Like `message-mail' command, but display mail buffer in another window."
3566   (interactive)
3567   (let ((pop-up-windows t)
3568         (special-display-buffer-names nil)
3569         (special-display-regexps nil)
3570         (same-window-buffer-names nil)
3571         (same-window-regexps nil))
3572     (message-pop-to-buffer (message-buffer-name "mail" to)))
3573   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3574
3575 ;;;###autoload
3576 (defun message-mail-other-frame (&optional to subject)
3577   "Like `message-mail' command, but display mail buffer in another frame."
3578   (interactive)
3579   (let ((pop-up-frames t)
3580         (special-display-buffer-names nil)
3581         (special-display-regexps nil)
3582         (same-window-buffer-names nil)
3583         (same-window-regexps nil))
3584     (message-pop-to-buffer (message-buffer-name "mail" to)))
3585   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3586
3587 ;;;###autoload
3588 (defun message-news-other-window (&optional newsgroups subject)
3589   "Start editing a news article to be sent."
3590   (interactive)
3591   (let ((pop-up-windows t)
3592         (special-display-buffer-names nil)
3593         (special-display-regexps nil)
3594         (same-window-buffer-names nil)
3595         (same-window-regexps nil))
3596     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3597   (message-setup `((Newsgroups . ,(or newsgroups ""))
3598                    (Subject . ,(or subject "")))))
3599
3600 ;;;###autoload
3601 (defun message-news-other-frame (&optional newsgroups subject)
3602   "Start editing a news article to be sent."
3603   (interactive)
3604   (let ((pop-up-frames t)
3605         (special-display-buffer-names nil)
3606         (special-display-regexps nil)
3607         (same-window-buffer-names nil)
3608         (same-window-regexps nil))
3609     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3610   (message-setup `((Newsgroups . ,(or newsgroups ""))
3611                    (Subject . ,(or subject "")))))
3612
3613 ;;; underline.el
3614
3615 ;; This code should be moved to underline.el (from which it is stolen).
3616
3617 ;;;###autoload
3618 (defun bold-region (start end)
3619   "Bold all nonblank characters in the region.
3620 Works by overstriking characters.
3621 Called from program, takes two arguments START and END
3622 which specify the range to operate on."
3623   (interactive "r")
3624   (save-excursion
3625     (let ((end1 (make-marker)))
3626       (move-marker end1 (max start end))
3627       (goto-char (min start end))
3628       (while (< (point) end1)
3629         (or (looking-at "[_\^@- ]")
3630             (insert (following-char) "\b"))
3631         (forward-char 1)))))
3632
3633 ;;;###autoload
3634 (defun unbold-region (start end)
3635   "Remove all boldness (overstruck characters) in the region.
3636 Called from program, takes two arguments START and END
3637 which specify the range to operate on."
3638   (interactive "r")
3639   (save-excursion
3640     (let ((end1 (make-marker)))
3641       (move-marker end1 (max start end))
3642       (goto-char (min start end))
3643       (while (re-search-forward "\b" end1 t)
3644         (if (eq (following-char) (char-after (- (point) 2)))
3645             (delete-char -2))))))
3646
3647 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3648
3649 ;; Support for toolbar
3650 (when (string-match "XEmacs\\|Lucid" emacs-version)
3651   (require 'messagexmas))
3652
3653 ;;; Group name completion.
3654
3655 (defvar message-newgroups-header-regexp
3656   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3657   "Regexp that match headers that lists groups.")
3658
3659 (defun message-tab ()
3660   "Expand group names in Newsgroups and Followup-To headers.
3661 Do a `tab-to-tab-stop' if not in those headers."
3662   (interactive)
3663   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3664         (mail-abbrev-in-expansion-header-p))
3665       (message-expand-group)
3666     (tab-to-tab-stop)))
3667
3668 (defvar gnus-active-hashtb)
3669 (defun message-expand-group ()
3670   (let* ((b (save-excursion
3671               (save-restriction
3672                 (narrow-to-region
3673                  (save-excursion
3674                    (beginning-of-line)
3675                    (skip-chars-forward "^:")
3676                    (1+ (point)))
3677                  (point))
3678                 (skip-chars-backward "^, \t\n") (point))))
3679          (completion-ignore-case t)
3680          (string (buffer-substring b (point)))
3681          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3682          (completions (all-completions string hashtb))
3683          (cur (current-buffer))
3684          comp)
3685     (delete-region b (point))
3686     (cond
3687      ((= (length completions) 1)
3688       (if (string= (car completions) string)
3689           (progn
3690             (insert string)
3691             (message "Only matching group"))
3692         (insert (car completions))))
3693      ((and (setq comp (try-completion string hashtb))
3694            (not (string= comp string)))
3695       (insert comp))
3696      (t
3697       (insert string)
3698       (if (not comp)
3699           (message "No matching groups")
3700         (save-selected-window
3701           (pop-to-buffer "*Completions*")
3702           (buffer-disable-undo (current-buffer))
3703           (let ((buffer-read-only nil))
3704             (erase-buffer)
3705             (let ((standard-output (current-buffer)))
3706               (display-completion-list (sort completions 'string<)))
3707             (goto-char (point-min))
3708             (delete-region (point) (progn (forward-line 3) (point))))))))))
3709
3710 ;;; Help stuff.
3711
3712 (defun message-talkative-question (ask question show &rest text)
3713   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3714 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3715 The following arguments may contain lists of values."
3716   (if (and show
3717            (setq text (message-flatten-list text)))
3718       (save-window-excursion
3719         (save-excursion
3720           (with-output-to-temp-buffer " *MESSAGE information message*"
3721             (set-buffer " *MESSAGE information message*")
3722             (mapcar 'princ text)
3723             (goto-char (point-min))))
3724         (funcall ask question))
3725     (funcall ask question)))
3726
3727 (defun message-flatten-list (list)
3728   "Return a new, flat list that contains all elements of LIST.
3729
3730 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3731 => (1 2 3 4 5 6 7)"
3732   (cond ((consp list)
3733          (apply 'append (mapcar 'message-flatten-list list)))
3734         (list
3735          (list list))))
3736
3737 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3738   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3739 Then clone the local variables and values from the old buffer to the
3740 new one, cloning only the locals having a substring matching the
3741 regexp varstr."
3742   (let ((oldbuf (current-buffer)))
3743     (save-excursion
3744       (set-buffer (generate-new-buffer name))
3745       (message-clone-locals oldbuf)
3746       (current-buffer))))
3747
3748 (defun message-clone-locals (buffer)
3749   "Clone the local variables from BUFFER to the current buffer."
3750   (let ((locals (save-excursion
3751                   (set-buffer buffer)
3752                   (buffer-local-variables)))
3753         (regexp "^gnus\\|^nn\\|^message"))
3754     (mapcar
3755      (lambda (local)
3756        (when (and (consp local)
3757                   (car local)
3758                   (string-match regexp (symbol-name (car local))))
3759          (ignore-errors
3760            (set (make-local-variable (car local))
3761                 (cdr local)))))
3762      locals)))
3763
3764 ;;; Miscellaneous functions
3765
3766 ;; stolen (and renamed) from nnheader.el
3767 (defun message-replace-chars-in-string (string from to)
3768   "Replace characters in STRING from FROM to TO."
3769   (let ((string (substring string 0))   ;Copy string.
3770         (len (length string))
3771         (idx 0))
3772     ;; Replace all occurrences of FROM with TO.
3773     (while (< idx len)
3774       (when (= (aref string idx) from)
3775         (aset string idx to))
3776       (setq idx (1+ idx)))
3777     string))
3778
3779 (run-hooks 'message-load-hook)
3780
3781 (provide 'message)
3782
3783 ;;; message.el ends here