*** 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 (yes-or-no-p "Kill the buffer? ")
1659     (let ((actions message-kill-actions))
1660       (kill-buffer (current-buffer))
1661       (message-do-actions actions))))
1662
1663 (defun message-bury (buffer)
1664   "Bury this mail buffer."
1665   (let ((newbuf (other-buffer buffer)))
1666     (bury-buffer buffer)
1667     (if (and (fboundp 'frame-parameters)
1668              (cdr (assq 'dedicated (frame-parameters)))
1669              (not (null (delq (selected-frame) (visible-frame-list)))))
1670         (delete-frame (selected-frame))
1671       (switch-to-buffer newbuf))))
1672
1673 (defun message-send (&optional arg)
1674   "Send the message in the current buffer.
1675 If `message-interactive' is non-nil, wait for success indication
1676 or error messages, and inform user.
1677 Otherwise any failure is reported in a message back to
1678 the user from the mailer."
1679   (interactive "P")
1680   (when (if buffer-file-name
1681             (y-or-n-p (format "Send buffer contents as %s message? "
1682                               (if (message-mail-p)
1683                                   (if (message-news-p) "mail and news" "mail")
1684                                 "news")))
1685           (or (buffer-modified-p)
1686               (y-or-n-p "No changes in the buffer; really send? ")))
1687     ;; Make it possible to undo the coming changes.
1688     (undo-boundary)
1689     (let ((inhibit-read-only t))
1690       (put-text-property (point-min) (point-max) 'read-only nil))
1691     (message-fix-before-sending)
1692     (run-hooks 'message-send-hook)
1693     (message "Sending...")
1694     (when (and (or (not (message-news-p))
1695                    (and (or (not (memq 'news message-sent-message-via))
1696                             (y-or-n-p
1697                              "Already sent message via news; resend? "))
1698                         (funcall message-send-news-function arg)))
1699                (or (not (message-mail-p))
1700                    (and (or (not (memq 'mail message-sent-message-via))
1701                             (y-or-n-p
1702                              "Already sent message via mail; resend? "))
1703                         (message-send-mail arg))))
1704       (message-do-fcc)
1705       ;;(when (fboundp 'mail-hist-put-headers-into-history)
1706       ;; (mail-hist-put-headers-into-history))
1707       (run-hooks 'message-sent-hook)
1708       (message "Sending...done")
1709       ;; If buffer has no file, mark it as unmodified and delete autosave.
1710       (unless buffer-file-name
1711         (set-buffer-modified-p nil)
1712         (delete-auto-save-file-if-necessary t))
1713       ;; Delete other mail buffers and stuff.
1714       (message-do-send-housekeeping)
1715       (message-do-actions message-send-actions)
1716       ;; Return success.
1717       t)))
1718
1719 (defun message-fix-before-sending ()
1720   "Do various things to make the message nice before sending it."
1721   ;; Make sure there's a newline at the end of the message.
1722   (goto-char (point-max))
1723   (unless (bolp)
1724     (insert "\n")))
1725
1726 (defun message-add-action (action &rest types)
1727   "Add ACTION to be performed when doing an exit of type TYPES."
1728   (let (var)
1729     (while types
1730       (set (setq var (intern (format "message-%s-actions" (pop types))))
1731            (nconc (symbol-value var) (list action))))))
1732
1733 (defun message-do-actions (actions)
1734   "Perform all actions in ACTIONS."
1735   ;; Now perform actions on successful sending.
1736   (while actions
1737     (ignore-errors
1738       (cond
1739        ;; A simple function.
1740        ((message-functionp (car actions))
1741         (funcall (car actions)))
1742        ;; Something to be evaled.
1743        (t
1744         (eval (car actions)))))
1745     (pop actions)))
1746
1747 (defun message-send-mail (&optional arg)
1748   (require 'mail-utils)
1749   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1750         (case-fold-search nil)
1751         (news (message-news-p))
1752         (mailbuf (current-buffer)))
1753     (save-restriction
1754       (message-narrow-to-headers)
1755       ;; Insert some headers.
1756       (let ((message-deletable-headers
1757              (if news nil message-deletable-headers)))
1758         (message-generate-headers message-required-mail-headers))
1759       ;; Let the user do all of the above.
1760       (run-hooks 'message-header-hook))
1761     (unwind-protect
1762         (save-excursion
1763           (set-buffer tembuf)
1764           (erase-buffer)
1765           ;; Avoid copying text props.
1766           (insert (format
1767                    "%s" (save-excursion
1768                           (set-buffer mailbuf)
1769                           (buffer-string))))
1770           ;; Remove some headers.
1771           (save-restriction
1772             (message-narrow-to-headers)
1773             ;; Remove some headers.
1774             (message-remove-header message-ignored-mail-headers t))
1775           (goto-char (point-max))
1776           ;; require one newline at the end.
1777           (or (= (preceding-char) ?\n)
1778               (insert ?\n))
1779           (when (and news
1780                      (or (message-fetch-field "cc")
1781                          (message-fetch-field "to")))
1782             (message-insert-courtesy-copy))
1783           (funcall message-send-mail-function))
1784       (kill-buffer tembuf))
1785     (set-buffer mailbuf)
1786     (push 'mail message-sent-message-via)))
1787
1788 (defun message-send-mail-with-sendmail ()
1789   "Send off the prepared buffer with sendmail."
1790   (let ((errbuf (if message-interactive
1791                     (generate-new-buffer " sendmail errors")
1792                   0))
1793         resend-to-addresses delimline)
1794     (let ((case-fold-search t))
1795       (save-restriction
1796         (message-narrow-to-headers)
1797         (setq resend-to-addresses (message-fetch-field "resent-to")))
1798       ;; Change header-delimiter to be what sendmail expects.
1799       (goto-char (point-min))
1800       (re-search-forward
1801        (concat "^" (regexp-quote mail-header-separator) "\n"))
1802       (replace-match "\n")
1803       (backward-char 1)
1804       (setq delimline (point-marker))
1805       (run-hooks 'message-send-mail-hook)
1806       ;; Insert an extra newline if we need it to work around
1807       ;; Sun's bug that swallows newlines.
1808       (goto-char (1+ delimline))
1809       (when (eval message-mailer-swallows-blank-line)
1810         (newline))
1811       (when message-interactive
1812         (save-excursion
1813           (set-buffer errbuf)
1814           (erase-buffer))))
1815     (let ((default-directory "/"))
1816       (apply 'call-process-region
1817              (append (list (point-min) (point-max)
1818                            (if (boundp 'sendmail-program)
1819                                sendmail-program
1820                              "/usr/lib/sendmail")
1821                            nil errbuf nil "-oi")
1822                      ;; Always specify who from,
1823                      ;; since some systems have broken sendmails.
1824                      ;; But some systems are more broken with -f, so
1825                      ;; we'll let users override this.
1826                      (if (null message-sendmail-f-is-evil)
1827                          (list "-f" (user-login-name)))
1828                      ;; These mean "report errors by mail"
1829                      ;; and "deliver in background".
1830                      (if (null message-interactive) '("-oem" "-odb"))
1831                      ;; Get the addresses from the message
1832                      ;; unless this is a resend.
1833                      ;; We must not do that for a resend
1834                      ;; because we would find the original addresses.
1835                      ;; For a resend, include the specific addresses.
1836                      (if resend-to-addresses
1837                          (list resend-to-addresses)
1838                        '("-t")))))
1839     (when message-interactive
1840       (save-excursion
1841         (set-buffer errbuf)
1842         (goto-char (point-min))
1843         (while (re-search-forward "\n\n* *" nil t)
1844           (replace-match "; "))
1845         (if (not (zerop (buffer-size)))
1846             (error "Sending...failed to %s"
1847                    (buffer-substring (point-min) (point-max)))))
1848       (when (bufferp errbuf)
1849         (kill-buffer errbuf)))))
1850
1851 (defun message-send-mail-with-qmail ()
1852   "Pass the prepared message buffer to qmail-inject.
1853 Refer to the documentation for the variable `message-send-mail-function'
1854 to find out how to use this."
1855   ;; replace the header delimiter with a blank line
1856   (goto-char (point-min))
1857   (re-search-forward
1858    (concat "^" (regexp-quote mail-header-separator) "\n"))
1859   (replace-match "\n")
1860   (run-hooks 'message-send-mail-hook)
1861   ;; send the message
1862   (case
1863       (apply
1864        'call-process-region 1 (point-max) message-qmail-inject-program
1865        nil nil nil
1866        ;; qmail-inject's default behaviour is to look for addresses on the
1867        ;; command line; if there're none, it scans the headers.
1868        ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
1869        ;;
1870        ;; in general, ALL of qmail-inject's defaults are perfect for simply
1871        ;; reading a formatted (i. e., at least a To: or Resent-To header)
1872        ;; message from stdin.
1873        ;;
1874        ;; qmail also has the advantage of not having been raped by
1875        ;; various vendors, so we don't have to allow for that, either --
1876        ;; compare this with message-send-mail-with-sendmail and weep
1877        ;; for sendmail's lost innocence.
1878        ;;
1879        ;; all this is way cool coz it lets us keep the arguments entirely
1880        ;; free for -inject-arguments -- a big win for the user and for us
1881        ;; since we don't have to play that double-guessing game and the user
1882        ;; gets full control (no gestapo'ish -f's, for instance).  --sj
1883        message-qmail-inject-args)
1884     ;; qmail-inject doesn't say anything on it's stdout/stderr,
1885     ;; we have to look at the retval instead
1886     (0 nil)
1887     (1   (error "qmail-inject reported permanent failure."))
1888     (111 (error "qmail-inject reported transient failure."))
1889     ;; should never happen
1890     (t   (error "qmail-inject reported unknown failure."))))
1891
1892 (defun message-send-mail-with-mh ()
1893   "Send the prepared message buffer with mh."
1894   (let ((mh-previous-window-config nil)
1895         (name (make-temp-name
1896                (concat (file-name-as-directory
1897                         (expand-file-name message-autosave-directory))
1898                        "msg."))))
1899     (setq buffer-file-name name)
1900     ;; MH wants to generate these headers itself.
1901     (when message-mh-deletable-headers
1902       (let ((headers message-mh-deletable-headers))
1903         (while headers
1904           (goto-char (point-min))
1905           (and (re-search-forward
1906                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1907                (message-delete-line))
1908           (pop headers))))
1909     (run-hooks 'message-send-mail-hook)
1910     ;; Pass it on to mh.
1911     (mh-send-letter)))
1912
1913 (defun message-send-news (&optional arg)
1914   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
1915         (case-fold-search nil)
1916         (method (if (message-functionp message-post-method)
1917                     (funcall message-post-method arg)
1918                   message-post-method))
1919         (messbuf (current-buffer))
1920         (message-syntax-checks
1921          (if arg
1922              (cons '(existing-newsgroups . disabled)
1923                    message-syntax-checks)
1924            message-syntax-checks))
1925         result)
1926     (save-restriction
1927       (message-narrow-to-headers)
1928       ;; Insert some headers.
1929       (message-generate-headers message-required-news-headers)
1930       ;; Let the user do all of the above.
1931       (run-hooks 'message-header-hook))
1932     (message-cleanup-headers)
1933     (if (not (message-check-news-syntax))
1934         (progn
1935           ;;(message "Posting not performed")
1936           nil)
1937       (unwind-protect
1938           (save-excursion
1939             (set-buffer tembuf)
1940             (buffer-disable-undo (current-buffer))
1941             (erase-buffer)
1942             ;; Avoid copying text props.
1943             (insert (format
1944                      "%s" (save-excursion
1945                             (set-buffer messbuf)
1946                             (buffer-string))))
1947             ;; Remove some headers.
1948             (save-restriction
1949               (message-narrow-to-headers)
1950               ;; Remove some headers.
1951               (message-remove-header message-ignored-news-headers t))
1952             (goto-char (point-max))
1953             ;; require one newline at the end.
1954             (or (= (preceding-char) ?\n)
1955                 (insert ?\n))
1956             (let ((case-fold-search t))
1957               ;; Remove the delimiter.
1958               (goto-char (point-min))
1959               (re-search-forward
1960                (concat "^" (regexp-quote mail-header-separator) "\n"))
1961               (replace-match "\n")
1962               (backward-char 1))
1963             (run-hooks 'message-send-news-hook)
1964             (require (car method))
1965             (funcall (intern (format "%s-open-server" (car method)))
1966                      (cadr method) (cddr method))
1967             (setq result
1968                   (funcall (intern (format "%s-request-post" (car method))))))
1969         (kill-buffer tembuf))
1970       (set-buffer messbuf)
1971       (if result
1972           (push 'news message-sent-message-via)
1973         (message "Couldn't send message via news: %s"
1974                  (nnheader-get-report (car method)))
1975         nil))))
1976
1977 ;;;
1978 ;;; Header generation & syntax checking.
1979 ;;;
1980
1981 (defmacro message-check (type &rest forms)
1982   "Eval FORMS if TYPE is to be checked."
1983   `(or (message-check-element ,type)
1984        (save-excursion
1985          ,@forms)))
1986
1987 (put 'message-check 'lisp-indent-function 1)
1988 (put 'message-check 'edebug-form-spec '(form body))
1989
1990 (defun message-check-element (type)
1991   "Returns non-nil if this type is not to be checked."
1992   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1993       t
1994     (let ((able (assq type message-syntax-checks)))
1995       (and (consp able)
1996            (eq (cdr able) 'disabled)))))
1997
1998 (defun message-check-news-syntax ()
1999   "Check the syntax of the message."
2000   (save-excursion
2001     (save-restriction
2002       (widen)
2003       (and
2004        ;; We narrow to the headers and check them first.
2005        (save-excursion
2006          (save-restriction
2007            (message-narrow-to-headers)
2008            (message-check-news-header-syntax)))
2009        ;; Check the body.
2010        (message-check-news-body-syntax)))))
2011
2012 (defun message-check-news-header-syntax ()
2013   (and
2014    ;; Check for commands in Subject.
2015    (message-check 'subject-cmsg
2016      (if (string-match "^cmsg " (message-fetch-field "subject"))
2017          (y-or-n-p
2018           "The control code \"cmsg\" is in the subject.  Really post? ")
2019        t))
2020    ;; Check for multiple identical headers.
2021    (message-check 'multiple-headers
2022      (let (found)
2023        (while (and (not found)
2024                    (re-search-forward "^[^ \t:]+: " nil t))
2025          (save-excursion
2026            (or (re-search-forward
2027                 (concat "^"
2028                         (regexp-quote
2029                          (setq found
2030                                (buffer-substring
2031                                 (match-beginning 0) (- (match-end 0) 2))))
2032                         ":")
2033                 nil t)
2034                (setq found nil))))
2035        (if found
2036            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2037          t)))
2038    ;; Check for Version and Sendsys.
2039    (message-check 'sendsys
2040      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2041          (y-or-n-p
2042           (format "The article contains a %s command.  Really post? "
2043                   (buffer-substring (match-beginning 0)
2044                                     (1- (match-end 0)))))
2045        t))
2046    ;; See whether we can shorten Followup-To.
2047    (message-check 'shorten-followup-to
2048      (let ((newsgroups (message-fetch-field "newsgroups"))
2049            (followup-to (message-fetch-field "followup-to"))
2050            to)
2051        (when (and newsgroups
2052                   (string-match "," newsgroups)
2053                   (not followup-to)
2054                   (not
2055                    (zerop
2056                     (length
2057                      (setq to (completing-read
2058                                "Followups to: (default all groups) "
2059                                (mapcar (lambda (g) (list g))
2060                                        (cons "poster"
2061                                              (message-tokenize-header
2062                                               newsgroups)))))))))
2063          (goto-char (point-min))
2064          (insert "Followup-To: " to "\n"))
2065        t))
2066    ;; Check "Shoot me".
2067    (message-check 'shoot
2068      (if (re-search-forward
2069           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2070          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2071        t))
2072    ;; Check for Approved.
2073    (message-check 'approved
2074      (if (re-search-forward "^Approved:" nil t)
2075          (y-or-n-p "The article contains an Approved header.  Really post? ")
2076        t))
2077    ;; Check the Message-ID header.
2078    (message-check 'message-id
2079      (let* ((case-fold-search t)
2080             (message-id (message-fetch-field "message-id" t)))
2081        (or (not message-id)
2082            (and (string-match "@" message-id)
2083                 (string-match "@[^\\.]*\\." message-id))
2084            (y-or-n-p
2085             (format "The Message-ID looks strange: \"%s\".  Really post? "
2086                     message-id)))))
2087    ;; Check the Subject header.
2088    (message-check 'subject
2089      (let* ((case-fold-search t)
2090             (subject (message-fetch-field "subject")))
2091        (or
2092         (and subject
2093              (not (string-match "\\`[ \t]*\\'" subject)))
2094         (ignore
2095          (message
2096           "The subject field is empty or missing.  Posting is denied.")))))
2097    ;; Check the Newsgroups & Followup-To headers.
2098    (message-check 'existing-newsgroups
2099      (let* ((case-fold-search t)
2100             (newsgroups (message-fetch-field "newsgroups"))
2101             (followup-to (message-fetch-field "followup-to"))
2102             (groups (message-tokenize-header
2103                      (if followup-to
2104                          (concat newsgroups "," followup-to)
2105                        newsgroups)))
2106             (hashtb (and (boundp 'gnus-active-hashtb)
2107                          gnus-active-hashtb))
2108             errors)
2109        (if (or (not hashtb)
2110                (not (boundp 'gnus-read-active-file))
2111                (not gnus-read-active-file)
2112                (eq gnus-read-active-file 'some))
2113            t
2114          (while groups
2115            (when (and (not (boundp (intern (car groups) hashtb)))
2116                       (not (equal (car groups) "poster")))
2117              (push (car groups) errors))
2118            (pop groups))
2119          (if (not errors)
2120              t
2121            (y-or-n-p
2122             (format
2123              "Really post to %s unknown group%s: %s "
2124              (if (= (length errors) 1) "this" "these")
2125              (if (= (length errors) 1) "" "s")
2126              (mapconcat 'identity errors ", ")))))))
2127    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2128    (message-check 'valid-newsgroups
2129      (let ((case-fold-search t)
2130            (headers '("Newsgroups" "Followup-To"))
2131            header error)
2132        (while (and headers (not error))
2133          (when (setq header (mail-fetch-field (car headers)))
2134            (if (or
2135                 (not
2136                  (string-match
2137                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2138                   header))
2139                 (memq
2140                  nil (mapcar
2141                       (lambda (g)
2142                         (not (string-match "\\.\\'\\|\\.\\." g)))
2143                       (message-tokenize-header header ","))))
2144                (setq error t)))
2145          (unless error
2146            (pop headers)))
2147        (if (not error)
2148            t
2149          (y-or-n-p
2150           (format "The %s header looks odd: \"%s\".  Really post? "
2151                   (car headers) header)))))
2152    ;; Check the From header.
2153    (message-check 'from
2154      (let* ((case-fold-search t)
2155             (from (message-fetch-field "from"))
2156             (ad (nth 1 (mail-extract-address-components from))))
2157        (cond
2158         ((not from)
2159          (message "There is no From line.  Posting is denied.")
2160          nil)
2161         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2162              (string-match "\\.\\." ad) ;larsi@ifi..uio
2163              (string-match "@\\." ad)   ;larsi@.ifi.uio
2164              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2165              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2166              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2167          (message
2168           "Denied posting -- the From looks strange: \"%s\"." from)
2169          nil)
2170         (t t))))))
2171
2172 (defun message-check-news-body-syntax ()
2173   (and
2174    ;; Check for long lines.
2175    (message-check 'long-lines
2176      (goto-char (point-min))
2177      (re-search-forward
2178       (concat "^" (regexp-quote mail-header-separator) "$"))
2179      (while (and
2180              (progn
2181                (end-of-line)
2182                (< (current-column) 80))
2183              (zerop (forward-line 1))))
2184      (or (bolp)
2185          (eobp)
2186          (y-or-n-p
2187           "You have lines longer than 79 characters.  Really post? ")))
2188    ;; Check whether the article is empty.
2189    (message-check 'empty
2190      (goto-char (point-min))
2191      (re-search-forward
2192       (concat "^" (regexp-quote mail-header-separator) "$"))
2193      (forward-line 1)
2194      (let ((b (point)))
2195        (goto-char (point-max))
2196        (re-search-backward message-signature-separator nil t)
2197        (beginning-of-line)
2198        (or (re-search-backward "[^ \n\t]" b t)
2199            (y-or-n-p "Empty article.  Really post? "))))
2200    ;; Check for control characters.
2201    (message-check 'control-chars
2202      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2203          (y-or-n-p
2204           "The article contains control characters.  Really post? ")
2205        t))
2206    ;; Check excessive size.
2207    (message-check 'size
2208      (if (> (buffer-size) 60000)
2209          (y-or-n-p
2210           (format "The article is %d octets long.  Really post? "
2211                   (buffer-size)))
2212        t))
2213    ;; Check whether any new text has been added.
2214    (message-check 'new-text
2215      (or
2216       (not message-checksum)
2217       (not (and (eq (message-checksum) (car message-checksum))
2218                 (eq (buffer-size) (cdr message-checksum))))
2219       (y-or-n-p
2220        "It looks like no new text has been added.  Really post? ")))
2221    ;; Check the length of the signature.
2222    (message-check 'signature
2223      (goto-char (point-max))
2224      (if (or (not (re-search-backward message-signature-separator nil t))
2225              (search-forward message-forward-end-separator nil t))
2226          t
2227        (if (> (count-lines (point) (point-max)) 5)
2228            (y-or-n-p
2229             (format
2230              "Your .sig is %d lines; it should be max 4.  Really post? "
2231              (1- (count-lines (point) (point-max)))))
2232          t)))))
2233
2234 (defun message-checksum ()
2235   "Return a \"checksum\" for the current buffer."
2236   (let ((sum 0))
2237     (save-excursion
2238       (goto-char (point-min))
2239       (re-search-forward
2240        (concat "^" (regexp-quote mail-header-separator) "$"))
2241       (while (not (eobp))
2242         (when (not (looking-at "[ \t\n]"))
2243           (setq sum (logxor (ash sum 1) (following-char))))
2244         (forward-char 1)))
2245     sum))
2246
2247 (defun message-do-fcc ()
2248   "Process Fcc headers in the current buffer."
2249   (let ((case-fold-search t)
2250         (buf (current-buffer))
2251         list file)
2252     (save-excursion
2253       (set-buffer (get-buffer-create " *message temp*"))
2254       (buffer-disable-undo (current-buffer))
2255       (erase-buffer)
2256       (insert-buffer-substring buf)
2257       (save-restriction
2258         (message-narrow-to-headers)
2259         (while (setq file (message-fetch-field "fcc"))
2260           (push file list)
2261           (message-remove-header "fcc" nil t)))
2262       (goto-char (point-min))
2263       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2264       (replace-match "" t t)
2265       ;; Process FCC operations.
2266       (while list
2267         (setq file (pop list))
2268         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2269             ;; Pipe the article to the program in question.
2270             (call-process-region (point-min) (point-max) shell-file-name
2271                                  nil nil nil shell-command-switch
2272                                  (match-string 1 file))
2273           ;; Save the article.
2274           (setq file (expand-file-name file))
2275           (unless (file-exists-p (file-name-directory file))
2276             (make-directory (file-name-directory file) t))
2277           (if (and message-fcc-handler-function
2278                    (not (eq message-fcc-handler-function 'rmail-output)))
2279               (funcall message-fcc-handler-function file)
2280             (if (and (file-readable-p file) (mail-file-babyl-p file))
2281                 (rmail-output file 1 nil t)
2282               (let ((mail-use-rfc822 t))
2283                 (rmail-output file 1 t t))))))
2284
2285       (kill-buffer (current-buffer)))))
2286
2287 (defun message-output (filename)
2288   "Append this article to Unix/babyl mail file.."
2289   (if (and (file-readable-p filename)
2290            (mail-file-babyl-p filename))
2291       (gnus-output-to-rmail filename t)
2292     (gnus-output-to-mail filename t)))
2293
2294 (defun message-cleanup-headers ()
2295   "Do various automatic cleanups of the headers."
2296   ;; Remove empty lines in the header.
2297   (save-restriction
2298     (message-narrow-to-headers)
2299     (while (re-search-forward "^[ \t]*\n" nil t)
2300       (replace-match "" t t)))
2301
2302   ;; Correct Newsgroups and Followup-To headers: change sequence of
2303   ;; spaces to comma and eliminate spaces around commas.  Eliminate
2304   ;; embedded line breaks.
2305   (goto-char (point-min))
2306   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2307     (save-restriction
2308       (narrow-to-region
2309        (point)
2310        (if (re-search-forward "^[^ \t]" nil t)
2311            (match-beginning 0)
2312          (forward-line 1)
2313          (point)))
2314       (goto-char (point-min))
2315       (while (re-search-forward "\n[ \t]+" nil t)
2316         (replace-match " " t t))        ;No line breaks (too confusing)
2317       (goto-char (point-min))
2318       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2319         (replace-match "," t t))
2320       (goto-char (point-min))
2321       ;; Remove trailing commas.
2322       (when (re-search-forward ",+$" nil t)
2323         (replace-match "" t t)))))
2324
2325 (defun message-make-date ()
2326   "Make a valid data header."
2327   (let ((now (current-time)))
2328     (timezone-make-date-arpa-standard
2329      (current-time-string now) (current-time-zone now))))
2330
2331 (defun message-make-message-id ()
2332   "Make a unique Message-ID."
2333   (concat "<" (message-unique-id)
2334           (let ((psubject (save-excursion (message-fetch-field "subject"))))
2335             (if (and message-reply-headers
2336                      (mail-header-references message-reply-headers)
2337                      (mail-header-subject message-reply-headers)
2338                      psubject
2339                      (mail-header-subject message-reply-headers)
2340                      (not (string=
2341                            (message-strip-subject-re
2342                             (mail-header-subject message-reply-headers))
2343                            (message-strip-subject-re psubject))))
2344                 "_-_" ""))
2345           "@" (message-make-fqdn) ">"))
2346
2347 (defvar message-unique-id-char nil)
2348
2349 ;; If you ever change this function, make sure the new version
2350 ;; cannot generate IDs that the old version could.
2351 ;; You might for example insert a "." somewhere (not next to another dot
2352 ;; or string boundary), or modify the "fsf" string.
2353 (defun message-unique-id ()
2354   ;; Don't use microseconds from (current-time), they may be unsupported.
2355   ;; Instead we use this randomly inited counter.
2356   (setq message-unique-id-char
2357         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2358            ;; (current-time) returns 16-bit ints,
2359            ;; and 2^16*25 just fits into 4 digits i base 36.
2360            (* 25 25)))
2361   (let ((tm (current-time)))
2362     (concat
2363      (if (memq system-type '(ms-dos emx vax-vms))
2364          (let ((user (downcase (user-login-name))))
2365            (while (string-match "[^a-z0-9_]" user)
2366              (aset user (match-beginning 0) ?_))
2367            user)
2368        (message-number-base36 (user-uid) -1))
2369      (message-number-base36 (+ (car   tm)
2370                                (lsh (% message-unique-id-char 25) 16)) 4)
2371      (message-number-base36 (+ (nth 1 tm)
2372                                (lsh (/ message-unique-id-char 25) 16)) 4)
2373      ;; Append the newsreader name, because while the generated
2374      ;; ID is unique to this newsreader, other newsreaders might
2375      ;; otherwise generate the same ID via another algorithm.
2376      ".fsf")))
2377
2378 (defun message-number-base36 (num len)
2379   (if (if (< len 0)
2380           (<= num 0)
2381         (= len 0))
2382       ""
2383     (concat (message-number-base36 (/ num 36) (1- len))
2384             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2385                                   (% num 36))))))
2386
2387 (defun message-make-organization ()
2388   "Make an Organization header."
2389   (let* ((organization
2390           (or (getenv "ORGANIZATION")
2391               (when message-user-organization
2392                 (if (message-functionp message-user-organization)
2393                     (funcall message-user-organization)
2394                   message-user-organization)))))
2395     (save-excursion
2396       (message-set-work-buffer)
2397       (cond ((stringp organization)
2398              (insert organization))
2399             ((and (eq t organization)
2400                   message-user-organization-file
2401                   (file-exists-p message-user-organization-file))
2402              (insert-file-contents message-user-organization-file)))
2403       (goto-char (point-min))
2404       (while (re-search-forward "[\t\n]+" nil t)
2405         (replace-match "" t t))
2406       (unless (zerop (buffer-size))
2407         (buffer-string)))))
2408
2409 (defun message-make-lines ()
2410   "Count the number of lines and return numeric string."
2411   (save-excursion
2412     (save-restriction
2413       (widen)
2414       (goto-char (point-min))
2415       (re-search-forward
2416        (concat "^" (regexp-quote mail-header-separator) "$"))
2417       (forward-line 1)
2418       (int-to-string (count-lines (point) (point-max))))))
2419
2420 (defun message-make-in-reply-to ()
2421   "Return the In-Reply-To header for this message."
2422   (when message-reply-headers
2423     (let ((from (mail-header-from message-reply-headers))
2424           (date (mail-header-date message-reply-headers)))
2425       (when from
2426         (let ((stop-pos
2427                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2428           (concat (if stop-pos (substring from 0 stop-pos) from)
2429                   "'s message of "
2430                   (if (or (not date) (string= date ""))
2431                       "(unknown date)" date)))))))
2432
2433 (defun message-make-distribution ()
2434   "Make a Distribution header."
2435   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2436     (cond ((message-functionp message-distribution-function)
2437            (funcall message-distribution-function))
2438           (t orig-distribution))))
2439
2440 (defun message-make-expires ()
2441   "Return an Expires header based on `message-expires'."
2442   (let ((current (current-time))
2443         (future (* 1.0 message-expires 60 60 24)))
2444     ;; Add the future to current.
2445     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2446     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2447     ;; Return the date in the future in UT.
2448     (timezone-make-date-arpa-standard
2449      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2450
2451 (defun message-make-path ()
2452   "Return uucp path."
2453   (let ((login-name (user-login-name)))
2454     (cond ((null message-user-path)
2455            (concat (system-name) "!" login-name))
2456           ((stringp message-user-path)
2457            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2458            (concat message-user-path "!" login-name))
2459           (t login-name))))
2460
2461 (defun message-make-from ()
2462   "Make a From header."
2463   (let* ((style message-from-style)
2464          (login (message-make-address))
2465          (fullname
2466           (or (and (boundp 'user-full-name)
2467                    user-full-name)
2468               (user-full-name))))
2469     (when (string= fullname "&")
2470       (setq fullname (user-login-name)))
2471     (save-excursion
2472       (message-set-work-buffer)
2473       (cond
2474        ((or (null style)
2475             (equal fullname ""))
2476         (insert login))
2477        ((or (eq style 'angles)
2478             (and (not (eq style 'parens))
2479                  ;; Use angles if no quoting is needed, or if parens would
2480                  ;; need quoting too.
2481                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2482                      (let ((tmp (concat fullname nil)))
2483                        (while (string-match "([^()]*)" tmp)
2484                          (aset tmp (match-beginning 0) ?-)
2485                          (aset tmp (1- (match-end 0)) ?-))
2486                        (string-match "[\\()]" tmp)))))
2487         (insert fullname)
2488         (goto-char (point-min))
2489         ;; Look for a character that cannot appear unquoted
2490         ;; according to RFC 822.
2491         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2492           ;; Quote fullname, escaping specials.
2493           (goto-char (point-min))
2494           (insert "\"")
2495           (while (re-search-forward "[\"\\]" nil 1)
2496             (replace-match "\\\\\\&" t))
2497           (insert "\""))
2498         (insert " <" login ">"))
2499        (t                               ; 'parens or default
2500         (insert login " (")
2501         (let ((fullname-start (point)))
2502           (insert fullname)
2503           (goto-char fullname-start)
2504           ;; RFC 822 says \ and nonmatching parentheses
2505           ;; must be escaped in comments.
2506           ;; Escape every instance of ()\ ...
2507           (while (re-search-forward "[()\\]" nil 1)
2508             (replace-match "\\\\\\&" t))
2509           ;; ... then undo escaping of matching parentheses,
2510           ;; including matching nested parentheses.
2511           (goto-char fullname-start)
2512           (while (re-search-forward
2513                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2514                   nil 1)
2515             (replace-match "\\1(\\3)" t)
2516             (goto-char fullname-start)))
2517         (insert ")")))
2518       (buffer-string))))
2519
2520 (defun message-make-sender ()
2521   "Return the \"real\" user address.
2522 This function tries to ignore all user modifications, and
2523 give as trustworthy answer as possible."
2524   (concat (user-login-name) "@" (system-name)))
2525
2526 (defun message-make-address ()
2527   "Make the address of the user."
2528   (or (message-user-mail-address)
2529       (concat (user-login-name) "@" (message-make-domain))))
2530
2531 (defun message-user-mail-address ()
2532   "Return the pertinent part of `user-mail-address'."
2533   (when user-mail-address
2534     (if (string-match " " user-mail-address)
2535         (nth 1 (mail-extract-address-components user-mail-address))
2536       user-mail-address)))
2537
2538 (defun message-make-fqdn ()
2539   "Return user's fully qualified domain name."
2540   (let ((system-name (system-name))
2541         (user-mail (message-user-mail-address)))
2542     (cond
2543      ((string-match "[^.]\\.[^.]" system-name)
2544       ;; `system-name' returned the right result.
2545       system-name)
2546      ;; Try `mail-host-address'.
2547      ((and (boundp 'mail-host-address)
2548            (stringp mail-host-address)
2549            (string-match "\\." mail-host-address))
2550       mail-host-address)
2551      ;; We try `user-mail-address' as a backup.
2552      ((and (string-match "\\." user-mail)
2553            (string-match "@\\(.*\\)\\'" user-mail))
2554       (match-string 1 user-mail))
2555      ;; Default to this bogus thing.
2556      (t
2557       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2558
2559 (defun message-make-host-name ()
2560   "Return the name of the host."
2561   (let ((fqdn (message-make-fqdn)))
2562     (string-match "^[^.]+\\." fqdn)
2563     (substring fqdn 0 (1- (match-end 0)))))
2564
2565 (defun message-make-domain ()
2566   "Return the domain name."
2567   (or mail-host-address
2568       (message-make-fqdn)))
2569
2570 (defun message-generate-headers (headers)
2571   "Prepare article HEADERS.
2572 Headers already prepared in the buffer are not modified."
2573   (save-restriction
2574     (message-narrow-to-headers)
2575     (let* ((Date (message-make-date))
2576            (Message-ID (message-make-message-id))
2577            (Organization (message-make-organization))
2578            (From (message-make-from))
2579            (Path (message-make-path))
2580            (Subject nil)
2581            (Newsgroups nil)
2582            (In-Reply-To (message-make-in-reply-to))
2583            (To nil)
2584            (Distribution (message-make-distribution))
2585            (Lines (message-make-lines))
2586            (X-Newsreader message-newsreader)
2587            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2588                           message-mailer))
2589            (Expires (message-make-expires))
2590            (case-fold-search t)
2591            header value elem)
2592       ;; First we remove any old generated headers.
2593       (let ((headers message-deletable-headers))
2594         (while headers
2595           (goto-char (point-min))
2596           (and (re-search-forward
2597                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2598                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2599                (message-delete-line))
2600           (pop headers)))
2601       ;; Go through all the required headers and see if they are in the
2602       ;; articles already.  If they are not, or are empty, they are
2603       ;; inserted automatically - except for Subject, Newsgroups and
2604       ;; Distribution.
2605       (while headers
2606         (goto-char (point-min))
2607         (setq elem (pop headers))
2608         (if (consp elem)
2609             (if (eq (car elem) 'optional)
2610                 (setq header (cdr elem))
2611               (setq header (car elem)))
2612           (setq header elem))
2613         (when (or (not (re-search-forward
2614                         (concat "^" (downcase (symbol-name header)) ":")
2615                         nil t))
2616                   (progn
2617                     ;; The header was found.  We insert a space after the
2618                     ;; colon, if there is none.
2619                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2620                     ;; Find out whether the header is empty...
2621                     (looking-at "[ \t]*$")))
2622           ;; So we find out what value we should insert.
2623           (setq value
2624                 (cond
2625                  ((and (consp elem) (eq (car elem) 'optional))
2626                   ;; This is an optional header.  If the cdr of this
2627                   ;; is something that is nil, then we do not insert
2628                   ;; this header.
2629                   (setq header (cdr elem))
2630                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2631                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2632                  ((consp elem)
2633                   ;; The element is a cons.  Either the cdr is a
2634                   ;; string to be inserted verbatim, or it is a
2635                   ;; function, and we insert the value returned from
2636                   ;; this function.
2637                   (or (and (stringp (cdr elem)) (cdr elem))
2638                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2639                  ((and (boundp header) (symbol-value header))
2640                   ;; The element is a symbol.  We insert the value
2641                   ;; of this symbol, if any.
2642                   (symbol-value header))
2643                  (t
2644                   ;; We couldn't generate a value for this header,
2645                   ;; so we just ask the user.
2646                   (read-from-minibuffer
2647                    (format "Empty header for %s; enter value: " header)))))
2648           ;; Finally insert the header.
2649           (when (and value
2650                      (not (equal value "")))
2651             (save-excursion
2652               (if (bolp)
2653                   (progn
2654                     ;; This header didn't exist, so we insert it.
2655                     (goto-char (point-max))
2656                     (insert (symbol-name header) ": " value "\n")
2657                     (forward-line -1))
2658                 ;; The value of this header was empty, so we clear
2659                 ;; totally and insert the new value.
2660                 (delete-region (point) (gnus-point-at-eol))
2661                 (insert value))
2662               ;; Add the deletable property to the headers that require it.
2663               (and (memq header message-deletable-headers)
2664                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2665                    (add-text-properties
2666                     (point) (match-end 0)
2667                     '(message-deletable t face italic) (current-buffer)))))))
2668       ;; Insert new Sender if the From is strange.
2669       (let ((from (message-fetch-field "from"))
2670             (sender (message-fetch-field "sender"))
2671             (secure-sender (message-make-sender)))
2672         (when (and from
2673                    (not (message-check-element 'sender))
2674                    (not (string=
2675                          (downcase
2676                           (cadr (mail-extract-address-components from)))
2677                          (downcase secure-sender)))
2678                    (or (null sender)
2679                        (not
2680                         (string=
2681                          (downcase
2682                           (cadr (mail-extract-address-components sender)))
2683                          (downcase secure-sender)))))
2684           (goto-char (point-min))
2685           ;; Rename any old Sender headers to Original-Sender.
2686           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2687             (beginning-of-line)
2688             (insert "Original-")
2689             (beginning-of-line))
2690           (insert "Sender: " secure-sender "\n"))))))
2691
2692 (defun message-insert-courtesy-copy ()
2693   "Insert a courtesy message in mail copies of combined messages."
2694   (let (newsgroups)
2695     (save-excursion
2696       (save-restriction
2697         (message-narrow-to-headers)
2698         (when (setq newsgroups (message-fetch-field "newsgroups"))
2699           (goto-char (point-max))
2700           (insert "Posted-To: " newsgroups "\n")))
2701       (forward-line 1)
2702       (when message-courtesy-message
2703         (cond
2704          ((string-match "%s" message-courtesy-message)
2705           (insert (format message-courtesy-message newsgroups)))
2706          (t
2707           (insert message-courtesy-message)))))))
2708
2709 ;;;
2710 ;;; Setting up a message buffer
2711 ;;;
2712
2713 (defun message-fill-address (header value)
2714   (save-restriction
2715     (narrow-to-region (point) (point))
2716     (insert (capitalize (symbol-name header))
2717             ": "
2718             (if (consp value) (car value) value)
2719             "\n")
2720     (narrow-to-region (point-min) (1- (point-max)))
2721     (let (quoted last)
2722       (goto-char (point-min))
2723       (while (not (eobp))
2724         (skip-chars-forward "^,\"" (point-max))
2725         (if (or (= (following-char) ?,)
2726                 (eobp))
2727             (when (not quoted)
2728               (if (and (> (current-column) 78)
2729                        last)
2730                   (progn
2731                     (save-excursion
2732                       (goto-char last)
2733                       (insert "\n\t"))
2734                     (setq last (1+ (point))))
2735                 (setq last (1+ (point)))))
2736           (setq quoted (not quoted)))
2737         (unless (eobp)
2738           (forward-char 1))))
2739     (goto-char (point-max))
2740     (widen)
2741     (forward-line 1)))
2742
2743 (defun message-fill-header (header value)
2744   (let ((begin (point))
2745         (fill-column 78)
2746         (fill-prefix "\t"))
2747     (insert (capitalize (symbol-name header))
2748             ": "
2749             (if (consp value) (car value) value)
2750             "\n")
2751     (save-restriction
2752       (narrow-to-region begin (point))
2753       (fill-region-as-paragraph begin (point))
2754       ;; Tapdance around looong Message-IDs.
2755       (forward-line -1)
2756       (when (looking-at "[ \t]*$")
2757         (message-delete-line))
2758       (goto-char begin)
2759       (re-search-forward ":" nil t)
2760       (when (looking-at "\n[ \t]+")
2761         (replace-match " " t t))
2762       (goto-char (point-max)))))
2763
2764 (defun message-position-point ()
2765   "Move point to where the user probably wants to find it."
2766   (message-narrow-to-headers)
2767   (cond
2768    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2769     (search-backward ":" )
2770     (widen)
2771     (forward-char 1)
2772     (if (= (following-char) ? )
2773         (forward-char 1)
2774       (insert " ")))
2775    (t
2776     (goto-char (point-max))
2777     (widen)
2778     (forward-line 1)
2779     (unless (looking-at "$")
2780       (forward-line 2)))
2781    (sit-for 0)))
2782
2783 (defun message-buffer-name (type &optional to group)
2784   "Return a new (unique) buffer name based on TYPE and TO."
2785   (cond
2786    ;; Check whether `message-generate-new-buffers' is a function,
2787    ;; and if so, call it.
2788    ((message-functionp message-generate-new-buffers)
2789     (funcall message-generate-new-buffers type to group))
2790    ;; Generate a new buffer name The Message Way.
2791    (message-generate-new-buffers
2792     (generate-new-buffer-name
2793      (concat "*" type
2794              (if to
2795                  (concat " to "
2796                          (or (car (mail-extract-address-components to))
2797                              to) "")
2798                "")
2799              (if (and group (not (string= group ""))) (concat " on " group) "")
2800              "*")))
2801    ;; Use standard name.
2802    (t
2803     (format "*%s message*" type))))
2804
2805 (defun message-pop-to-buffer (name)
2806   "Pop to buffer NAME, and warn if it already exists and is modified."
2807   (let ((buffer (get-buffer name)))
2808     (if (and buffer
2809              (buffer-name buffer))
2810         (progn
2811           (set-buffer (pop-to-buffer buffer))
2812           (when (and (buffer-modified-p)
2813                      (not (y-or-n-p
2814                            "Message already being composed; erase? ")))
2815             (error "Message being composed")))
2816       (set-buffer (pop-to-buffer name))))
2817   (erase-buffer)
2818   (message-mode))
2819
2820 (defun message-do-send-housekeeping ()
2821   "Kill old message buffers."
2822   ;; We might have sent this buffer already.  Delete it from the
2823   ;; list of buffers.
2824   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2825   (while (and message-max-buffers
2826               message-buffer-list
2827               (>= (length message-buffer-list) message-max-buffers))
2828     ;; Kill the oldest buffer -- unless it has been changed.
2829     (let ((buffer (pop message-buffer-list)))
2830       (when (and (buffer-name buffer)
2831                  (not (buffer-modified-p buffer)))
2832         (kill-buffer buffer))))
2833   ;; Rename the buffer.
2834   (if message-send-rename-function
2835       (funcall message-send-rename-function)
2836     (when (string-match "\\`\\*" (buffer-name))
2837       (rename-buffer
2838        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2839   ;; Push the current buffer onto the list.
2840   (when message-max-buffers
2841     (setq message-buffer-list
2842           (nconc message-buffer-list (list (current-buffer))))))
2843
2844 (defvar mc-modes-alist)
2845 (defun message-setup (headers &optional replybuffer actions)
2846   (when (and (boundp 'mc-modes-alist)
2847              (not (assq 'message-mode mc-modes-alist)))
2848     (push '(message-mode (encrypt . mc-encrypt-message)
2849                          (sign . mc-sign-message))
2850           mc-modes-alist))
2851   (when actions
2852     (setq message-send-actions actions))
2853   (setq message-reply-buffer replybuffer)
2854   (goto-char (point-min))
2855   ;; Insert all the headers.
2856   (mail-header-format
2857    (let ((h headers)
2858          (alist message-header-format-alist))
2859      (while h
2860        (unless (assq (caar h) message-header-format-alist)
2861          (push (list (caar h)) alist))
2862        (pop h))
2863      alist)
2864    headers)
2865   (delete-region (point) (progn (forward-line -1) (point)))
2866   (when message-default-headers
2867     (insert message-default-headers))
2868   (put-text-property
2869    (point)
2870    (progn
2871      (insert mail-header-separator "\n")
2872      (1- (point)))
2873    'read-only nil)
2874   (forward-line -1)
2875   (when (message-news-p)
2876     (when message-default-news-headers
2877       (insert message-default-news-headers))
2878     (when message-generate-headers-first
2879       (message-generate-headers
2880        (delq 'Lines
2881              (delq 'Subject
2882                    (copy-sequence message-required-news-headers))))))
2883   (when (message-mail-p)
2884     (when message-default-mail-headers
2885       (insert message-default-mail-headers))
2886     (when message-generate-headers-first
2887       (message-generate-headers
2888        (delq 'Lines
2889              (delq 'Subject
2890                    (copy-sequence message-required-mail-headers))))))
2891   (run-hooks 'message-signature-setup-hook)
2892   (message-insert-signature)
2893   (message-set-auto-save-file-name)
2894   (save-restriction
2895     (message-narrow-to-headers)
2896     (run-hooks 'message-header-setup-hook))
2897   (set-buffer-modified-p nil)
2898   (run-hooks 'message-setup-hook)
2899   (message-position-point)
2900   (undo-boundary))
2901
2902 (defun message-set-auto-save-file-name ()
2903   "Associate the message buffer with a file in the drafts directory."
2904   (when message-autosave-directory
2905     (unless (file-exists-p message-autosave-directory)
2906       (make-directory message-autosave-directory t))
2907     (let ((name (make-temp-name
2908                  (expand-file-name
2909                   (concat (file-name-as-directory message-autosave-directory)
2910                           "msg.")))))
2911       (setq buffer-auto-save-file-name
2912             (save-excursion
2913               (prog1
2914                   (progn
2915                     (set-buffer (get-buffer-create " *draft tmp*"))
2916                     (setq buffer-file-name name)
2917                     (make-auto-save-file-name))
2918                 (kill-buffer (current-buffer)))))
2919       (clear-visited-file-modtime))))
2920
2921 \f
2922
2923 ;;;
2924 ;;; Commands for interfacing with message
2925 ;;;
2926
2927 ;;;###autoload
2928 (defun message-mail (&optional to subject
2929                                other-headers continue switch-function
2930                                yank-action send-actions)
2931   "Start editing a mail message to be sent."
2932   (interactive)
2933   (let ((message-this-is-mail t))
2934     (message-pop-to-buffer (message-buffer-name "mail" to))
2935     (message-setup
2936      (nconc
2937       `((To . ,(or to "")) (Subject . ,(or subject "")))
2938       (when other-headers other-headers)))))
2939
2940 ;;;###autoload
2941 (defun message-news (&optional newsgroups subject)
2942   "Start editing a news article to be sent."
2943   (interactive)
2944   (let ((message-this-is-news t))
2945     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2946     (message-setup `((Newsgroups . ,(or newsgroups ""))
2947                      (Subject . ,(or subject ""))))))
2948
2949 ;;;###autoload
2950 (defun message-reply (&optional to-address wide ignore-reply-to)
2951   "Start editing a reply to the article in the current buffer."
2952   (interactive)
2953   (let ((cur (current-buffer))
2954         from subject date reply-to to cc
2955         references message-id follow-to
2956         (inhibit-point-motion-hooks t)
2957         mct never-mct gnus-warning)
2958     (save-restriction
2959       (message-narrow-to-head)
2960       ;; Allow customizations to have their say.
2961       (if (not wide)
2962           ;; This is a regular reply.
2963           (if (message-functionp message-reply-to-function)
2964               (setq follow-to (funcall message-reply-to-function)))
2965         ;; This is a followup.
2966         (if (message-functionp message-wide-reply-to-function)
2967             (save-excursion
2968               (setq follow-to
2969                     (funcall message-wide-reply-to-function)))))
2970       ;; Find all relevant headers we need.
2971       (setq from (message-fetch-field "from")
2972             date (message-fetch-field "date")
2973             subject (or (message-fetch-field "subject") "none")
2974             to (message-fetch-field "to")
2975             cc (message-fetch-field "cc")
2976             mct (message-fetch-field "mail-copies-to")
2977             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2978             references (message-fetch-field "references")
2979             message-id (message-fetch-field "message-id" t))
2980       ;; Remove any (buggy) Re:'s that are present and make a
2981       ;; proper one.
2982       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2983         (setq subject (substring subject (match-end 0))))
2984       (setq subject (concat "Re: " subject))
2985
2986       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2987                  (string-match "<[^>]+>" gnus-warning))
2988         (setq message-id (match-string 0 gnus-warning)))
2989
2990       ;; Handle special values of Mail-Copies-To.
2991       (when mct
2992         (cond ((equal (downcase mct) "never")
2993                (setq never-mct t)
2994                (setq mct nil))
2995               ((equal (downcase mct) "always")
2996                (setq mct (or reply-to from)))))
2997
2998       (unless follow-to
2999         (if (or (not wide)
3000                 to-address)
3001             (setq follow-to (list (cons 'To (or to-address reply-to from))))
3002           (let (ccalist)
3003             (save-excursion
3004               (message-set-work-buffer)
3005               (unless never-mct
3006                 (insert (or reply-to from "")))
3007               (insert (if (bolp) "" ", ") (or to ""))
3008               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3009               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3010               (goto-char (point-min))
3011               (while (re-search-forward "[ \t]+" nil t)
3012                 (replace-match " " t t))
3013               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3014               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3015                         (erase-buffer)))
3016               (goto-char (point-min))
3017               ;; Perhaps Mail-Copies-To: never removed the only address?
3018               (when (eobp)
3019                 (insert (or reply-to from "")))
3020               (setq ccalist
3021                     (mapcar
3022                      (lambda (addr)
3023                        (cons (mail-strip-quoted-names addr) addr))
3024                      (message-tokenize-header (buffer-string))))
3025               (let ((s ccalist))
3026                 (while s
3027                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3028             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3029             (when ccalist
3030               (let ((ccs (cons 'Cc (mapconcat
3031                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3032                 (when (string-match "^ +" (cdr ccs))
3033                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3034                 (push ccs follow-to))))))
3035       (widen))
3036
3037     (message-pop-to-buffer (message-buffer-name
3038                             (if wide "wide reply" "reply") from
3039                             (if wide to-address nil)))
3040
3041     (setq message-reply-headers
3042           (vector 0 subject from date message-id references 0 0 ""))
3043
3044     (message-setup
3045      `((Subject . ,subject)
3046        ,@follow-to
3047        ,@(if (or references message-id)
3048              `((References . ,(concat (or references "") (and references " ")
3049                                       (or message-id ""))))
3050            nil))
3051      cur)))
3052
3053 ;;;###autoload
3054 (defun message-wide-reply (&optional to-address)
3055   "Make a \"wide\" reply to the message in the current buffer."
3056   (interactive)
3057   (message-reply to-address t))
3058
3059 ;;;###autoload
3060 (defun message-followup (&optional to-newsgroups)
3061   "Follow up to the message in the current buffer.
3062 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3063   (interactive)
3064   (let ((cur (current-buffer))
3065         from subject date reply-to mct
3066         references message-id follow-to
3067         (inhibit-point-motion-hooks t)
3068         (message-this-is-news t)
3069         followup-to distribution newsgroups gnus-warning posted-to)
3070     (save-restriction
3071       (narrow-to-region
3072        (goto-char (point-min))
3073        (if (search-forward "\n\n" nil t)
3074            (1- (point))
3075          (point-max)))
3076       (when (message-functionp message-followup-to-function)
3077         (setq follow-to
3078               (funcall message-followup-to-function)))
3079       (setq from (message-fetch-field "from")
3080             date (message-fetch-field "date")
3081             subject (or (message-fetch-field "subject") "none")
3082             references (message-fetch-field "references")
3083             message-id (message-fetch-field "message-id" t)
3084             followup-to (message-fetch-field "followup-to")
3085             newsgroups (message-fetch-field "newsgroups")
3086             posted-to (message-fetch-field "posted-to")
3087             reply-to (message-fetch-field "reply-to")
3088             distribution (message-fetch-field "distribution")
3089             mct (message-fetch-field "mail-copies-to"))
3090       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3091                  (string-match "<[^>]+>" gnus-warning))
3092         (setq message-id (match-string 0 gnus-warning)))
3093       ;; Remove bogus distribution.
3094       (when (and (stringp distribution)
3095                  (let ((case-fold-search t))
3096                    (string-match "world" distribution)))
3097         (setq distribution nil))
3098       ;; Remove any (buggy) Re:'s that are present and make a
3099       ;; proper one.
3100       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3101         (setq subject (substring subject (match-end 0))))
3102       (setq subject (concat "Re: " subject))
3103       (widen))
3104
3105     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3106
3107     (message-setup
3108      `((Subject . ,subject)
3109        ,@(cond
3110           (to-newsgroups
3111            (list (cons 'Newsgroups to-newsgroups)))
3112           (follow-to follow-to)
3113           ((and followup-to message-use-followup-to)
3114            (list
3115             (cond
3116              ((equal (downcase followup-to) "poster")
3117               (if (or (eq message-use-followup-to 'use)
3118                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3119 You should normally obey the Followup-To: header.
3120
3121 `Followup-To: poster' sends your response via e-mail instead of news.
3122
3123 A typical situation where `Followup-To: poster' is used is when the poster
3124 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3125                   (progn
3126                     (setq message-this-is-news nil)
3127                     (cons 'To (or reply-to from "")))
3128                 (cons 'Newsgroups newsgroups)))
3129              (t
3130               (if (or (equal followup-to newsgroups)
3131                       (not (eq message-use-followup-to 'ask))
3132                       (message-y-or-n-p
3133                        (concat "Obey Followup-To: " followup-to "? ") t "\
3134 You should normally obey the Followup-To: header.
3135
3136         `Followup-To: " followup-to "'
3137 directs your response to " (if (string-match "," followup-to)
3138                                "the specified newsgroups"
3139                              "that newsgroup only") ".
3140
3141 If a message is posted to several newsgroups, Followup-To is often
3142 used to direct the following discussion to one newsgroup only,
3143 because discussions that are spread over several newsgroup tend to
3144 be fragmented and very difficult to follow.
3145
3146 Also, some source/announcement newsgroups are not indented for discussion;
3147 responses here are directed to other newsgroups."))
3148                   (cons 'Newsgroups followup-to)
3149                 (cons 'Newsgroups newsgroups))))))
3150           (posted-to
3151            `((Newsgroups . ,posted-to)))
3152           (t
3153            `((Newsgroups . ,newsgroups))))
3154        ,@(and distribution (list (cons 'Distribution distribution)))
3155        ,@(if (or references message-id)
3156              `((References . ,(concat (or references "") (and references " ")
3157                                       (or message-id "")))))
3158        ,@(when (and mct
3159                     (not (equal (downcase mct) "never")))
3160            (list (cons 'Cc (if (equal (downcase mct) "always")
3161                                (or reply-to from "")
3162                              mct)))))
3163
3164      cur)
3165
3166     (setq message-reply-headers
3167           (vector 0 subject from date message-id references 0 0 ""))))
3168
3169
3170 ;;;###autoload
3171 (defun message-cancel-news ()
3172   "Cancel an article you posted."
3173   (interactive)
3174   (unless (message-news-p)
3175     (error "This is not a news article; canceling is impossible"))
3176   (when (yes-or-no-p "Do you really want to cancel this article? ")
3177     (let (from newsgroups message-id distribution buf)
3178       (save-excursion
3179         ;; Get header info. from original article.
3180         (save-restriction
3181           (message-narrow-to-head)
3182           (setq from (message-fetch-field "from")
3183                 newsgroups (message-fetch-field "newsgroups")
3184                 message-id (message-fetch-field "message-id" t)
3185                 distribution (message-fetch-field "distribution")))
3186         ;; Make sure that this article was written by the user.
3187         (unless (string-equal
3188                  (downcase (cadr (mail-extract-address-components from)))
3189                  (downcase (message-make-address)))
3190           (error "This article is not yours"))
3191         ;; Make control message.
3192         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3193         (buffer-disable-undo (current-buffer))
3194         (erase-buffer)
3195         (insert "Newsgroups: " newsgroups "\n"
3196                 "From: " (message-make-from) "\n"
3197                 "Subject: cmsg cancel " message-id "\n"
3198                 "Control: cancel " message-id "\n"
3199                 (if distribution
3200                     (concat "Distribution: " distribution "\n")
3201                   "")
3202                 mail-header-separator "\n"
3203                 message-cancel-message)
3204         (message "Canceling your article...")
3205         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
3206           (funcall message-send-news-function))
3207         (message "Canceling your article...done")
3208         (kill-buffer buf)))))
3209
3210 ;;;###autoload
3211 (defun message-supersede ()
3212   "Start composing a message to supersede the current message.
3213 This is done simply by taking the old article and adding a Supersedes
3214 header line with the old Message-ID."
3215   (interactive)
3216   (let ((cur (current-buffer)))
3217     ;; Check whether the user owns the article that is to be superseded.
3218     (unless (string-equal
3219              (downcase (cadr (mail-extract-address-components
3220                               (message-fetch-field "from"))))
3221              (downcase (message-make-address)))
3222       (error "This article is not yours"))
3223     ;; Get a normal message buffer.
3224     (message-pop-to-buffer (message-buffer-name "supersede"))
3225     (insert-buffer-substring cur)
3226     (message-narrow-to-head)
3227     ;; Remove unwanted headers.
3228     (when message-ignored-supersedes-headers
3229       (message-remove-header message-ignored-supersedes-headers t))
3230     (goto-char (point-min))
3231     (if (not (re-search-forward "^Message-ID: " nil t))
3232         (error "No Message-ID in this article")
3233       (replace-match "Supersedes: " t t))
3234     (goto-char (point-max))
3235     (insert mail-header-separator)
3236     (widen)
3237     (forward-line 1)))
3238
3239 ;;;###autoload
3240 (defun message-recover ()
3241   "Reread contents of current buffer from its last auto-save file."
3242   (interactive)
3243   (let ((file-name (make-auto-save-file-name)))
3244     (cond ((save-window-excursion
3245              (if (not (eq system-type 'vax-vms))
3246                  (with-output-to-temp-buffer "*Directory*"
3247                    (buffer-disable-undo standard-output)
3248                    (let ((default-directory "/"))
3249                      (call-process
3250                       "ls" nil standard-output nil "-l" file-name))))
3251              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3252            (let ((buffer-read-only nil))
3253              (erase-buffer)
3254              (insert-file-contents file-name nil)))
3255           (t (error "message-recover cancelled")))))
3256
3257 ;;; Forwarding messages.
3258
3259 (defun message-make-forward-subject ()
3260   "Return a Subject header suitable for the message in the current buffer."
3261   (save-excursion
3262     (save-restriction
3263       (current-buffer)
3264       (message-narrow-to-head)
3265       (concat "[" (or (message-fetch-field
3266                        (if (message-news-p) "newsgroups" "from"))
3267                       "(nowhere)")
3268               "] " (or (message-fetch-field "Subject") "")))))
3269
3270 ;;;###autoload
3271 (defun message-forward (&optional news)
3272   "Forward the current message via mail.
3273 Optional NEWS will use news to forward instead of mail."
3274   (interactive "P")
3275   (let ((cur (current-buffer))
3276         (subject (message-make-forward-subject))
3277         art-beg)
3278     (if news (message-news nil subject) (message-mail nil subject))
3279     ;; Put point where we want it before inserting the forwarded
3280     ;; message.
3281     (if message-signature-before-forwarded-message
3282         (goto-char (point-max))
3283       (message-goto-body))
3284     ;; Make sure we're at the start of the line.
3285     (unless (eolp)
3286       (insert "\n"))
3287     ;; Narrow to the area we are to insert.
3288     (narrow-to-region (point) (point))
3289     ;; Insert the separators and the forwarded buffer.
3290     (insert message-forward-start-separator)
3291     (setq art-beg (point))
3292     (insert-buffer-substring cur)
3293     (goto-char (point-max))
3294     (insert message-forward-end-separator)
3295     (set-text-properties (point-min) (point-max) nil)
3296     ;; Remove all unwanted headers.
3297     (goto-char art-beg)
3298     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3299                                   (1- (point))
3300                                 (point)))
3301     (goto-char (point-min))
3302     (message-remove-header message-included-forward-headers t nil t)
3303     (widen)
3304     (message-position-point)))
3305
3306 ;;;###autoload
3307 (defun message-resend (address)
3308   "Resend the current article to ADDRESS."
3309   (interactive "sResend message to: ")
3310   (message "Resending message to %s..." address)
3311   (save-excursion
3312     (let ((cur (current-buffer))
3313           beg)
3314       ;; We first set up a normal mail buffer.
3315       (set-buffer (get-buffer-create " *message resend*"))
3316       (buffer-disable-undo (current-buffer))
3317       (erase-buffer)
3318       (message-setup `((To . ,address)))
3319       ;; Insert our usual headers.
3320       (message-generate-headers '(From Date To))
3321       (message-narrow-to-headers)
3322       ;; Rename them all to "Resent-*".
3323       (while (re-search-forward "^[A-Za-z]" nil t)
3324         (forward-char -1)
3325         (insert "Resent-"))
3326       (widen)
3327       (forward-line)
3328       (delete-region (point) (point-max))
3329       (setq beg (point))
3330       ;; Insert the message to be resent.
3331       (insert-buffer-substring cur)
3332       (goto-char (point-min))
3333       (search-forward "\n\n")
3334       (forward-char -1)
3335       (save-restriction
3336         (narrow-to-region beg (point))
3337         (message-remove-header message-ignored-resent-headers t)
3338         (goto-char (point-max)))
3339       (insert mail-header-separator)
3340       ;; Rename all old ("Also-")Resent headers.
3341       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3342         (beginning-of-line)
3343         (insert "Also-"))
3344       ;; Quote any "From " lines at the beginning.
3345       (goto-char beg)
3346       (when (looking-at "From ")
3347         (replace-match "X-From-Line: "))
3348       ;; Send it.
3349       (message-send-mail)
3350       (kill-buffer (current-buffer)))
3351     (message "Resending message to %s...done" address)))
3352
3353 ;;;###autoload
3354 (defun message-bounce ()
3355   "Re-mail the current message.
3356 This only makes sense if the current message is a bounce message than
3357 contains some mail you have written which has been bounced back to
3358 you."
3359   (interactive)
3360   (let ((cur (current-buffer))
3361         boundary)
3362     (message-pop-to-buffer (message-buffer-name "bounce"))
3363     (insert-buffer-substring cur)
3364     (undo-boundary)
3365     (message-narrow-to-head)
3366     (if (and (message-fetch-field "Mime-Version")
3367              (setq boundary (message-fetch-field "Content-Type")))
3368         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3369             (setq boundary (concat (match-string 1 boundary) " *\n"
3370                                    "Content-Type: message/rfc822"))
3371           (setq boundary nil)))
3372     (widen)
3373     (goto-char (point-min))
3374     (search-forward "\n\n" nil t)
3375     (or (and boundary
3376              (re-search-forward boundary nil t)
3377              (forward-line 2))
3378         (and (re-search-forward message-unsent-separator nil t)
3379              (forward-line 1))
3380         (and (search-forward "\n\n" nil t)
3381              (re-search-forward "^Return-Path:.*\n" nil t)))
3382     ;; We remove everything before the bounced mail.
3383     (delete-region
3384      (point-min)
3385      (if (re-search-forward "^[^ \n\t]+:" nil t)
3386          (match-beginning 0)
3387        (point)))
3388     (save-restriction
3389       (message-narrow-to-head)
3390       (message-remove-header message-ignored-bounced-headers t)
3391       (goto-char (point-max))
3392       (insert mail-header-separator))
3393     (message-position-point)))
3394
3395 ;;;
3396 ;;; Interactive entry points for new message buffers.
3397 ;;;
3398
3399 ;;;###autoload
3400 (defun message-mail-other-window (&optional to subject)
3401   "Like `message-mail' command, but display mail buffer in another window."
3402   (interactive)
3403   (let ((pop-up-windows t)
3404         (special-display-buffer-names nil)
3405         (special-display-regexps nil)
3406         (same-window-buffer-names nil)
3407         (same-window-regexps nil))
3408     (message-pop-to-buffer (message-buffer-name "mail" to)))
3409   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3410
3411 ;;;###autoload
3412 (defun message-mail-other-frame (&optional to subject)
3413   "Like `message-mail' command, but display mail buffer in another frame."
3414   (interactive)
3415   (let ((pop-up-frames t)
3416         (special-display-buffer-names nil)
3417         (special-display-regexps nil)
3418         (same-window-buffer-names nil)
3419         (same-window-regexps nil))
3420     (message-pop-to-buffer (message-buffer-name "mail" to)))
3421   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3422
3423 ;;;###autoload
3424 (defun message-news-other-window (&optional newsgroups subject)
3425   "Start editing a news article to be sent."
3426   (interactive)
3427   (let ((pop-up-windows t)
3428         (special-display-buffer-names nil)
3429         (special-display-regexps nil)
3430         (same-window-buffer-names nil)
3431         (same-window-regexps nil))
3432     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3433   (message-setup `((Newsgroups . ,(or newsgroups ""))
3434                    (Subject . ,(or subject "")))))
3435
3436 ;;;###autoload
3437 (defun message-news-other-frame (&optional newsgroups subject)
3438   "Start editing a news article to be sent."
3439   (interactive)
3440   (let ((pop-up-frames t)
3441         (special-display-buffer-names nil)
3442         (special-display-regexps nil)
3443         (same-window-buffer-names nil)
3444         (same-window-regexps nil))
3445     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3446   (message-setup `((Newsgroups . ,(or newsgroups ""))
3447                    (Subject . ,(or subject "")))))
3448
3449 ;;; underline.el
3450
3451 ;; This code should be moved to underline.el (from which it is stolen).
3452
3453 ;;;###autoload
3454 (defun bold-region (start end)
3455   "Bold all nonblank characters in the region.
3456 Works by overstriking characters.
3457 Called from program, takes two arguments START and END
3458 which specify the range to operate on."
3459   (interactive "r")
3460   (save-excursion
3461     (let ((end1 (make-marker)))
3462       (move-marker end1 (max start end))
3463       (goto-char (min start end))
3464       (while (< (point) end1)
3465         (or (looking-at "[_\^@- ]")
3466             (insert (following-char) "\b"))
3467         (forward-char 1)))))
3468
3469 ;;;###autoload
3470 (defun unbold-region (start end)
3471   "Remove all boldness (overstruck characters) in the region.
3472 Called from program, takes two arguments START and END
3473 which specify the range to operate on."
3474   (interactive "r")
3475   (save-excursion
3476     (let ((end1 (make-marker)))
3477       (move-marker end1 (max start end))
3478       (goto-char (min start end))
3479       (while (re-search-forward "\b" end1 t)
3480         (if (eq (following-char) (char-after (- (point) 2)))
3481             (delete-char -2))))))
3482
3483 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3484
3485 ;; Support for toolbar
3486 (when (string-match "XEmacs\\|Lucid" emacs-version)
3487   (require 'messagexmas))
3488
3489 ;;; Group name completion.
3490
3491 (defvar message-newgroups-header-regexp
3492   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3493   "Regexp that match headers that lists groups.")
3494
3495 (defun message-tab ()
3496   "Expand group names in Newsgroups and Followup-To headers.
3497 Do a `tab-to-tab-stop' if not in those headers."
3498   (interactive)
3499   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3500         (mail-abbrev-in-expansion-header-p))
3501       (message-expand-group)
3502     (tab-to-tab-stop)))
3503
3504 (defvar gnus-active-hashtb)
3505 (defun message-expand-group ()
3506   (let* ((b (save-excursion
3507               (save-restriction
3508                 (narrow-to-region
3509                  (save-excursion
3510                    (beginning-of-line)
3511                    (skip-chars-forward "^:")
3512                    (1+ (point)))
3513                  (point))
3514                 (skip-chars-backward "^, \t\n") (point))))
3515          (completion-ignore-case t)
3516          (string (buffer-substring b (point)))
3517          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3518          (completions (all-completions string hashtb))
3519          (cur (current-buffer))
3520          comp)
3521     (delete-region b (point))
3522     (cond
3523      ((= (length completions) 1)
3524       (if (string= (car completions) string)
3525           (progn
3526             (insert string)
3527             (message "Only matching group"))
3528         (insert (car completions))))
3529      ((and (setq comp (try-completion string hashtb))
3530            (not (string= comp string)))
3531       (insert comp))
3532      (t
3533       (insert string)
3534       (if (not comp)
3535           (message "No matching groups")
3536         (pop-to-buffer "*Completions*")
3537         (buffer-disable-undo (current-buffer))
3538         (let ((buffer-read-only nil))
3539           (erase-buffer)
3540           (let ((standard-output (current-buffer)))
3541             (display-completion-list (sort completions 'string<)))
3542           (goto-char (point-min))
3543           (pop-to-buffer cur)))))))
3544
3545 ;;; Help stuff.
3546
3547 (defun message-talkative-question (ask question show &rest text)
3548   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.
3549 The following arguments may contain lists of values."
3550   (if (and show
3551            (setq text (message-flatten-list text)))
3552       (save-window-excursion
3553         (save-excursion
3554           (with-output-to-temp-buffer " *MESSAGE information message*"
3555             (set-buffer " *MESSAGE information message*")
3556             (mapcar 'princ text)
3557             (goto-char (point-min))))
3558         (funcall ask question))
3559     (funcall ask question)))
3560
3561 (defun message-flatten-list (list)
3562   "Return a new, flat list that contains all elements of LIST.
3563
3564 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3565 => (1 2 3 4 5 6 7)"
3566   (cond ((consp list)
3567          (apply 'append (mapcar 'message-flatten-list list)))
3568         (list
3569          (list list))))
3570
3571 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3572   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3573 Then clone the local variables and values from the old buffer to the
3574 new one, cloning only the locals having a substring matching the
3575 regexp varstr."
3576   (let ((oldlocals (buffer-local-variables)))
3577     (save-excursion
3578       (set-buffer (generate-new-buffer name))
3579       (mapcar (lambda (dude)
3580                 (when (and (car dude)
3581                            (or (not varstr)
3582                                (string-match varstr (symbol-name (car dude)))))
3583                   (ignore-errors
3584                     (set (make-local-variable (car dude))
3585                          (cdr dude)))))
3586               oldlocals)
3587       (current-buffer))))
3588
3589 (run-hooks 'message-load-hook)
3590
3591 (provide 'message)
3592
3593 ;;; message.el ends here