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