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