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