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