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