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