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