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