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