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