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