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