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