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