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