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